diff --git a/.do/deploy.template.yaml b/.do/deploy.template.yaml index 2a39445..8e43766 100644 --- a/.do/deploy.template.yaml +++ b/.do/deploy.template.yaml @@ -1,5 +1,10 @@ spec: name: cpdlc-server + # App Platform has no persistent disk, so the server keeps its data in a PostgreSQL database + databases: + - name: db + engine: PG + production: false services: - name: cpdlc-server instance_count: 1 @@ -13,16 +18,26 @@ spec: envs: - key: Logging__Level value: Information - - key: Acars__0__Type - value: Hoppie - - key: Acars__0__FlightSimulationNetwork - value: VATSIM - - key: Acars__0__StationIdentifier - value: CHANGE_ME - - key: Acars__0__Url - value: http://www.hoppie.nl/acars/system/connect.html - - key: Acars__0__AuthenticationCode - value: CHANGE_ME + - key: DatabaseProvider + value: PostgreSql + - key: DatabaseConnectionString + scope: RUN_TIME + value: ${db.DATABASE_URL} + + # You must set the master key before you deploy. Without it, the server does not start. + # Make a key with: openssl rand -base64 32 + # Keep a copy of the key in a safe place. If the key changes, you must enter the ACARS authentication codes again. + - key: MasterKey + scope: RUN_TIME type: SECRET - - key: Handoff__NotificationLeadTime - value: "10" + value: "" + + # You must set the VATSIM Connect client before you deploy. Without it, the server does not start. + # Set the redirect URL of the client to https:///signin-vatsim + - key: VatsimConnect__ClientId + scope: RUN_TIME + value: "" + - key: VatsimConnect__ClientSecret + scope: RUN_TIME + type: SECRET + value: "" diff --git a/.fallout/build.schema.json b/.fallout/build.schema.json index a4dd618..b351094 100644 --- a/.fallout/build.schema.json +++ b/.fallout/build.schema.json @@ -24,6 +24,8 @@ "ExecutableTarget": { "type": "string", "enum": [ + "AddMigration", + "AddNuGetSource", "CheckVersion", "CompilePlugin", "CompileServer", @@ -126,11 +128,28 @@ ], "description": "Configuration to build - Default is 'Debug' (local) or 'Release' (server)" }, + "ForceVersion": { + "type": "string", + "description": "Version to use instead of the GitVersion version, for example 1.0.0-rc1" + }, "GitHubToken": { "type": "string", "description": "GitHub token for creating releases", "default": "Secrets must be entered via 'fallout :secrets [profile]'" }, + "MigrationName": { + "type": "string", + "description": "Name of the migration to add" + }, + "NuGetToken": { + "type": "string", + "description": "GitHub personal access token (classic) with the read:packages scope, for the NuGet feed", + "default": "Secrets must be entered via 'fallout :secrets [profile]'" + }, + "NuGetUsername": { + "type": "string", + "description": "GitHub username for the NuGet feed" + }, "ProfileName": { "type": "string" }, diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5404231..b24ccae 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -39,5 +39,8 @@ jobs: .fallout/temp ~/.nuget/packages key: ${{ runner.os }}-${{ hashFiles('**/global.json', '**/*.csproj', '**/Directory.Packages.props') }} - - name: 'Run: CompilePlugin, Test' - run: ./build.cmd CompilePlugin Test + - name: 'Run: AddNuGetSource, CompilePlugin, Test' + run: ./build.cmd AddNuGetSource CompilePlugin Test + env: + NuGetUsername: ${{ secrets.NUGET_USERNAME }} + NuGetToken: ${{ secrets.NUGET_TOKEN }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e866228..fa336e8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -39,8 +39,10 @@ jobs: .fallout/temp ~/.nuget/packages key: ${{ runner.os }}-${{ hashFiles('**/global.json', '**/*.csproj', '**/Directory.Packages.props') }} - - name: 'Run: Release' - run: ./build.cmd Release + - name: 'Run: AddNuGetSource, Release' + run: ./build.cmd AddNuGetSource Release env: GitHubToken: ${{ secrets.GITHUB_TOKEN }} + NuGetUsername: ${{ secrets.NUGET_USERNAME }} + NuGetToken: ${{ secrets.NUGET_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index 1719b69..e67900b 100644 --- a/.gitignore +++ b/.gitignore @@ -149,4 +149,7 @@ npm-debug.log # Database *.db* -/logs \ No newline at end of file +/logs + +# Local SQLite database of the CPDLC server +.data/ diff --git a/CPDLC.json b/CPDLC.json index 7449022..253f9b5 100644 --- a/CPDLC.json +++ b/CPDLC.json @@ -1,5 +1,6 @@ { "ServerEndpoint": "https://vatpac-cpdlc.eoinmotherway.dev/hubs/controller", + "AutoConnect": false, "Stations": ["YBBB", "YMMM", "NFFF", "AYPM"], "LogLevel": "Verbose", "MaxCurrentMessages": 50, diff --git a/README.md b/README.md index 20f54a0..cb0bc51 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,11 @@ +> [!NOTE] +> Even though the development of this plugin was inspired by real ATM systems such as those from Thales Group, the plugin is absolutely NOT affiliated with or endorsed by said company. The plugin and all associated files shall be used solely for the purpose of simulation on the VATSIM network. +> +> The plugin and the CPDLC server are third-party software. They are not provided, operated or endorsed by VATSIM. + ## Overview This plugin enables CPDLC (Controller-Pilot Data Link Communications) functionality in vatSys, allowing controllers to send and receive datalink messages with aircraft on the VATSIM network. @@ -26,9 +31,7 @@ Deploy your own CPDLC Server instance: [![Deploy to DigitalOcean](https://www.deploytodo.com/do-btn-blue.svg)](https://cloud.digitalocean.com/apps/new?repo=https://github.com/YuKitsune/CPDLCPlugin/tree/main) -After deployment, configure the following environment variables: -- `Acars__0__StationIdentifier`: Your station identifier (e.g., YZZZ) -- `Acars__0__AuthenticationCode`: Your Hoppie ACARS authentication code +Before you deploy, set the `MasterKey` environment variable to a key from `openssl rand -base64 32`, and keep a copy of the key in a safe place. After deployment, open the setup URL from the server log to create the administrator. Then add your ACARS connection (station identifier and Hoppie authentication code) in Settings → ACARS on the server dashboard (`/settings/acars`). ## Installation diff --git a/build/Build.cs b/build/Build.cs index fa9e694..d49dd67 100644 --- a/build/Build.cs +++ b/build/Build.cs @@ -23,14 +23,15 @@ namespace _build; GitHubActionsImage.WindowsLatest, OnPushBranches = ["main"], OnPullRequestBranches = ["main"], - InvokedTargets = [nameof(CompilePlugin), nameof(Test)], + InvokedTargets = [nameof(AddNuGetSource), nameof(CompilePlugin), nameof(Test)], + ImportSecrets = [nameof(NuGetUsername), nameof(NuGetToken)], FetchDepth = 0)] [GitHubActions( "release", GitHubActionsImage.WindowsLatest, OnPushTags = ["v*"], - InvokedTargets = [nameof(Release)], - ImportSecrets = [nameof(GitHubToken)], + InvokedTargets = [nameof(AddNuGetSource), nameof(Release)], + ImportSecrets = [nameof(GitHubToken), nameof(NuGetUsername), nameof(NuGetToken)], EnableGitHubToken = true, FetchDepth = 0, WritePermissions = [GitHubActionsPermissions.Contents])] @@ -54,15 +55,32 @@ class Build : FalloutBuild [Secret] readonly string GitHubToken; + [Parameter("GitHub username for the NuGet feed")] + readonly string NuGetUsername; + + [Parameter("GitHub personal access token (classic) with the read:packages scope, for the NuGet feed")] + [Secret] + readonly string NuGetToken; + [Parameter("Output directory for server build")] readonly string ServerOutputDirectory; + [Parameter("Name of the migration to add")] + readonly string MigrationName; + + [Parameter("Version to use instead of the GitVersion version, for example 1.0.0-rc1")] + readonly string ForceVersion; + [GitRepository] readonly GitRepository GitRepository; [GitVersion] readonly GitVersion GitVersion; + // The NuGet feed that contains the vatSysToolbox package + const string NuGetSourceName = "YuKitsune"; + const string NuGetSourceUrl = "https://nuget.pkg.github.com/YuKitsune/index.json"; + const string ReleasePluginName = "CPDLCPlugin"; const string DebugPluginName = "CPDLCPlugin - Debug"; const string PluginAssemblyFileName = "CPDLCPlugin.dll"; @@ -147,9 +165,44 @@ class Build : FalloutBuild Log.Information("vatSys.exe extracted to {Path}", VatSysExePath); }); + Target AddNuGetSource => _ => _ + .Description("Adds the GitHub Packages NuGet feed with the GitHub credentials, or updates the credentials.") + .Requires(() => NuGetUsername) + .Requires(() => NuGetToken) + .Executes(() => + { + // The .NET CLI can encrypt the password only on Windows + var storePasswordInClearText = !OperatingSystem.IsWindows(); + + var sourceExists = DotNetTasks.DotNet("nuget list source", logOutput: false) + .Any(o => o.Text.Contains(NuGetSourceUrl)); + + if (sourceExists) + { + Log.Information("Updating the credentials of the NuGet source {Name}", NuGetSourceName); + DotNetTasks.DotNetNuGetUpdateSource(s => s + .SetName(NuGetSourceName) + .SetSource(NuGetSourceUrl) + .SetUsername(NuGetUsername) + .SetPassword(NuGetToken) + .SetStorePasswordInClearText(storePasswordInClearText)); + } + else + { + Log.Information("Adding the NuGet source {Name}", NuGetSourceName); + DotNetTasks.DotNetNuGetAddSource(s => s + .SetName(NuGetSourceName) + .SetSource(NuGetSourceUrl) + .SetUsername(NuGetUsername) + .SetPassword(NuGetToken) + .SetStorePasswordInClearText(storePasswordInClearText)); + } + }); + Target CompilePlugin => _ => _ .Description("Compiles the plugin") .DependsOn(DownloadVatSys) + .After(AddNuGetSource) .Executes(() => { var version = GetSemanticVersion(); @@ -164,8 +217,8 @@ class Build : FalloutBuild .SetConfiguration(Configuration) .SetOutputDirectory(PluginBuildOutputDirectory) .SetVersion(version) - .SetAssemblyVersion(GitVersion.MajorMinorPatch) - .SetFileVersion(GitVersion.MajorMinorPatch) + .SetAssemblyVersion(GetMajorMinorPatch()) + .SetFileVersion(GetMajorMinorPatch()) .SetInformationalVersion(version) .SetProperty("VatSysPath", VatSysExePath.Parent.Parent)); }); @@ -234,6 +287,7 @@ class Build : FalloutBuild Target TestPlugin => _ => _ .DependsOn(DownloadVatSys) + .After(AddNuGetSource) .Executes(() => { Log.Information("Running plugin tests"); @@ -365,13 +419,29 @@ class Build : FalloutBuild .SetConfiguration(Configuration) .SetOutput(ServerBuildOutputDirectory) .SetVersion(version) - .SetAssemblyVersion(GitVersion.MajorMinorPatch) - .SetFileVersion(GitVersion.MajorMinorPatch) + .SetAssemblyVersion(GetMajorMinorPatch()) + .SetFileVersion(GetMajorMinorPatch()) .SetInformationalVersion(version)); Log.Information("Server published to {OutputDirectory}", ServerBuildOutputDirectory); }); + Target AddMigration => _ => _ + .Description("Adds an EF Core migration for each database provider of the server (SQLite and PostgreSQL).") + .Requires(() => MigrationName) + .Executes(() => + { + AddServerMigration("SqliteCpdlcDbContext", "Persistence/Migrations/Sqlite"); + AddServerMigration("PostgreSqlCpdlcDbContext", "Persistence/Migrations/PostgreSql"); + + void AddServerMigration(string context, string outputDirectory) + { + Log.Information("Adding migration {MigrationName} for {Context}", MigrationName, context); + DotNetTasks.DotNet( + $"ef migrations add {MigrationName} --project {ServerProjectPath} --context {context} --output-dir {outputDirectory}"); + } + }); + Target PackageServer => _ => _ .Description("Bundles the server into a zip archive.") .DependsOn(CompileServer) @@ -477,8 +547,20 @@ static AbsolutePath GetVatSysProfilePath(string profileName) return Path.Combine(documentsPath, "vatSys Files", "Profiles", profileName); } + // The assembly and file versions cannot have a pre-release label or build metadata + string GetMajorMinorPatch() + { + if (!string.IsNullOrEmpty(ForceVersion)) + return ForceVersion.Split('-', '+')[0]; + + return GitVersion?.MajorMinorPatch ?? "0.0.0"; + } + string GetSemanticVersion() { + if (!string.IsNullOrEmpty(ForceVersion)) + return ForceVersion; + // For main/master branch, or if we're on a detached head (building from a tag) // use major.minor.patch (e.g., "1.2.3") if (string.IsNullOrEmpty(GitVersion.BranchName) || GitVersion.BranchName is "main" or "master") diff --git a/docker-compose.yml b/docker-compose.yml index 1d971be..2fd8761 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -12,8 +12,36 @@ services: dockerfile: source/CPDLCServer/Dockerfile env_file: - .env + environment: + DataPath: /data + # Used only when DatabaseProvider=PostgreSql. In the container, the database is at the postgres service. + DatabaseConnectionString: Host=postgres;Port=5432;Database=cpdlc;Username=cpdlc;Password=cpdlc + depends_on: + postgres: + condition: service_healthy + required: false ports: - "8080:8080" + volumes: + - server-data:/data + + # A PostgreSQL server for local development. Start it with: docker compose --profile postgres up + postgres: + profiles: [postgres] + image: postgres:17-alpine + environment: + POSTGRES_DB: cpdlc + POSTGRES_USER: cpdlc + POSTGRES_PASSWORD: cpdlc + ports: + - "127.0.0.1:5432:5432" + volumes: + - postgres-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U cpdlc -d cpdlc"] + interval: 5s + timeout: 5s + retries: 10 ngrok: profiles: [ngrok] @@ -25,3 +53,7 @@ services: - .env ports: - 4040:4040 + +volumes: + server-data: + postgres-data: diff --git a/docs/Dockerfile b/docs/Dockerfile index ef45c26..4674d31 100644 --- a/docs/Dockerfile +++ b/docs/Dockerfile @@ -3,7 +3,6 @@ # Stage 1: Build the static site with Node. FROM node:lts-alpine AS build ENV FORCE_COLOR=0 -RUN corepack enable WORKDIR /opt/docusaurus COPY . /opt/docusaurus/ RUN npm ci diff --git a/docs/docs/concepts/index.md b/docs/docs/concepts/index.md index 54315e5..32e0468 100644 --- a/docs/docs/concepts/index.md +++ b/docs/docs/concepts/index.md @@ -42,6 +42,17 @@ Connections can be initiated by: In both cases, the server automatically accepts valid logon requests. +### Connection Reset + +If an aircraft that is already connected sends `REQUEST LOGON` again, the new logon replaces the existing connection. +Hoppie's network identifies an aircraft only by its callsign, so the new logon can be from a different pilot with the same callsign. + +When the server resets a connection: + +- It closes all open dialogues of the previous connection, and adds the message `CPDLC CONNECTION RESET` to each dialogue +- The aircraft connects as Next Data Authority (NDA) again +- It cancels the ADS-C contract of the previous connection, then requests a new contract + ## Data Authority Data authority determines which ground station is responsible for communicating with an aircraft. @@ -241,9 +252,12 @@ Controllers use ADS-C to see aircraft that are outside radar coverage, such as a The aircraft sends reports automatically. The pilot does not have to do anything. Each report has the position, the altitude, and the time of the report. -:::note -ADS-C and CPDLC are separate systems. An aircraft can have an ADS-C contract with a ground station without a CPDLC connection. -For convenience, this plugin connects ADS-C to CPDLC. The server requests an ADS-C contract when an aircraft logs on with CPDLC, and cancels the contract when the CPDLC connection ends. +:::note[VATSIM accommodation] +ADS-C and CPDLC are separate systems. In real operations, an aircraft can have an ADS-C contract with a ground station without a CPDLC connection. +The aircraft makes ADS-C contracts after an AFN logon, and an ATSU usually keeps its ADS-C contract after it transfers the CPDLC connection to the next ATSU, until the aircraft is clear of its airspace. + +Hoppie's network has no AFN logon, so the CPDLC connection is the only signal that an aircraft is online. +Thus this plugin connects ADS-C to CPDLC. The server requests an ADS-C contract when an aircraft logs on with CPDLC, and cancels the contract when the CPDLC connection ends or is reset. ::: ### Contracts @@ -266,7 +280,7 @@ Each ATSU has a **default reporting interval**. When an aircraft logs on with CPDLC, the server automatically requests a periodic contract with the default reporting interval. This is the **default contract**. A controller can select a different reporting interval for an aircraft, for example, a shorter interval near a conflict. This is the **selected contract**. -A selected contract ends after a fixed time. Then the server requests the default contract again. +The selected contract stays until a controller goes back to the default contract. ```mermaid sequenceDiagram @@ -281,7 +295,7 @@ sequenceDiagram ATSU->>Pilot: Periodic contract (selected interval) Pilot->>ATSU: Report Note over ATSU,Pilot: Selected contract accepted - Note over ATSU,Pilot: Selected contract ends + Note over ATSU,Pilot: Controller selects DEF ATSU->>Pilot: Periodic contract (default interval) ``` diff --git a/docs/docs/server/index.md b/docs/docs/server/index.md index ccc633f..056c4a0 100644 --- a/docs/docs/server/index.md +++ b/docs/docs/server/index.md @@ -19,9 +19,15 @@ Deploy your own CPDLC Server instance to DigitalOcean: [![Deploy to DigitalOcean](https://www.deploytodo.com/do-btn-blue.svg)](https://cloud.digitalocean.com/apps/new?repo=https://github.com/YuKitsune/CPDLCPlugin/tree/main) -After deployment, configure the following environment variables in the DigitalOcean dashboard: -- `Acars__0__StationIdentifier`: Your station identifier (e.g., YBBB) -- `Acars__0__AuthenticationCode`: Your Hoppie ACARS authentication code +Since App Platform doesn't offer persistent disks, the template makes a PostgreSQL development database for the server data. + +:::warning +You must set the `MasterKey`, `VatsimConnect__ClientId` and `VatsimConnect__ClientSecret` environment variables before you deploy. If one of them is not set, the server does not start. + +Make a key with `openssl rand -base64 32`, and keep a copy in a safe place. See [VATSIM Connect](#vatsim-connect) for the client. +::: + +After deployment, open `/setup` on the server, and enter the CID of the first administrator and the operator details (see [Setup](#setup)). Then log in with VATSIM, and add your ACARS connection in Configuration → ACARS connections (`/configuration/acars`). ## Prerequisites @@ -31,86 +37,164 @@ Before running the CPDLC Server, ensure you have: - [Docker](https://www.docker.com/get-started) (for Docker deployment) - A Hoppies ACARS account and logon code from [hoppie.nl](https://www.hoppie.nl/acars/system/register.html) +## Setup + +When the server starts for the first time, it is not set up. All the pages of the dashboard redirect to the setup page (`/setup`). + +On the setup page, enter: + +- The VATSIM CID of the first administrator. +- The operator name: the person or organisation that operates the server, for example a VATSIM division or FIR. +- The privacy contact: an email address or a URL. Users use it to ask questions about their data, or to ask for their data to be deleted. + +The privacy policy shows the operator name and the privacy contact. You can change them later in Configuration → Settings. + +After the setup, the setup page does not exist. The administrator logs in with VATSIM, and can add more administrators in Configuration → Administrators. + +:::warning +The setup page needs no login. The first person who opens it chooses the administrator. Do the setup immediately after the first start. +::: + +### VATSIM Connect + +All users log in with [VATSIM Connect](https://vatsim.dev/services/connect). Make an OAuth client for the server at [auth.vatsim.net](https://auth.vatsim.net) (or [auth-dev.vatsim.net](https://auth-dev.vatsim.net) for development), with the redirect URL `https:///signin-vatsim`. Then set these environment variables: + +- `VatsimConnect__ClientId`: the ID of the client. +- `VatsimConnect__ClientSecret`: the secret of the client. +- `VatsimConnect__Authority` (optional): the VATSIM Connect server. The default is `https://auth.vatsim.net`. +- `VatsimConnect__DevCid` (optional, development only): the login page logs in all users with this CID, and does not use VATSIM Connect. The client ID and the client secret are then not necessary. The server uses this value only when `ASPNETCORE_ENVIRONMENT` is `Development`. + +Any VATSIM user can log in, open the CPDLC and ADS-C areas, and connect with the plugin. Only an administrator can open the Configuration area. + +Behind a proxy that ends TLS, the server uses the `X-Forwarded-Proto` header, so that the redirect URL uses `https`. + +### Plugin Authentication + +The plugin must authenticate before it can connect to the server. In the SETUP window of the plugin, select **Authenticate**. The browser opens the server, the user logs in with VATSIM, and selects **Allow**. Then the plugin gets a token. The token is valid for 30 days. The plugin keeps it encrypted for the Windows account of the user. + +### Master Key + +The master key encrypts the secrets in the database, for example the authentication codes of the ACARS connections. Set it in the `MasterKey` environment variable before the first start. You can make a key with `openssl rand -base64 32`, and keep a copy in a safe place. + +If `MasterKey` is not set, or the key is not valid, the server does not start. + +If the key is lost, the server cannot decrypt the secrets. + ## Configuration -The server can be configured using environment variables. -Copy `example.env` to `.env` and update with your settings: +The logging level, the master key, VATSIM Connect, the data directory and the database are configured with environment variables. `MasterKey`, `VatsimConnect__ClientId` and `VatsimConnect__ClientSecret` are required. +For local development, copy `example.env` to `.env` and update with your settings: ```bash # Logging Logging__Level=Information -# ACARS Client Configuration -Acars__0__Type=Hoppie -Acars__0__FlightSimulationNetwork=VATSIM -Acars__0__StationIdentifier=YBBB -Acars__0__Url=http://www.hoppie.nl/acars/system/connect.html -Acars__0__AuthenticationCode=your-hoppie-logon-code -# Reporting interval in minutes of the ADS-C contract requested on CPDLC logon (default: 10) -Acars__0__DefaultAdscReportingInterval=10 -# Minutes from the request of a selected ADS-C contract to its end. Then the default contract is requested again (default: 60) -Acars__0__SelectedAdscContractDuration=60 - -# Handoff Configuration -# How many minutes before the expected transfer time to send the NEXT DATA AUTHORITY message (default: 10) -Handoff__NotificationLeadTime=10 - -# ADS-C from VATSIM status data -# Make ADS-C reports from the VATSIM status data for aircraft that do not support ADS-C over Hoppie (default: false) -VatsimStatus__Enabled=false -# The URL of the VATSIM status data (default: https://data.vatsim.net/v3/vatsim-data.json) -VatsimStatus__Url=https://data.vatsim.net/v3/vatsim-data.json -# The time in seconds between downloads of the VATSIM status data (default: 120) -VatsimStatus__PollingIntervalSeconds=120 -# Also make reports for aircraft that do not have D1 or G1 in Item 10b of the flight plan (default: false) -VatsimStatus__AllowNonEquippedAircraft=false +# Master Key (required) +# Encrypts the secrets in the database. Make a key with: openssl rand -base64 32 +MasterKey=your-master-key + +# VATSIM Connect (required) +VatsimConnect__ClientId=your-client-id +VatsimConnect__ClientSecret=your-client-secret + +# Data Directory +# The directory of the SQLite database (cpdlc.db) (default: /data) +DataPath=/data + +# Database Configuration +# The database provider: Sqlite or PostgreSql (default: Sqlite) +DatabaseProvider=Sqlite +# PostgreSQL: the connection string. A URL (postgresql://...) is also accepted. +# DatabaseConnectionString=Host=localhost;Database=cpdlc;Username=cpdlc;Password=your-password ``` -### Multiple ACARS Connections +### Persistence -You can configure multiple ACARS clients by incrementing the index (`Acars__1__`, `Acars__2__`, etc.). This is useful when serving multiple ATSUs (e.g., YBBB and YMMM) +The server keeps the CPDLC connections, the dialogues, the ADS-C contracts, the ADS-C reports, settings, and the ACARS connections in a database. -Example configuration for multiple connections: +The server can use SQLite or PostgreSQL (`DatabaseProvider`): -```bash -# Brisbane FIR -Acars__0__Type=Hoppie -Acars__0__FlightSimulationNetwork=VATSIM -Acars__0__StationIdentifier=YBBB -Acars__0__Url=http://www.hoppie.nl/acars/system/connect.html -Acars__0__AuthenticationCode=your-ybbb-hoppie-code - -# Melbourne FIR -Acars__1__Type=Hoppie -Acars__1__FlightSimulationNetwork=VATSIM -Acars__1__StationIdentifier=YMMM -Acars__1__Url=http://www.hoppie.nl/acars/system/connect.html -Acars__1__AuthenticationCode=your-ymmm-hoppie-code -``` +- **SQLite** (default): the database is the file `cpdlc.db` in the data directory (`DataPath`). In the Docker image, the data directory is the `/data` volume. For local development, it is the `.data` directory at the root of the repository. +- **PostgreSQL**: set `DatabaseConnectionString`. Use PostgreSQL when the platform has no persistent disk, for example DigitalOcean App Platform. + +The server applies the migrations when it starts. With SQLite, it also makes the database file. + +The server deletes a dialogue when the dialogue retention period ends (default: 24 hours). The period starts when the dialogue opens, not when the server starts. Thus, after a restart, the server deletes the dialogues that are older than the period within a few minutes. The server keeps the dialogues after the aircraft disconnects. + +The server keeps only the latest ADS-C report for each contract. The report expires soon after the next periodic reports do not arrive (see [ADS-C](#ads-c)). + +When a CPDLC connection ends, the server deletes the CPDLC message IDs of the aircraft. The next connection starts again at the first message ID. + +### Concurrent Changes + +The server processes the requests from controllers, the ACARS connections and the background tasks at the same time. Each changed record has a version. If two requests change the same record at the same time, the second request fails and the server runs it again with the new data, up to three times. + +### ACARS Connections + +The ACARS connections connect the server to the upstream ACARS networks. Add, change and delete them in Configuration → ACARS connections on the dashboard (`/configuration/acars`). + +- When you add a connection, the server connects to the ACARS network. +- When you change a connection, the server will reconnect to the upstream ACARS network with the new settings. + +You can add more than one connection, for example when the server serves more than one ATSU (YBBB and YMMM). Only one connection can use a station identifier. + +The server keeps the authentication code of each connection encrypted with the master key (`MasterKey`). The dashboard does not show the code. If the master key changes, the server cannot decrypt the codes, and you must enter them again. + +Each connection can have a message of the day. The server sends it to each aircraft as a CPDLC free text message, after the aircraft logs on and after the delay of the connection. The aircraft does not reply. The message shows in the dialogues, the same as the other uplinks. + +The Traffic button of a connection shows the most recent requests to the ACARS network and their responses, as raw text. The server keeps the last 500 requests of each connection in memory. The authentication code is not shown. The Logs button shows the log of the connection. :::note `Hoppie` is currently the only supported ACARS network type. ::: +### Privacy Policy + +VATSIM Connect needs a privacy policy and a statement that the service is not provided or endorsed by VATSIM. The server has both: + +- The privacy policy is at `/privacy`. Everyone can open it, also without a login. It shows the operator, the privacy contact, the data that the server collects, who can see it, the third parties, and how long the server keeps the data. The retention times come from the settings, so the page is correct when you change them. +- Each page shows this statement, with a link to the privacy policy: "This server is a third-party service. It is not provided, operated or endorsed by VATSIM." +- The login page tells users that VATSIM gives the server their CID and name, and that they accept the privacy policy when they log in. + +:::warning +The privacy policy describes the software. The operator is responsible for the data on their server. Read the policy, and make sure that it agrees with the laws that apply to you and with the VATSIM policies, before you open the server to users. +::: + +### Branding + +In the Branding section of Configuration → Settings, you can change the name of the server, add a banner image (PNG, JPEG or WebP, 1 MB or less), and add a message of the day. They show at the top of the sidebar and on the login page. The banner changes when you upload or remove it. The Save button saves the name and the message of the day. + +### Logs + +The Logs page of the dashboard (`/configuration/logs`) shows the live log of the server, with the same text and level colours as the console output. + +You can show only the entries at or above a level, of one area (CPDLC, ADS-C, ACARS or System), of one ACARS connection, or with a text. You can also pause the log and clear the page. The filters are in the URL, so you can share a link to a filtered log. The logging level of the server (`Logging__Level`) sets which entries the server writes. + ### ADS-C -When an aircraft logs on with CPDLC, the server requests the default ADS-C contract with the aircraft. When the CPDLC connection ends, the server cancels the contract. +When an aircraft logs on with CPDLC, the server requests the default ADS-C contract with the aircraft. When the CPDLC connection ends or is reset, the server cancels the contract. -Each ATSU has its own default reporting interval, set with `Acars____DefaultAdscReportingInterval`. Controllers can read this value. +:::note[VATSIM accommodation] +In real operations, ADS-C does not depend on CPDLC, and an ATSU usually keeps its ADS-C contract after a CPDLC transfer. Hoppie's network has no AFN logon, so the server uses the CPDLC connection as the signal that an aircraft is online. +::: + +Each ATSU has its own default reporting interval, set on its ACARS connection. Controllers can read this value. -A controller can select a different reporting interval for an aircraft. The selected contract ends `Acars____SelectedAdscContractDuration` minutes after the server sends the request. Then the server requests the default contract again. A controller can also go back to the default contract at any time. +A controller can select a different reporting interval for an aircraft. The selected contract stays until a controller goes back to the default contract. The aircraft does not acknowledge a request. The first report after a request accepts it. If the aircraft rejects a selected contract, the server requests the default contract again. If the aircraft rejects the default contract, the server does not send it again. -The server keeps the latest report for each aircraft. When a controller connects, the plugin loads these reports, so that the controller sees the ADS-C tracks immediately. +The server keeps one report for each contract. A new report replaces the previous report. When a controller connects, the plugin loads the latest report for each aircraft, so that the controller sees the ADS-C tracks immediately. + +A report expires when the next two periodic reports do not arrive. The expiry time is two reporting intervals plus three minutes, from the time in the report. A contract with only a demand request uses the default reporting interval. When a report expires, or when its contract is removed, the server deletes the report and the plugin shows the flight plan track again. -The ADS-C page of the dashboard (`/adsc`) shows all the contracts and their states, and a log of all the ADS-C messages that the server sent and received. +The ADS-C area of the dashboard shows all the contracts and their states (`/adsc`), and a log of all the ADS-C messages that the server sent and received (`/adsc/messages`). ### ADS-C from VATSIM Status Data -Not all aircraft support ADS-C over Hoppie's network. When `VatsimStatus__Enabled` is `true`, the server fakes ADS-C reports using data from the [VATSIM status API](https://data.vatsim.net/v3/vatsim-data.json). +Not all aircraft support ADS-C over Hoppie's network. When the "ADS-C from VATSIM status data" setting is on, the server fakes ADS-C reports using data from the [VATSIM status API](https://data.vatsim.net/v3/vatsim-data.json). -This is only done for aircraft that have `D1` or `G1` in Item 10b of the flight plan, unless `VatsimStatus__AllowNonEquippedAircraft` is `true`. A report from Hoppie always has priority. If the Hoppie reports stop for more than two reporting intervals, the server uses the VATSIM status data again. +This is only done for aircraft that have `D1` or `G1` in Item 10b of the flight plan, unless the "allow aircraft without ADS-C equipment" setting is on. The server waits for the "report delay" after it makes a contract before it uses the VATSIM status data, so that the aircraft can send its first report through Hoppie. A report from Hoppie always has priority, and it stops the VATSIM reports for that contract. When the Hoppie report expires, the server uses the VATSIM status data again. ## Running diff --git a/docs/docs/vatsys-plugin/configuration.md b/docs/docs/vatsys-plugin/configuration.md index 116dc9a..e0c9a1a 100644 --- a/docs/docs/vatsys-plugin/configuration.md +++ b/docs/docs/vatsys-plugin/configuration.md @@ -17,6 +17,15 @@ URL of the CPDLC server WebSocket endpoint. "ServerEndpoint": "http://localhost:5261/hubs/controller" ``` +### AutoConnect + +When `true`, the plugin connects to the CPDLC server when vatSys connects to VATSIM. It uses the first station in `Stations`. The plugin must be authenticated (see [Connecting to the CPDLC Server](plugin.md#connecting-to-the-cpdlc-server)). Default: `false`. + +**Example:** +```json +"AutoConnect": true +``` + ### Stations List of station identifiers this controller position will use. The plugin will connect to the server using these callsigns. @@ -224,6 +233,7 @@ Array of message groups for organizing messages in the editor. Each group has: ```json { "ServerEndpoint": "http://localhost:5261/hubs/controller", + "AutoConnect": false, "Stations": ["YZZZ", "YXXX"], "LogLevel": "Verbose", "MaxCurrentMessages": 50, diff --git a/docs/docs/vatsys-plugin/plugin.md b/docs/docs/vatsys-plugin/plugin.md index 4825edc..06cae8c 100644 --- a/docs/docs/vatsys-plugin/plugin.md +++ b/docs/docs/vatsys-plugin/plugin.md @@ -11,6 +11,10 @@ It explains how to connect to the server, interpret track labels, manage CPDLC m To connect, open the CPDLC menu and select Setup. Verify the server URL and station ID, then click Connect. +The first time, you must authenticate with the server. Below the server URL, the Setup window shows if you are authenticated. Click Authenticate. The browser opens the server. Log in with VATSIM, then click Allow. The plugin keeps the authentication for 30 days. To remove it, click Log out. + +The plugin does not connect to the server on the sweatbox. To connect automatically when you connect to VATSIM, set `AutoConnect` in the [configuration](configuration.md#autoconnect). + The station you select is your primary ATSU. Once connected, you can send and receive messages for any ATSU managed by that server. This allows controllers to extend their jurisdiction across FIR boundaries (e.g., Brisbane Centre extending to Melbourne Centre) when both ATSUs share a server. ## Track Label Item @@ -214,7 +218,6 @@ The window shows: - **Last Report:** The time of the latest report from the aircraft - **Default Period:** The default reporting interval of your ATSU, in minutes - **Selected Period:** The reporting interval that a controller selected, in minutes. `DEF` shows that the default period is selected. -- **Selected Period End:** The time when the selected contract ends. Then the server requests the default contract again. - **Source:** The source of the latest report. `Hoppie` is a report from the aircraft through ACARS. `VATSIM` is a server-generated report using VATSIM data when there is no report from ACARS. A symbol next to each contract shows the state of the request: @@ -229,9 +232,9 @@ A symbol next to each contract shows the state of the request: 2. Click a period in the list, or type a period (in minutes) in the box at the bottom of the list, then press Enter. The server sends the request to the aircraft immediately. -The selected contract ends after a time that the server sets (60 minutes by default). +The selected contract stays until a controller changes it. -To go back to the default contract before the selected contract ends, click `DEF` in the list. +To go back to the default contract, click `DEF` in the list. #### Requesting a Demand Report diff --git a/example.env b/example.env index 284a1f4..290ea90 100644 --- a/example.env +++ b/example.env @@ -4,45 +4,36 @@ ASPNETCORE_ENVIRONMENT=Development # Logging Configuration Logging__Level=Debug -# ACARS Network Configuration -# Multiple configurations can be added by incrementing the index (0, 1, 2, etc.) - -# First ACARS Configuration -Acars__0__Type=Hoppie -Acars__0__FlightSimulationNetwork=VATSIM -Acars__0__StationIdentifier=YBBB -Acars__0__Url=http://www.hoppie.nl/acars/system/connect.html -Acars__0__AuthenticationCode=your-authentication-code-here -# Reporting interval in minutes of the ADS-C contract requested on CPDLC logon (default: 10) -Acars__0__DefaultAdscReportingInterval=10 -# Minutes from the request of a selected ADS-C contract to its end. Then the default contract is requested again (default: 60) -Acars__0__SelectedAdscContractDuration=60 - -# Example: Second ACARS Configuration (uncomment to use) -# Acars__1__Type=Hoppie -# Acars__1__FlightSimulationNetwork=IVAO -# Acars__1__StationIdentifier=KJFK -# Acars__1__Url=http://www.hoppie.nl/acars/system/connect.html -# Acars__1__AuthenticationCode=your-other-authentication-code - -# Connection Monitoring Configuration -# The time in minutes between checks of the connected callsigns on the ACARS network (default: 15) -ConnectivityCheckIntervalMinutes=15 -# The time (hh:mm:ss) without contact from an aircraft before its connection times out (default: 3 times ConnectivityCheckIntervalMinutes) -# Use a value of more than 2 times ConnectivityCheckIntervalMinutes. If not, one failed check will cause connections to time out. -AircraftConnectionTimeout=00:45:00 - -# Handoff Configuration -# How many minutes before the expected transfer time to send the NEXT DATA AUTHORITY message (default: 20) -Handoff__NotificationLeadTime=20 - -# ADS-C from VATSIM status data -# Make ADS-C reports from the VATSIM status data for aircraft that do not support ADS-C over Hoppie (default: false) -VatsimStatus__Enabled=false -# The time in seconds between downloads of the VATSIM status data (default: 120) -VatsimStatus__PollingIntervalSeconds=120 -# Also make reports for aircraft that do not have D1 or G1 in Item 10b of the flight plan (default: false) -VatsimStatus__AllowNonEquippedAircraft=false +# Master Key (required) +# Encrypts the secrets in the database, for example the authentication codes of the ACARS connections. +# Make a key with: openssl rand -base64 32 +# Keep the key safe. If the key changes, the server cannot decrypt the secrets, and you must enter them again. +MasterKey= + +# VATSIM Connect (required) +# The OAuth client of this server. Make it at https://auth.vatsim.net (or https://auth-dev.vatsim.net for development). +# Set the redirect URL of the client to https:///signin-vatsim +VatsimConnect__ClientId= +VatsimConnect__ClientSecret= + +# The VATSIM Connect server (default: https://auth.vatsim.net) +VatsimConnect__Authority=https://auth-dev.vatsim.net + +# Development only: log in all users with this CID, and do not use VATSIM Connect. +# When this is set, the client ID and the client secret are not necessary. +# VatsimConnect__DevCid=10000001 + +# Data Directory +# The directory of the SQLite database (cpdlc.db). The server makes it if it does not exist. +# (default: .data at the root of the repository in Development, /data in other environments) +# DataPath=/data + +# Database Configuration +# The database provider: Sqlite or PostgreSql (default: Sqlite) +# DatabaseProvider=Sqlite + +# PostgreSQL: the connection string. A URL (postgresql://user:password@host:port/database?sslmode=require) is also accepted. +# DatabaseConnectionString=Host=localhost;Database=cpdlc;Username=cpdlc;Password=your-password # ngrok auth token to allow remote connections to your local debug server # https://ngrok.com/ diff --git a/source/CPDLCPlugin.Tests/Messages/UpdateNextDataAuthorityRequestHandlerTests.cs b/source/CPDLCPlugin.Tests/Messages/UpdateNextDataAuthorityRequestHandlerTests.cs index 9a51547..ab1f51e 100644 --- a/source/CPDLCPlugin.Tests/Messages/UpdateNextDataAuthorityRequestHandlerTests.cs +++ b/source/CPDLCPlugin.Tests/Messages/UpdateNextDataAuthorityRequestHandlerTests.cs @@ -4,6 +4,7 @@ using CPDLCServer.Contracts; using NSubstitute; using Serilog.Core; +using vatSysToolbox; namespace CPDLCPlugin.Tests.Messages; diff --git a/source/CPDLCPlugin/AdscReportStore.cs b/source/CPDLCPlugin/AdscReportStore.cs index c9c20df..5d13726 100644 --- a/source/CPDLCPlugin/AdscReportStore.cs +++ b/source/CPDLCPlugin/AdscReportStore.cs @@ -82,6 +82,26 @@ public async Task> All(CancellationToken canc } } + /// + /// Removes the report of the aircraft, if it is from the ATSU. + /// + /// True if the report was removed. + public async Task Remove(string callsign, string stationId, CancellationToken cancellationToken = default) + { + await _semaphore.WaitAsync(cancellationToken); + try + { + if (!_latestReports.TryGetValue(callsign, out var report) || report.StationId != stationId) + return false; + + return _latestReports.Remove(callsign); + } + finally + { + _semaphore.Release(); + } + } + public async Task Clear(CancellationToken cancellationToken = default) { await _semaphore.WaitAsync(cancellationToken); diff --git a/source/CPDLCPlugin/AdscTrackDisplay.cs b/source/CPDLCPlugin/AdscTrackDisplay.cs index 395c33b..c8fd3d1 100644 --- a/source/CPDLCPlugin/AdscTrackDisplay.cs +++ b/source/CPDLCPlugin/AdscTrackDisplay.cs @@ -2,6 +2,7 @@ using CPDLCPlugin.Configuration; using CPDLCServer.Contracts; using vatsys; +using vatSysToolbox.Infrastructure; namespace CPDLCPlugin; @@ -55,6 +56,22 @@ public void Show(AdscReportDto report) fdr.PredictedPosition.Location = new Coordinate(report.Latitude, report.Longitude); } + /// + /// Removes the ADS-C track of the aircraft, if it shows a report from the ATSU. + /// The track goes back to its flight plan position. + /// + public void Remove(string callsign, string stationId) + { + if (!_tracks.TryGetValue(callsign, out var track) || track.Report.StationId != stationId) + return; + + // Do not remove a newer report that arrived after the check + if (!((ICollection>)_tracks).Remove(new KeyValuePair(callsign, track))) + return; + + RestoreFlightPlanPosition(callsign); + } + public void Clear() { var callsigns = _tracks.Keys.ToArray(); diff --git a/source/CPDLCPlugin/AdscTrackPatches.cs b/source/CPDLCPlugin/AdscTrackPatches.cs index 6854f1e..f6472e4 100644 --- a/source/CPDLCPlugin/AdscTrackPatches.cs +++ b/source/CPDLCPlugin/AdscTrackPatches.cs @@ -10,6 +10,7 @@ namespace CPDLCPlugin; /// /// When a report arrives, the track moves to the reported position and uses the ADSC symbol. /// Each time vatSys extrapolates the flight plan positions, the track moves along the route from the reported position and uses the ADSCExtrapolated symbol. +/// The controller cannot open the PRL menu, because the PRL comes from the reports. /// /// A coupled radar track always has priority over an ADS-C report. /// @@ -44,6 +45,11 @@ public static void Apply(AdscTrackDisplay display) harmony.Patch( RequireMethod("vatsys.FDP2:GenerateTrackPosition"), postfix: new HarmonyMethod(typeof(AdscTrackPatches), nameof(GenerateTrackPositionPostfix))); + + // The PRL label item and the PRL strip item open this menu on a left click + harmony.Patch( + RequireMethod("vatsys.MMI:OpenPRLMenu"), + prefix: new HarmonyMethod(typeof(AdscTrackPatches), nameof(OpenPRLMenuPrefix))); } catch { @@ -89,6 +95,20 @@ static void PaintTrackGeometryRealisationPrefix(ref TrackSymbols.Types type, ref aircraftHeading = -1; } + static bool OpenPRLMenuPrefix(FDP2.FDR SourceFDR, ref bool __result) + { + if (!HasAdscTrack(SourceFDR)) + return true; + + __result = false; + return false; + } + + static bool HasAdscTrack(FDP2.FDR? fdr) + { + return _display is not null && fdr is not null && _display.TryGetTrack(fdr.Callsign, out _); + } + static void GenerateTrackPositionPostfix(FDP2.FDR fdr) { if (_display is null || fdr.CoupledTrack is not null) diff --git a/source/CPDLCPlugin/AtsuSettingsStore.cs b/source/CPDLCPlugin/AtsuSettingsStore.cs deleted file mode 100644 index c1ec783..0000000 --- a/source/CPDLCPlugin/AtsuSettingsStore.cs +++ /dev/null @@ -1,22 +0,0 @@ -using CPDLCServer.Contracts; - -namespace CPDLCPlugin; - -/// -/// Holds the read-only settings of the ATSU this client is connected to. -/// The settings are null when the client is not connected. -/// -public class AtsuSettingsStore -{ - public AtsuSettingsDto? Settings { get; private set; } - - public void Set(AtsuSettingsDto settings) - { - Settings = settings; - } - - public void Clear() - { - Settings = null; - } -} diff --git a/source/CPDLCPlugin/BackgroundWorker.cs b/source/CPDLCPlugin/BackgroundWorker.cs deleted file mode 100644 index fd0d849..0000000 --- a/source/CPDLCPlugin/BackgroundWorker.cs +++ /dev/null @@ -1,29 +0,0 @@ -namespace CPDLCPlugin; - -public class BackgroundWorker : IAsyncDisposable -{ - readonly Task _workerTask; - readonly CancellationTokenSource _cancellationTokenSource; - - public BackgroundWorker(Func workerTask) - { - _cancellationTokenSource = new CancellationTokenSource(); - _workerTask = workerTask(_cancellationTokenSource.Token); - } - - public async ValueTask DisposeAsync() - { - _cancellationTokenSource.Cancel(); - try - { - await _workerTask; - } - catch (OperationCanceledException) when (_cancellationTokenSource.IsCancellationRequested) - { - // Ignored, likely thrown due to cancellation - } - - _workerTask.Dispose(); - _cancellationTokenSource.Dispose(); - } -} diff --git a/source/CPDLCPlugin/CPDLCPlugin.csproj b/source/CPDLCPlugin/CPDLCPlugin.csproj index 6290c1b..495b02c 100644 --- a/source/CPDLCPlugin/CPDLCPlugin.csproj +++ b/source/CPDLCPlugin/CPDLCPlugin.csproj @@ -26,10 +26,14 @@ + + + + @@ -37,6 +41,7 @@ + $(VatSysPath)\bin\vatSys.exe False diff --git a/source/CPDLCPlugin/Configuration/ConfigurationLoader.cs b/source/CPDLCPlugin/Configuration/ConfigurationLoader.cs index 9ab925c..3b47a7d 100644 --- a/source/CPDLCPlugin/Configuration/ConfigurationLoader.cs +++ b/source/CPDLCPlugin/Configuration/ConfigurationLoader.cs @@ -1,7 +1,7 @@ using System.IO; -using System.Reflection; using System.Text.Json; using System.Text.Json.Serialization; +using vatSysToolbox.Configuration; namespace CPDLCPlugin.Configuration; @@ -11,38 +11,12 @@ public static class ConfigurationLoader public static PluginConfiguration Load() { - var searchDirectories = new List(); - - // Search the profile first - if (ProfileDirectoryResolver.TryGetProfileDirectory(out var profileDirectory)) - { - searchDirectories.AddRange([ - Path.Combine(profileDirectory.FullName, "Plugins", "Configs", "CPDLC Plugin"), - Path.Combine(profileDirectory.FullName, "Plugins", "Configs", "CPDLCPlugin"), - Path.Combine(profileDirectory.FullName, "Plugins", "Configs", "CPDLC"), - Path.Combine(profileDirectory.FullName, "Plugins", "Configs"), - Path.Combine(profileDirectory.FullName, "Plugins"), - profileDirectory.FullName - ]); - } - - // Search the assembly directory last - var assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - searchDirectories.Add(assemblyDirectory); - - var configFilePath = string.Empty; - foreach (var searchDirectory in searchDirectories) - { - var filePath = Path.Combine(searchDirectory, ConfigFileName); - if (!File.Exists(filePath)) - continue; - - configFilePath = filePath; - break; - } - - if (string.IsNullOrEmpty(configFilePath)) - throw new FileNotFoundException($"Unable to locate {ConfigFileName}"); + var configFilePath = ConfigurationLocator.LocateConfigurationFile( + typeof(Plugin).Assembly, + ConfigFileName, + "CPDLC Plugin", + "CPDLCPlugin", + "CPDLC"); var configurationJson = File.ReadAllText(configFilePath); var configuration = JsonSerializer.Deserialize(configurationJson, new JsonSerializerOptions diff --git a/source/CPDLCPlugin/Configuration/PluginConfiguration.cs b/source/CPDLCPlugin/Configuration/PluginConfiguration.cs index e970dfc..617abdc 100644 --- a/source/CPDLCPlugin/Configuration/PluginConfiguration.cs +++ b/source/CPDLCPlugin/Configuration/PluginConfiguration.cs @@ -5,6 +5,10 @@ namespace CPDLCPlugin.Configuration; public class PluginConfiguration { public required string ServerEndpoint { get; init; } + + // When true, the plugin connects to the CPDLC server when vatSys connects to VATSIM. + // It uses the first station in Stations. + public bool AutoConnect { get; init; } public required string[] Stations { get; init; } public int MaxCurrentMessages { get; init; } = 50; public int MaxArchivedMessages { get; init; } = 50; diff --git a/source/CPDLCPlugin/Configuration/ProfileDirectoryResolver.cs b/source/CPDLCPlugin/Configuration/ProfileDirectoryResolver.cs deleted file mode 100644 index b5fcd1c..0000000 --- a/source/CPDLCPlugin/Configuration/ProfileDirectoryResolver.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.IO; -using System.Reflection; -using vatsys; - -namespace CPDLCPlugin.Configuration; - -public static class ProfileDirectoryResolver -{ - public static bool TryGetProfileDirectory(out DirectoryInfo? directoryInfo) - { - directoryInfo = null; - if (!Profile.Loaded) - return false; - - var shortNameObject = typeof(Profile).GetField("shortName", BindingFlags.Static | BindingFlags.NonPublic); - var shortName = (string)shortNameObject.GetValue(shortNameObject); - - directoryInfo = new DirectoryInfo(Path.Combine(Helpers.GetFilesFolder(), "Profiles", shortName)); - return true; - } -} diff --git a/source/CPDLCPlugin/Configuration/XmlInstaller.cs b/source/CPDLCPlugin/Configuration/XmlInstaller.cs index a39f894..ff0588c 100644 --- a/source/CPDLCPlugin/Configuration/XmlInstaller.cs +++ b/source/CPDLCPlugin/Configuration/XmlInstaller.cs @@ -1,4 +1,5 @@ using System.IO; +using vatSysToolbox.Configuration; namespace CPDLCPlugin.Configuration; diff --git a/source/CPDLCPlugin/Controls/BeveledBorder.cs b/source/CPDLCPlugin/Controls/BeveledBorder.cs deleted file mode 100644 index 86f1c23..0000000 --- a/source/CPDLCPlugin/Controls/BeveledBorder.cs +++ /dev/null @@ -1,168 +0,0 @@ -using System.Windows; -using System.Windows.Controls; -using System.Windows.Media; - -namespace CPDLCPlugin.Controls; - -public enum BevelType -{ - Raised, - Sunken, - Outline -} - -public class BeveledBorder : Decorator -{ - public static readonly DependencyProperty BorderThicknessProperty = - DependencyProperty.Register( - nameof(BorderThickness), - typeof(Thickness), - typeof(BeveledBorder), - new FrameworkPropertyMetadata( - new Thickness(0), - FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure)); - - public static readonly DependencyProperty BevelTypeProperty = - DependencyProperty.Register( - nameof(BevelType), - typeof(BevelType), - typeof(BeveledBorder), - new FrameworkPropertyMetadata( - BevelType.Raised, - FrameworkPropertyMetadataOptions.AffectsRender)); - - public Thickness BorderThickness - { - get => (Thickness)GetValue(BorderThicknessProperty); - set => SetValue(BorderThicknessProperty, value); - } - - public BevelType BevelType - { - get => (BevelType)GetValue(BevelTypeProperty); - set => SetValue(BevelTypeProperty, value); - } - - Thickness BorderThicknessDoubled => - new Thickness(BorderThickness.Left * 2, BorderThickness.Top * 2, BorderThickness.Right * 2, - BorderThickness.Bottom * 2); - - protected override Size MeasureOverride(Size constraint) - { - if (Child != null) - { - var thickness = BevelType == BevelType.Outline ? BorderThicknessDoubled : BorderThickness; - - var availableChildSize = new Size( - Math.Max(constraint.Width - thickness.Left - thickness.Right, 0), - Math.Max(constraint.Height - thickness.Top - thickness.Bottom, 0)); - - Child.Measure(availableChildSize); - - return new Size( - Child.DesiredSize.Width + thickness.Left + thickness.Right, - Child.DesiredSize.Height + thickness.Top + thickness.Bottom); - } - - return new Size(0, 0); - } - - protected override Size ArrangeOverride(Size arrangeSize) - { - if (Child != null) - { - var thickness = BevelType == BevelType.Outline ? BorderThicknessDoubled : BorderThickness; - var childRect = new Rect( - thickness.Left, - thickness.Top, - arrangeSize.Width - thickness.Left - thickness.Right, - arrangeSize.Height - thickness.Top - thickness.Bottom); - - Child.Arrange(childRect); - } - - return arrangeSize; - } - - protected override void OnRender(DrawingContext dc) - { - switch (BevelType) - { - case BevelType.Raised: - case BevelType.Sunken: - DrawBevel(dc, BevelType == BevelType.Raised); - break; - - case BevelType.Outline: - DrawOutline(dc); - break; - - default: - throw new NotSupportedException(); - } - } - - void DrawBevel(DrawingContext dc, bool isRaised) - { - var light = isRaised ? Theme.LightBrush : Theme.DarkBrush; - var dark = isRaised ? Theme.DarkBrush : Theme.LightBrush; - - var topLeftGeometry = GetTopLeftGeometry(0, 0, ActualWidth, ActualHeight, BorderThickness); - dc.DrawGeometry(light, new Pen(light, 0), topLeftGeometry); - - var bottomRightGeometry = GetBottomRightGeometry(0, 0, ActualWidth, ActualHeight, BorderThickness); - dc.DrawGeometry(dark, new Pen(dark, 0), bottomRightGeometry); - } - - void DrawOutline(DrawingContext dc) - { - var outerLight = Theme.LightBrush; - var outerDark = Theme.DarkBrush; - var innerDark = Theme.DarkBrush; - var innerLight = Theme.LightBrush; - - dc.DrawGeometry(outerLight, new Pen(outerLight, 0), - GetTopLeftGeometry(0, 0, ActualWidth, ActualHeight, BorderThickness)); - dc.DrawGeometry(outerDark, new Pen(outerDark, 0), - GetBottomRightGeometry(0, 0, ActualWidth, ActualHeight, BorderThickness)); - - dc.DrawGeometry(innerDark, new Pen(innerDark, 0), - GetTopLeftGeometry(BorderThickness.Left, BorderThickness.Top, ActualWidth - BorderThickness.Right, - ActualHeight - BorderThickness.Bottom, BorderThickness)); - dc.DrawGeometry(innerLight, new Pen(innerLight, 0), - GetBottomRightGeometry(BorderThickness.Left, BorderThickness.Top, ActualWidth - BorderThickness.Right, - ActualHeight - BorderThickness.Bottom, BorderThickness)); - } - - Geometry GetTopLeftGeometry(double left, double top, double right, double bottom, Thickness thickness) - { - var segments = new[] - { - new Point(left, top), - new Point(right, top), - new Point(right - thickness.Right, top + thickness.Top), - new Point(left + thickness.Left, top + thickness.Top), - new Point(left + thickness.Left, bottom - thickness.Bottom), - new Point(left, bottom), - new Point(left, top) - }.Select(p => new LineSegment(p, false)); - - return new PathGeometry([new PathFigure(new Point(left, top), segments, true)]); - } - - Geometry GetBottomRightGeometry(double left, double top, double right, double bottom, Thickness thickness) - { - var segments = new[] - { - new Point(right, top), - new Point(right, bottom), - new Point(left, bottom), - new Point(left + thickness.Left, bottom - thickness.Bottom), - new Point(right - thickness.Right, bottom - thickness.Bottom), - new Point(right - thickness.Right, top + thickness.Bottom), - new Point(right, top) - }.Select(p => new LineSegment(p, false)); - - return new PathGeometry([new PathFigure(new Point(left, top), segments, true)]); - } -} diff --git a/source/CPDLCPlugin/Controls/BeveledLine.cs b/source/CPDLCPlugin/Controls/BeveledLine.cs deleted file mode 100644 index 10c8d58..0000000 --- a/source/CPDLCPlugin/Controls/BeveledLine.cs +++ /dev/null @@ -1,106 +0,0 @@ -using System.Windows; -using System.Windows.Controls; -using System.Windows.Media; - -namespace CPDLCPlugin.Controls; - -public class BeveledLine : FrameworkElement -{ - public static readonly DependencyProperty OrientationProperty = - DependencyProperty.Register( - nameof(Orientation), - typeof(Orientation), - typeof(BeveledLine), - new FrameworkPropertyMetadata( - Orientation.Horizontal, - FrameworkPropertyMetadataOptions.AffectsRender, - OnOrientationChanged)); - - public static readonly DependencyProperty FlippedProperty = - DependencyProperty.Register( - nameof(Flipped), - typeof(bool), - typeof(BeveledLine), - new FrameworkPropertyMetadata( - false, - FrameworkPropertyMetadataOptions.AffectsRender, - OnFlippedChanged)); - - public Orientation Orientation - { - get => (Orientation)GetValue(OrientationProperty); - set => SetValue(OrientationProperty, value); - } - - public bool Flipped - { - get => (bool)GetValue(FlippedProperty); - set => SetValue(FlippedProperty, value); - } - - static void OnOrientationChanged(object sender, DependencyPropertyChangedEventArgs args) - { - if (sender is not BeveledLine separator) - return; - - separator.Orientation = (Orientation)args.NewValue; - separator.InvalidateVisual(); - } - - static void OnFlippedChanged(object sender, DependencyPropertyChangedEventArgs args) - { - if (sender is not BeveledLine separator) - return; - - separator.Flipped = (bool)args.NewValue; - separator.InvalidateVisual(); - } - - protected override void OnRender(DrawingContext drawingContext) - { - switch (Orientation) - { - case Orientation.Horizontal: - { - var topBrush = Flipped ? Theme.DarkBrush : Theme.LightBrush; - var topPen = new Pen(topBrush, 0); - var topGeometry = GetGeometry(0, 0, ActualWidth, ActualHeight / 2); - drawingContext.DrawGeometry(topBrush, topPen, topGeometry); - - var bottomBrush = Flipped ? Theme.LightBrush : Theme.DarkBrush; - var bottomPen = new Pen(bottomBrush, 0); - var bottomGeometry = GetGeometry(0, ActualHeight / 2, ActualWidth, ActualHeight); - drawingContext.DrawGeometry(bottomBrush, bottomPen, bottomGeometry); - break; - } - case Orientation.Vertical: - { - var leftBrush = Flipped ? Theme.DarkBrush : Theme.LightBrush; - var leftPen = new Pen(leftBrush, 0); - var leftGeometry = GetGeometry(0, 0, ActualWidth / 2, ActualHeight); - drawingContext.DrawGeometry(leftBrush, leftPen, leftGeometry); - - var bottomBrush = Flipped ? Theme.LightBrush : Theme.DarkBrush; - var bottomPen = new Pen(bottomBrush, 0); - var bottomGeometry = GetGeometry(ActualWidth / 2, 0, ActualWidth, ActualHeight); - drawingContext.DrawGeometry(bottomBrush, bottomPen, bottomGeometry); - break; - } - } - } - - Geometry GetGeometry(double left, double top, double right, double bottom) - { - var segments = new Point[] - { - new(left, top), - new(right, top), - new(right, bottom), - new(left, bottom), - new(left, top) - } - .Select(p => new LineSegment(p, false)); - - return new PathGeometry([new PathFigure(new Point(left, top), segments, true)]); - } -} diff --git a/source/CPDLCPlugin/Controls/Chevron.cs b/source/CPDLCPlugin/Controls/Chevron.cs deleted file mode 100644 index dda6c89..0000000 --- a/source/CPDLCPlugin/Controls/Chevron.cs +++ /dev/null @@ -1,280 +0,0 @@ -using System.Windows; -using System.Windows.Controls; -using System.Windows.Media; - -namespace CPDLCPlugin.Controls; - -public enum Direction -{ - Left, Up, Right, Down -}; - -/// -/// A chevron control with 3D beveled edges -/// -public class Chevron : Control -{ - public static readonly DependencyProperty DirectionProperty = - DependencyProperty.Register( - nameof(Direction), - typeof(Direction), - typeof(Chevron), - new FrameworkPropertyMetadata( - Direction.Up, - FrameworkPropertyMetadataOptions.AffectsRender)); - - public Direction Direction - { - get => (Direction) GetValue(DirectionProperty); - set => SetValue(DirectionProperty, value); - } - - public Chevron() - { - Width = 8; - Height = 8; - } - - protected override void OnRender(DrawingContext dc) - { - base.OnRender(dc); - - var width = ActualWidth; - var height = ActualHeight; - - if (width <= 0 || height <= 0) - return; - - DrawBeveledChevron(dc, width, height, Direction); - } - - private void DrawBeveledChevron(DrawingContext dc, double width, double height, Direction direction) - { - var foreground = Foreground ?? Brushes.Black; - var lineWidth = Theme.BeveledLineWidth / 2; - - switch (direction) - { - case Direction.Up: - DrawUpChevron(dc, width, height, foreground, lineWidth); - break; - case Direction.Down: - DrawDownChevron(dc, width, height, foreground, lineWidth); - break; - case Direction.Left: - DrawLeftChevron(dc, width, height, foreground, lineWidth); - break; - case Direction.Right: - DrawRightChevron(dc, width, height, foreground, lineWidth); - break; - } - } - - void DrawUpChevron(DrawingContext dc, double width, double height, Brush foreground, double lineWidth) - { - // Outer triangle: top vertex at (width/2, 0), bottom vertices at (0, height) and (width, height) - var outerTop = new Point(width / 2, 0); - var outerBottomLeft = new Point(0, height); - var outerBottomRight = new Point(width, height); - - // Draw full background triangle - var backgroundGeometry = new PathGeometry([ - new PathFigure(outerTop, [ - new LineSegment(outerBottomRight, true), - new LineSegment(outerBottomLeft, true) - ], true) - ]); - dc.DrawGeometry(foreground, null, backgroundGeometry); - - var innerTop = new Point(width / 2, lineWidth); - var innerBottomLeft = new Point(lineWidth, height - lineWidth); - var innerBottomRight = new Point(width - lineWidth, height - lineWidth); - - // Draw beveled edges as polygons on top - // Left edge: Light (trapezoid from outer to inner) - var leftBevelGeometry = new PathGeometry([ - new PathFigure(outerBottomLeft, [ - new LineSegment(outerTop, true), - new LineSegment(innerTop, true), - new LineSegment(innerBottomLeft, true) - ], true) - ]); - dc.DrawGeometry(Theme.LightBrush, null, leftBevelGeometry); - - // Right edge: Dark - var rightBevelGeometry = new PathGeometry([ - new PathFigure(outerTop, [ - new LineSegment(outerBottomRight, true), - new LineSegment(innerBottomRight, true), - new LineSegment(innerTop, true) - ], true) - ]); - dc.DrawGeometry(Theme.DarkBrush, null, rightBevelGeometry); - - // Bottom edge: Dark - var bottomBevelGeometry = new PathGeometry([ - new PathFigure(outerBottomRight, [ - new LineSegment(outerBottomLeft, true), - new LineSegment(innerBottomLeft, true), - new LineSegment(innerBottomRight, true) - ], true) - ]); - dc.DrawGeometry(Theme.DarkBrush, null, bottomBevelGeometry); - } - - void DrawDownChevron(DrawingContext dc, double width, double height, Brush foreground, double lineWidth) - { - // Outer triangle: bottom vertex at (width/2, height), top vertices at (0, 0) and (width, 0) - var outerBottom = new Point(width / 2, height); - var outerTopLeft = new Point(0, 0); - var outerTopRight = new Point(width, 0); - - // Draw full background triangle - var backgroundGeometry = new PathGeometry([ - new PathFigure(outerBottom, [ - new LineSegment(outerTopLeft, true), - new LineSegment(outerTopRight, true) - ], true) - ]); - dc.DrawGeometry(foreground, null, backgroundGeometry); - - var innerBottom = new Point(width / 2, height - lineWidth); - var innerTopLeft = new Point(lineWidth, lineWidth); - var innerTopRight = new Point(width - lineWidth, lineWidth); - - // Draw beveled edges as polygons on top - // Top edge: Light - var topBevelGeometry = new PathGeometry([ - new PathFigure(outerTopLeft, [ - new LineSegment(outerTopRight, true), - new LineSegment(innerTopRight, true), - new LineSegment(innerTopLeft, true) - ], true) - ]); - dc.DrawGeometry(Theme.LightBrush, null, topBevelGeometry); - - // Right edge: Dark - var rightBevelGeometry = new PathGeometry([ - new PathFigure(outerTopRight, [ - new LineSegment(outerBottom, true), - new LineSegment(innerBottom, true), - new LineSegment(innerTopRight, true) - ], true) - ]); - dc.DrawGeometry(Theme.DarkBrush, null, rightBevelGeometry); - - // Left edge: Light - var leftBevelGeometry = new PathGeometry([ - new PathFigure(outerBottom, [ - new LineSegment(outerTopLeft, true), - new LineSegment(innerTopLeft, true), - new LineSegment(innerBottom, true) - ], true) - ]); - dc.DrawGeometry(Theme.LightBrush, null, leftBevelGeometry); - } - - void DrawLeftChevron(DrawingContext dc, double width, double height, Brush foreground, double lineWidth) - { - // Outer triangle: left vertex at (0, height/2), right vertices at (width, 0) and (width, height) - var outerLeft = new Point(0, height / 2); - var outerTopRight = new Point(width, 0); - var outerBottomRight = new Point(width, height); - - // Draw full background triangle - var backgroundGeometry = new PathGeometry([ - new PathFigure(outerLeft, [ - new LineSegment(outerTopRight, true), - new LineSegment(outerBottomRight, true) - ], true) - ]); - dc.DrawGeometry(foreground, null, backgroundGeometry); - - var innerLeft = new Point(lineWidth, height / 2); - var innerTopRight = new Point(width - lineWidth, lineWidth); - var innerBottomRight = new Point(width - lineWidth, height - lineWidth); - - // Draw beveled edges as polygons on top - // Top edge: Light - var topBevelGeometry = new PathGeometry([ - new PathFigure(outerTopRight, [ - new LineSegment(outerLeft, true), - new LineSegment(innerLeft, true), - new LineSegment(innerTopRight, true) - ], true) - ]); - dc.DrawGeometry(Theme.LightBrush, null, topBevelGeometry); - - // Bottom edge: Dark - var bottomBevelGeometry = new PathGeometry([ - new PathFigure(outerLeft, [ - new LineSegment(outerBottomRight, true), - new LineSegment(innerBottomRight, true), - new LineSegment(innerLeft, true) - ], true) - ]); - dc.DrawGeometry(Theme.DarkBrush, null, bottomBevelGeometry); - - // Right edge: Dark - var rightBevelGeometry = new PathGeometry([ - new PathFigure(outerBottomRight, [ - new LineSegment(outerTopRight, true), - new LineSegment(innerTopRight, true), - new LineSegment(innerBottomRight, true) - ], true) - ]); - dc.DrawGeometry(Theme.DarkBrush, null, rightBevelGeometry); - } - - void DrawRightChevron(DrawingContext dc, double width, double height, Brush foreground, double lineWidth) - { - // Outer triangle: right vertex at (width, height/2), left vertices at (0, 0) and (0, height) - var outerRight = new Point(width, height / 2); - var outerTopLeft = new Point(0, 0); - var outerBottomLeft = new Point(0, height); - - // Draw full background triangle - var backgroundGeometry = new PathGeometry([ - new PathFigure(outerRight, [ - new LineSegment(outerBottomLeft, true), - new LineSegment(outerTopLeft, true) - ], true) - ]); - dc.DrawGeometry(foreground, null, backgroundGeometry); - - var innerRight = new Point(width - lineWidth, height / 2); - var innerTopLeft = new Point(lineWidth, lineWidth); - var innerBottomLeft = new Point(lineWidth, height - lineWidth); - - // Draw beveled edges as polygons on top - // Left edge: Light - var leftBevelGeometry = new PathGeometry([ - new PathFigure(outerBottomLeft, [ - new LineSegment(outerTopLeft, true), - new LineSegment(innerTopLeft, true), - new LineSegment(innerBottomLeft, true) - ], true) - ]); - dc.DrawGeometry(Theme.LightBrush, null, leftBevelGeometry); - - // Top edge: Light - var topBevelGeometry = new PathGeometry([ - new PathFigure(outerTopLeft, [ - new LineSegment(outerRight, true), - new LineSegment(innerRight, true), - new LineSegment(innerTopLeft, true) - ], true) - ]); - dc.DrawGeometry(Theme.LightBrush, null, topBevelGeometry); - - // Bottom edge: Dark - var bottomBevelGeometry = new PathGeometry([ - new PathFigure(outerRight, [ - new LineSegment(outerBottomLeft, true), - new LineSegment(innerBottomLeft, true), - new LineSegment(innerRight, true) - ], true) - ]); - dc.DrawGeometry(Theme.DarkBrush, null, bottomBevelGeometry); - } -} diff --git a/source/CPDLCPlugin/Controls/CustomScrollBar.xaml b/source/CPDLCPlugin/Controls/CustomScrollBar.xaml deleted file mode 100644 index 612e3ac..0000000 --- a/source/CPDLCPlugin/Controls/CustomScrollBar.xaml +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/source/CPDLCPlugin/Controls/CustomScrollBar.xaml.cs b/source/CPDLCPlugin/Controls/CustomScrollBar.xaml.cs deleted file mode 100644 index 780c264..0000000 --- a/source/CPDLCPlugin/Controls/CustomScrollBar.xaml.cs +++ /dev/null @@ -1,186 +0,0 @@ -using System.Windows; -using System.Windows.Controls; -using System.Windows.Input; - -namespace CPDLCPlugin.Controls; - -public partial class CustomScrollBar : UserControl -{ - bool _isDragging; - Point _lastMousePosition; - - public static readonly DependencyProperty ScrollViewerProperty = - DependencyProperty.Register( - nameof(ScrollViewer), - typeof(ScrollViewer), - typeof(CustomScrollBar), - new PropertyMetadata(null, OnScrollViewerChanged)); - - public ScrollViewer? ScrollViewer - { - get => (ScrollViewer?)GetValue(ScrollViewerProperty); - set => SetValue(ScrollViewerProperty, value); - } - - public CustomScrollBar() - { - InitializeComponent(); - } - - void UserControl_Loaded(object sender, RoutedEventArgs e) - { - if (PART_ScrollUpButton != null) - PART_ScrollUpButton.MouseLeftButtonDown += OnUpButtonClick; - - if (PART_ScrollDownButton != null) - PART_ScrollDownButton.MouseLeftButtonDown += OnDownButtonClick; - - if (PART_Thumb != null) - { - PART_Thumb.MouseLeftButtonDown += OnThumbMouseDown; - PART_Thumb.MouseLeftButtonUp += OnThumbMouseUp; - PART_Thumb.MouseMove += OnThumbMouseMove; - } - - // Force initial update - Dispatcher.BeginInvoke(new Action(() => UpdateScrollBar())); - UpdateScrollBar(); - } - - static void OnScrollViewerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - if (d is CustomScrollBar scrollBar) - { - if (e.OldValue is ScrollViewer oldScrollViewer) - { - oldScrollViewer.ScrollChanged -= scrollBar.OnScrollChanged; - } - - if (e.NewValue is ScrollViewer newScrollViewer) - { - newScrollViewer.ScrollChanged += scrollBar.OnScrollChanged; - } - - scrollBar.UpdateScrollBar(); - } - } - - void OnScrollChanged(object? sender, ScrollChangedEventArgs e) - { - UpdateScrollBar(); - } - - void OnUpButtonClick(object sender, MouseButtonEventArgs e) - { - ScrollViewer?.LineUp(); - } - - void OnDownButtonClick(object sender, MouseButtonEventArgs e) - { - ScrollViewer?.LineDown(); - } - - void OnThumbMouseDown(object sender, MouseButtonEventArgs e) - { - if (PART_Thumb != null && PART_Track != null) - { - _isDragging = true; - _lastMousePosition = e.GetPosition(PART_Thumb); - PART_Thumb.CaptureMouse(); - } - } - - void OnThumbMouseUp(object sender, MouseButtonEventArgs e) - { - if (PART_Thumb != null && _isDragging) - { - _isDragging = false; - PART_Thumb.ReleaseMouseCapture(); - } - } - - void OnThumbMouseMove(object sender, MouseEventArgs e) - { - if (_isDragging && PART_Track != null && ScrollViewer != null && ScrollViewer.ScrollableHeight > 0) - { - var currentTrackPosition = e.GetPosition(PART_Track); - var trackHeight = PART_Track.ActualHeight; - var thumbHeight = PART_Thumb?.ActualHeight ?? 20; - var scrollableTrackHeight = trackHeight - thumbHeight; - - if (scrollableTrackHeight > 0) - { - // Calculate where the thumb should be positioned - // currentTrackPosition.Y is where the mouse is relative to track - // _lastMousePosition.Y is the offset within the thumb where the mouse was clicked - var desiredThumbTop = currentTrackPosition.Y - _lastMousePosition.Y; - - // Clamp to valid range - var clampedThumbTop = Math.Max(0, Math.Min(scrollableTrackHeight, desiredThumbTop)); - - // Convert thumb position to scroll offset - var scrollRatio = clampedThumbTop / scrollableTrackHeight; - var newScrollOffset = scrollRatio * ScrollViewer.ScrollableHeight; - - ScrollViewer.ScrollToVerticalOffset(newScrollOffset); - } - } - } - - void UpdateScrollBar() - { - if (PART_Thumb == null || PART_Track == null) - return; - - // Always show the thumb for this UI style - PART_Thumb.Visibility = Visibility.Visible; - - if (ScrollViewer == null) - { - // Default thumb when no ScrollViewer - PART_Thumb.Height = 20; - PART_Thumb.Margin = new Thickness(1, 0, 1, 0); - return; - } - - var viewportHeight = ScrollViewer.ViewportHeight; - var contentHeight = ScrollViewer.ExtentHeight; - var scrollOffset = ScrollViewer.VerticalOffset; - - // Calculate thumb size and position - var trackHeight = PART_Track.ActualHeight; - - if (trackHeight <= 0) - { - // Track not ready yet - return; - } - - double thumbHeight; - double thumbPosition; - - if (contentHeight <= viewportHeight || ScrollViewer.ScrollableHeight <= 0) - { - // No scrolling needed - thumb takes full track height - thumbHeight = trackHeight; - thumbPosition = 0; - } - else - { - // Calculate proportional thumb based on viewport to content ratio - var ratio = viewportHeight / contentHeight; - thumbHeight = Math.Max(20, ratio * trackHeight); // Minimum 20px height - var scrollableHeight = trackHeight - thumbHeight; - thumbPosition = scrollableHeight * (scrollOffset / ScrollViewer.ScrollableHeight); - } - - PART_Thumb.Height = thumbHeight; - PART_Thumb.Margin = new Thickness(1, thumbPosition, 1, 0); - } - - protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) - { - base.OnRenderSizeChanged(sizeInfo); - UpdateScrollBar(); - } -} diff --git a/source/CPDLCPlugin/Controls/GridWithBorder.cs b/source/CPDLCPlugin/Controls/GridWithBorder.cs deleted file mode 100644 index d6395e0..0000000 --- a/source/CPDLCPlugin/Controls/GridWithBorder.cs +++ /dev/null @@ -1,131 +0,0 @@ -using System.Windows; -using System.Windows.Controls; -using System.Windows.Media; - -namespace CPDLCPlugin.Controls; - -public class GridWithBorder : Grid -{ - public static readonly DependencyProperty BorderBrushProperty = - DependencyProperty.Register( - nameof(BorderBrush), - typeof(Brush), - typeof(GridWithBorder), - new FrameworkPropertyMetadata( - Brushes.Black, - FrameworkPropertyMetadataOptions.AffectsRender)); - - public static readonly DependencyProperty BorderThicknessProperty = - DependencyProperty.Register( - nameof(BorderThickness), - typeof(double), - typeof(GridWithBorder), - new FrameworkPropertyMetadata( - 1.0, - FrameworkPropertyMetadataOptions.AffectsRender)); - - public Brush BorderBrush - { - get => (Brush)GetValue(BorderBrushProperty); - set => SetValue(BorderBrushProperty, value); - } - - public double BorderThickness - { - get => (double)GetValue(BorderThicknessProperty); - set => SetValue(BorderThicknessProperty, value); - } - - protected override void OnRender(DrawingContext dc) - { - base.OnRender(dc); - - if (BorderThickness <= 0) - return; - - var pen = new Pen(BorderBrush, BorderThickness); - - var rect = new Rect( - BorderThickness / 2, - BorderThickness / 2, - ActualWidth - BorderThickness, - ActualHeight - BorderThickness); - dc.DrawRectangle(null, pen, rect); - - // Draw vertical lines between columns - if (ColumnDefinitions.Count > 1) - { - double x = 0; - for (int i = 0; i < ColumnDefinitions.Count - 1; i++) - { - x += GetColumnActualWidth(i); - dc.DrawLine(pen, new Point(x, 0), new Point(x, ActualHeight)); - } - } - - // Draw horizontal lines between rows - if (RowDefinitions.Count > 1) - { - double y = 0; - for (int i = 0; i < RowDefinitions.Count - 1; i++) - { - y += GetRowActualHeight(i); - dc.DrawLine(pen, new Point(0, y), new Point(ActualWidth, y)); - } - } - } - - double GetColumnActualWidth(int columnIndex) - { - if (columnIndex < 0 || columnIndex >= ColumnDefinitions.Count) - return 0; - - var columnDefinition = ColumnDefinitions[columnIndex]; - - // Use reflection to access the internal ActualWidth property - var actualWidthProperty = typeof(ColumnDefinition).GetProperty("ActualWidth", - System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); - - if (actualWidthProperty != null) - { - var width = (double)actualWidthProperty.GetValue(columnDefinition); - if (width > 0) return width; - } - - // Fallback: For fixed width columns, use the Width value - if (columnDefinition.Width.IsAbsolute) - { - return columnDefinition.Width.Value; - } - - // Final fallback: equal distribution - return ActualWidth / ColumnDefinitions.Count; - } - - double GetRowActualHeight(int rowIndex) - { - if (rowIndex < 0 || rowIndex >= RowDefinitions.Count) - return 0; - - var rowDefinition = RowDefinitions[rowIndex]; - - // Use reflection to access the internal ActualHeight property - var actualHeightProperty = typeof(RowDefinition).GetProperty("ActualHeight", - System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); - - if (actualHeightProperty != null) - { - var height = (double)actualHeightProperty.GetValue(rowDefinition); - if (height > 0) return height; - } - - // Fallback: For fixed height rows, use the Height value - if (rowDefinition.Height.IsAbsolute) - { - return rowDefinition.Height.Value; - } - - // Final fallback: equal distribution - return ActualHeight / RowDefinitions.Count; - } -} diff --git a/source/CPDLCPlugin/Controls/TextInput.xaml b/source/CPDLCPlugin/Controls/TextInput.xaml deleted file mode 100644 index ba5780e..0000000 --- a/source/CPDLCPlugin/Controls/TextInput.xaml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/source/CPDLCPlugin/Controls/TextInput.xaml.cs b/source/CPDLCPlugin/Controls/TextInput.xaml.cs deleted file mode 100644 index 817ccad..0000000 --- a/source/CPDLCPlugin/Controls/TextInput.xaml.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System.Text.RegularExpressions; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Input; - -namespace CPDLCPlugin.Controls; - -public partial class TextInput : UserControl -{ - public TextInput() - { - InitializeComponent(); - } - - public static readonly DependencyProperty MaxCharactersProperty = - DependencyProperty.Register(nameof(MaxCharacters), typeof(int), typeof(TextInput), new PropertyMetadata(100)); - - public int MaxCharacters - { - get => (int)GetValue(MaxCharactersProperty); - set => SetValue(MaxCharactersProperty, value); - } - - public static readonly DependencyProperty DigitsOnlyProperty = - DependencyProperty.Register(nameof(DigitsOnly), typeof(bool), typeof(TextInput), new PropertyMetadata(false)); - - public bool DigitsOnly - { - get => (bool)GetValue(DigitsOnlyProperty); - set => SetValue(DigitsOnlyProperty, value); - } - - public static readonly DependencyProperty ValueProperty = - DependencyProperty.Register(nameof(Value), typeof(string), typeof(TextInput), new PropertyMetadata("")); - - public string Value - { - get => InputBox.Text; - set => InputBox.Text = value; - } - - void InputBox_PreviewTextInput(object sender, TextCompositionEventArgs e) - { - if (DigitsOnly) - { - e.Handled = !Regex.IsMatch(e.Text, "^[0-9]*$"); - } - } - - void InputBox_TextChanged(object sender, TextChangedEventArgs e) - { - if (DigitsOnly) - { - var digitsOnly = Regex.Replace(InputBox.Text, "[^0-9]", ""); - if (InputBox.Text != digitsOnly) - { - var caretIndex = InputBox.CaretIndex; - InputBox.Text = digitsOnly; - InputBox.CaretIndex = caretIndex > digitsOnly.Length ? digitsOnly.Length : caretIndex; - } - } - } -} diff --git a/source/CPDLCPlugin/Converters/AddOneConverter.cs b/source/CPDLCPlugin/Converters/AddOneConverter.cs deleted file mode 100644 index 946093b..0000000 --- a/source/CPDLCPlugin/Converters/AddOneConverter.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System.Globalization; -using System.Windows.Data; - -namespace CPDLCPlugin.Converters; - -[ValueConversion(typeof(int), typeof(int))] -public class AddOneConverter : IValueConverter -{ - public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) - { - return value switch - { - int i => i + 1, - _ => 1 - }; - } - - public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) - { - return value switch - { - int i => i - 1, - _ => 0 - }; - } -} diff --git a/source/CPDLCPlugin/Converters/BoolToVisibilityConverter.cs b/source/CPDLCPlugin/Converters/BoolToVisibilityConverter.cs deleted file mode 100644 index 95214cc..0000000 --- a/source/CPDLCPlugin/Converters/BoolToVisibilityConverter.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Globalization; -using System.Windows; -using System.Windows.Data; - -namespace CPDLCPlugin.Converters; - -[ValueConversion(typeof(bool), typeof(Visibility))] -public class BoolToVisibilityConverter : IValueConverter -{ - public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) - { - if (value is not bool boolValue) - throw new NotSupportedException(); - - return boolValue ? Visibility.Visible : Visibility.Collapsed; - } - - public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } -} \ No newline at end of file diff --git a/source/CPDLCPlugin/Converters/DirectionToRotationAngleConverter.cs b/source/CPDLCPlugin/Converters/DirectionToRotationAngleConverter.cs deleted file mode 100644 index d2ac64b..0000000 --- a/source/CPDLCPlugin/Converters/DirectionToRotationAngleConverter.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Globalization; -using System.Windows.Data; -using CPDLCPlugin.Controls; - -namespace CPDLCPlugin.Converters; - -[ValueConversion(typeof(Direction), typeof(double))] -class DirectionToRotationAngleConverter : IValueConverter -{ - public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) - { - if (value is Direction direction) - { - return direction switch - { - Direction.Left => 270, - Direction.Up => 0, - Direction.Right => 90, - Direction.Down => 180, - _ => throw new ArgumentOutOfRangeException($"Unknown direction: {direction}") - }; - } - - throw new NotSupportedException(); - } - - public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } -} diff --git a/source/CPDLCPlugin/Converters/FontSizeToHeightConverter.cs b/source/CPDLCPlugin/Converters/FontSizeToHeightConverter.cs deleted file mode 100644 index 325b6ba..0000000 --- a/source/CPDLCPlugin/Converters/FontSizeToHeightConverter.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Windows.Data; - -namespace CPDLCPlugin.Converters; - -public class FontSizeToHeightConverter : IValueConverter -{ - const double ScaleFactor = 0.715; - - public object Convert(object? value, Type targetType, object? parameter, System.Globalization.CultureInfo culture) - { - if (value is not double size) - throw new NotSupportedException(); - - return size * ScaleFactor; - } - - public object ConvertBack(object? value, Type targetType, object? parameter, System.Globalization.CultureInfo culture) - { - throw new NotImplementedException(); - } -} \ No newline at end of file diff --git a/source/CPDLCPlugin/Converters/FontSizeToLineHeightConverter.cs b/source/CPDLCPlugin/Converters/FontSizeToLineHeightConverter.cs deleted file mode 100644 index 1e28196..0000000 --- a/source/CPDLCPlugin/Converters/FontSizeToLineHeightConverter.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Windows.Data; - -namespace CPDLCPlugin.Converters; - -public class FontSizeToLineHeightConverter : IValueConverter -{ - const double ScaleFactor = 0.875; - - public object Convert(object? value, Type targetType, object? parameter, System.Globalization.CultureInfo culture) - { - if (value is null) - throw new NotSupportedException(); - - return double.Parse(value.ToString()) * ScaleFactor; - } - - public object ConvertBack(object? value, Type targetType, object? parameter, System.Globalization.CultureInfo culture) - { - throw new NotImplementedException(); - } -} \ No newline at end of file diff --git a/source/CPDLCPlugin/Converters/HalfConverter.cs b/source/CPDLCPlugin/Converters/HalfConverter.cs deleted file mode 100644 index 6316791..0000000 --- a/source/CPDLCPlugin/Converters/HalfConverter.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Globalization; -using System.Windows; -using System.Windows.Data; - -namespace CPDLCPlugin.Converters; - -[ValueConversion(typeof(double), typeof(double))] -[ValueConversion(typeof(Thickness), typeof(Thickness))] -public class HalfConverter : IValueConverter -{ - public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) - { - return value switch - { - double d => d / 2, - Thickness t => new Thickness(t.Left / 2, t.Top / 2, t.Right / 2, t.Bottom / 2), - _ => throw new NotImplementedException() - }; - } - - public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) - { - return value switch - { - double d => d * 2, - Thickness t => new Thickness(t.Left * 2, t.Top * 2, t.Right * 2, t.Bottom * 2), - _ => throw new NotImplementedException() - }; - } -} diff --git a/source/CPDLCPlugin/Converters/TotalSecondsConverter.cs b/source/CPDLCPlugin/Converters/TotalSecondsConverter.cs deleted file mode 100644 index 451c45c..0000000 --- a/source/CPDLCPlugin/Converters/TotalSecondsConverter.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Globalization; -using System.Windows.Data; - -namespace CPDLCPlugin.Converters; - -[ValueConversion(typeof(TimeSpan), typeof(string))] -class TotalSecondsConverter : IValueConverter -{ - public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) - { - if (value is TimeSpan timeSpan) - return $"{timeSpan.TotalSeconds}s"; - - throw new NotSupportedException(); - } - - public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } -} diff --git a/source/CPDLCPlugin/CpdlcMessages.cs b/source/CPDLCPlugin/CpdlcMessages.cs new file mode 100644 index 0000000..cbda28c --- /dev/null +++ b/source/CPDLCPlugin/CpdlcMessages.cs @@ -0,0 +1,32 @@ +namespace CPDLCPlugin; + +/// +/// The messages that other plugins (for example, the buttons of the Eurocat Menus plugin) use to control the CPDLC +/// plugin. Send these messages to the mailbox . The plugin ignores the payload. +/// +public static class CpdlcMessages +{ + /// + /// Opens or closes the CPDLC Setup window. + /// + public const string ToggleSetupWindow = "dev.eoinmotherway.cpdlc.toggle-setup-window"; + + /// + /// Opens or closes the ADS Contract window for the selected track. + /// + public const string ToggleAdsContractWindow = "dev.eoinmotherway.cpdlc.toggle-ads-contract-window"; + + /// + /// Opens or closes the CPDLC History window for the selected track. + /// + public const string ToggleHistoryWindow = "dev.eoinmotherway.cpdlc.toggle-history-window"; + + // The plugin sends these messages to all plugins when a window opens or closes. The payload is an empty JSON object. + + public const string SetupWindowOpened = "dev.eoinmotherway.cpdlc.setup-window-opened"; + public const string SetupWindowClosed = "dev.eoinmotherway.cpdlc.setup-window-closed"; + public const string AdsContractWindowOpened = "dev.eoinmotherway.cpdlc.ads-contract-window-opened"; + public const string AdsContractWindowClosed = "dev.eoinmotherway.cpdlc.ads-contract-window-closed"; + public const string HistoryWindowOpened = "dev.eoinmotherway.cpdlc.history-window-opened"; + public const string HistoryWindowClosed = "dev.eoinmotherway.cpdlc.history-window-closed"; +} diff --git a/source/CPDLCPlugin/DpiAwareness.cs b/source/CPDLCPlugin/DpiAwareness.cs deleted file mode 100644 index ae2587a..0000000 --- a/source/CPDLCPlugin/DpiAwareness.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System.IO; -using Microsoft.Win32; - -namespace CPDLCPlugin; - -public static class DpiAwareness -{ - public static void EnsureDpiAwareness() - { - try - { - if (!TryGetVatSysExecutablePath(out var vatSysExecutablePath)) - return; - - const string registryPath = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"; - const string dpiValue = "DPIUNAWARE"; - - using var key = Registry.CurrentUser.OpenSubKey(registryPath, writable: false); - var existingValue = key?.GetValue(vatSysExecutablePath) as string; - - // If already set, exit early - if (existingValue != null && existingValue.Contains(dpiValue)) - return; - - // Set the registry key - using var writableKey = Registry.CurrentUser.OpenSubKey(registryPath, writable: true) - ?? Registry.CurrentUser.CreateSubKey(registryPath); - - writableKey.SetValue(vatSysExecutablePath, dpiValue, RegistryValueKind.String); - - // Restart vatSys to apply the DPI setting - RestartVatSys(); - } - catch (Exception ex) - { - Plugin.AddError(ex); - } - } - - static void RestartVatSys() - { - try - { - if (!TryGetVatSysExecutablePath(out var vatSysExecutablePath)) - return; - - System.Diagnostics.Process.Start(vatSysExecutablePath); - Environment.Exit(0); - } - catch (Exception ex) - { - Plugin.AddError(ex); - } - } - - static bool TryGetVatSysInstallationPath(out string? installationPath) - { - using var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Sawbe\vatSys"); - installationPath = key?.GetValue("Path") as string; - return !string.IsNullOrEmpty(installationPath) && Directory.Exists(installationPath); - } - - static bool TryGetVatSysExecutablePath(out string? executablePath) - { - try - { - if (!TryGetVatSysInstallationPath(out var installationPath)) - { - executablePath = null; - return false; - } - - executablePath = Path.Combine(installationPath, "bin", "vatSys.exe"); - return File.Exists(executablePath); - } - catch - { - executablePath = null; - return false; - } - } -} diff --git a/source/CPDLCPlugin/ErrorReporter.cs b/source/CPDLCPlugin/ErrorReporter.cs deleted file mode 100644 index eacfd27..0000000 --- a/source/CPDLCPlugin/ErrorReporter.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace CPDLCPlugin; - -public interface IErrorReporter -{ - void ReportError(Exception ex); - void ReportError(Exception ex, string message); -} - -public class ErrorReporter : IErrorReporter -{ - public void ReportError(Exception exception) - { - Plugin.AddError(exception); - } - - public void ReportError(Exception exception, string message) - { - Plugin.AddError(exception, message); - } -} \ No newline at end of file diff --git a/source/CPDLCPlugin/FakeAdscReportPatch.cs b/source/CPDLCPlugin/FakeAdscReportPatch.cs index b9af925..2267e2d 100644 --- a/source/CPDLCPlugin/FakeAdscReportPatch.cs +++ b/source/CPDLCPlugin/FakeAdscReportPatch.cs @@ -1,6 +1,7 @@ using System.Windows.Forms; using HarmonyLib; using vatsys; +using vatSysToolbox; namespace CPDLCPlugin; @@ -14,11 +15,13 @@ public static class FakeAdscReportPatch const string HarmonyId = "CPDLCPlugin.FakeAdscReport"; static Action? _onClick; + static IErrorReporter? _errorReporter; static volatile bool _armed; - public static void Apply(Action onClick) + public static void Apply(Action onClick, IErrorReporter errorReporter) { _onClick = onClick; + _errorReporter = errorReporter; var method = AccessTools.Method("vatsys.ASDControlDX:ASD_MouseDown") ?? throw new MissingMethodException("Cannot find the vatSys method vatsys.ASDControlDX:ASD_MouseDown"); @@ -48,7 +51,7 @@ static bool AsdMouseDownPrefix(object __instance, MouseEventArgs e) } catch (Exception ex) { - Plugin.AddError(ex, "Cannot send a fake ADS-C report"); + _errorReporter?.ReportError(ex, "Cannot send a fake ADS-C report"); } return false; diff --git a/source/CPDLCPlugin/GuiInvoker.cs b/source/CPDLCPlugin/GuiInvoker.cs deleted file mode 100644 index 6ecafb3..0000000 --- a/source/CPDLCPlugin/GuiInvoker.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System.Windows.Forms; -using vatsys; - -namespace CPDLCPlugin; - -public interface IGuiInvoker -{ - void InvokeOnGUI(Action
action); -} - -public class GuiInvoker : IGuiInvoker -{ - public void InvokeOnGUI(Action action) - { - var mainForm = Application.OpenForms["MainForm"]; - if (mainForm == null) - return; - - // Check if the window handle is valid before invoking - if (mainForm.IsDisposed || !mainForm.IsHandleCreated) - return; - - // If already on UI thread, execute directly to avoid deadlock - if (!mainForm.InvokeRequired) - { - action(mainForm); - return; - } - - try - { - MMI.InvokeOnGUI(delegate { action(mainForm); }); - } - catch (ObjectDisposedException) - { - // Control was disposed during invocation - ignore during shutdown - } - catch (InvalidOperationException) - { - // Window handle was destroyed during invocation - ignore during shutdown - } - } -} \ No newline at end of file diff --git a/source/CPDLCPlugin/IClock.cs b/source/CPDLCPlugin/IClock.cs deleted file mode 100644 index 22d9f79..0000000 --- a/source/CPDLCPlugin/IClock.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace CPDLCPlugin; - -public interface IClock -{ - DateTimeOffset UtcNow(); -} - -public class SystemClock : IClock -{ - public DateTimeOffset UtcNow() => DateTimeOffset.UtcNow; -} diff --git a/source/CPDLCPlugin/IWindowHandle.cs b/source/CPDLCPlugin/IWindowHandle.cs deleted file mode 100644 index db03c65..0000000 --- a/source/CPDLCPlugin/IWindowHandle.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Windows.Forms; - -namespace CPDLCPlugin; - -public interface IWindowHandle -{ - event EventHandler? Closed; - event EventHandler? Moved; - - void Close(); -} - -public class FormWindowHandle : IWindowHandle -{ - readonly Form _form; - - public FormWindowHandle(Form form) - { - _form = form; - _form.FormClosed += (_, _) => Closed?.Invoke(this, EventArgs.Empty); - _form.Move += (_, _) => Moved?.Invoke(this, EventArgs.Empty); - } - - public event EventHandler? Closed; - public event EventHandler? Moved; - - public void Close() - { - _form.Close(); - } -} diff --git a/source/CPDLCPlugin/LabelItems/TextStatusLabelItemProvider.cs b/source/CPDLCPlugin/LabelItems/TextStatusLabelItemProvider.cs index 24a954e..c0e2f23 100644 --- a/source/CPDLCPlugin/LabelItems/TextStatusLabelItemProvider.cs +++ b/source/CPDLCPlugin/LabelItems/TextStatusLabelItemProvider.cs @@ -1,9 +1,10 @@ using vatsys; using vatsys.Plugin; +using vatSysToolbox; namespace CPDLCPlugin.LabelItems; -public class TextStatusLabelItemProvider(ColourCache colourCache) +public class TextStatusLabelItemProvider(ColourCache colourCache, IErrorReporter errorReporter) { public CustomLabelItem? GetLabelItem(string itemType, FDP2.FDR? fdr) { @@ -82,7 +83,7 @@ public class TextStatusLabelItemProvider(ColourCache colourCache) } catch (Exception ex) { - Plugin.AddError(ex, "Failed to handle label item click"); + errorReporter.ReportError(ex, "Failed to handle label item click"); } }; @@ -143,7 +144,7 @@ public class TextStatusLabelItemProvider(ColourCache colourCache) } catch (Exception ex) { - Plugin.AddError(ex, "Failed to handle strip item click"); + errorReporter.ReportError(ex, "Failed to handle strip item click"); } }; diff --git a/source/CPDLCPlugin/Messages/AdscReportExpiredNotification.cs b/source/CPDLCPlugin/Messages/AdscReportExpiredNotification.cs new file mode 100644 index 0000000..d742765 --- /dev/null +++ b/source/CPDLCPlugin/Messages/AdscReportExpiredNotification.cs @@ -0,0 +1,25 @@ +using CommunityToolkit.Mvvm.Messaging; +using MediatR; +using Serilog; + +namespace CPDLCPlugin.Messages; + +public record AdscReportExpiredNotification(string Callsign, string StationId) : INotification; + +public class AdscReportExpiredNotificationHandler( + AdscReportStore adscReportStore, + AdscTrackDisplay adscTrackDisplay, + ILogger logger) + : INotificationHandler +{ + public async Task Handle(AdscReportExpiredNotification notification, CancellationToken cancellationToken) + { + logger.Information("ADS-C report from {Callsign} via {StationId} expired", notification.Callsign, notification.StationId); + + // The aircraft can have a newer report from a different ATSU. Then the ADS-C track stays. + await adscReportStore.Remove(notification.Callsign, notification.StationId, cancellationToken); + adscTrackDisplay.Remove(notification.Callsign, notification.StationId); + + WeakReferenceMessenger.Default.Send(notification); + } +} diff --git a/source/CPDLCPlugin/Messages/AuthenticateRequest.cs b/source/CPDLCPlugin/Messages/AuthenticateRequest.cs new file mode 100644 index 0000000..548b08c --- /dev/null +++ b/source/CPDLCPlugin/Messages/AuthenticateRequest.cs @@ -0,0 +1,30 @@ +using CommunityToolkit.Mvvm.Messaging; +using CPDLCPlugin.Server; +using CPDLCServer.Contracts; +using MediatR; +using Serilog; + +namespace CPDLCPlugin.Messages; + +// Opens the browser, so that the user can log in to the CPDLC server with VATSIM +public record AuthenticateRequest(string ServerEndpoint) : IRequest; + +public class AuthenticateRequestHandler( + PluginAuthenticator authenticator, + TokenStore tokenStore, + AuthenticationState authenticationState, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(AuthenticateRequest request, CancellationToken cancellationToken) + { + var server = ServerAddress.GetBaseUri(request.ServerEndpoint); + + var response = await authenticator.Authenticate(server, cancellationToken); + tokenStore.Save(server, response.AccessToken); + authenticationState.Set(server, new PluginUserDto(response.Cid, response.Name, response.Expires)); + + logger.Information("Authenticated with {Server} as {Name} ({Cid})", server, response.Name, response.Cid); + WeakReferenceMessenger.Default.Send(new AuthenticationChangedNotification()); + } +} diff --git a/source/CPDLCPlugin/Messages/AuthenticationChangedNotification.cs b/source/CPDLCPlugin/Messages/AuthenticationChangedNotification.cs new file mode 100644 index 0000000..d1c1187 --- /dev/null +++ b/source/CPDLCPlugin/Messages/AuthenticationChangedNotification.cs @@ -0,0 +1,4 @@ +namespace CPDLCPlugin.Messages; + +// Sent with the WeakReferenceMessenger when the plugin authenticates or logs out +public record AuthenticationChangedNotification; diff --git a/source/CPDLCPlugin/Messages/CheckAuthenticationRequest.cs b/source/CPDLCPlugin/Messages/CheckAuthenticationRequest.cs new file mode 100644 index 0000000..cb98fc7 --- /dev/null +++ b/source/CPDLCPlugin/Messages/CheckAuthenticationRequest.cs @@ -0,0 +1,38 @@ +using CommunityToolkit.Mvvm.Messaging; +using CPDLCPlugin.Server; +using MediatR; +using Serilog; + +namespace CPDLCPlugin.Messages; + +// Asks the CPDLC server if the saved token is valid. Returns the token, or null when the plugin is not authenticated. +// A token that the server does not accept is deleted. +public record CheckAuthenticationRequest(string ServerEndpoint) : IRequest; + +public class CheckAuthenticationRequestHandler( + PluginAuthenticator authenticator, + TokenStore tokenStore, + AuthenticationState authenticationState, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(CheckAuthenticationRequest request, CancellationToken cancellationToken) + { + var server = ServerAddress.GetBaseUri(request.ServerEndpoint); + + var token = tokenStore.Get(server); + var user = token is null ? null : await authenticator.GetUser(server, token, cancellationToken); + + if (token is not null && user is null) + { + logger.Information("The server {Server} did not accept the saved token. Deleting it", server); + tokenStore.Delete(server); + token = null; + } + + authenticationState.Set(server, user); + WeakReferenceMessenger.Default.Send(new AuthenticationChangedNotification()); + + return token; + } +} diff --git a/source/CPDLCPlugin/Messages/ConnectRequest.cs b/source/CPDLCPlugin/Messages/ConnectRequest.cs index 4ee8cf3..73906d9 100644 --- a/source/CPDLCPlugin/Messages/ConnectRequest.cs +++ b/source/CPDLCPlugin/Messages/ConnectRequest.cs @@ -1,54 +1,71 @@ -using CPDLCPlugin.Server; -using MediatR; -using Serilog; -using vatsys; - -namespace CPDLCPlugin.Messages; - -public record ConnectRequest(string ServerEndpoint, string StationId) : IRequest; - -public class ConnectRequestHandler(Plugin plugin, IMediator mediator, ILogger logger) : IRequestHandler -{ - public async Task Handle(ConnectRequest request, CancellationToken cancellationToken) - { - logger.Information("Connecting to {ServerEndpoint}", request.ServerEndpoint); - - // If already connected, disconnect first - if (plugin.ConnectionManager is not null) - { - logger.Information("Existing connection found, disconnecting"); - if (plugin.ConnectionManager.IsConnected) - { - await plugin.ConnectionManager.StopAsync(); - logger.Information("Existing connection stopped"); - } - - plugin.ConnectionManager.Dispose(); - plugin.ConnectionManager = null; - } - - if (!Network.IsConnected) - { - logger.Warning("Cannot connect to server: not connected to VATSIM"); - throw new Exception("Not connected to VATSIM"); - } - - logger.Verbose("Creating SignalR connection"); - var downlinkHandler = new MediatorMessageHandler(mediator); - plugin.ConnectionManager = new SignalRConnectionManager( - request.ServerEndpoint, - downlinkHandler, - logger.ForContext()); - - // Initialize the connection with the station ID and current callsign - logger.Information("Initializing SignalR connection"); - await plugin.ConnectionManager.InitializeAsync(request.StationId, Network.Callsign); - - // Start the connection - logger.Information("Starting SignalR connection"); - await plugin.ConnectionManager.StartAsync(); - - logger.Information("Connected to server"); - await mediator.Publish(new ConnectedNotification(), cancellationToken); - } -} +using CPDLCPlugin.Server; +using MediatR; +using Serilog; +using vatsys; +using vatSysToolbox; + +namespace CPDLCPlugin.Messages; + +public record ConnectRequest(string ServerEndpoint, string StationId) : IRequest; + +public class ConnectRequestHandler(Plugin plugin, IMediator mediator, IErrorReporter errorReporter, ILogger logger) : IRequestHandler +{ + public async Task Handle(ConnectRequest request, CancellationToken cancellationToken) + { + logger.Information("Connecting to {ServerEndpoint}", request.ServerEndpoint); + + // If already connected, disconnect first + if (plugin.ConnectionManager is not null) + { + logger.Information("Existing connection found, disconnecting"); + if (plugin.ConnectionManager.IsConnected) + { + await plugin.ConnectionManager.StopAsync(); + logger.Information("Existing connection stopped"); + } + + plugin.ConnectionManager.Dispose(); + plugin.ConnectionManager = null; + } + + if (!Network.IsConnected) + { + logger.Warning("Cannot connect to server: not connected to VATSIM"); + throw new Exception("Not connected to VATSIM"); + } + + // The CPDLC server is for the live network only + if (!Network.IsOfficialServer) + { + logger.Warning("Cannot connect to server: connected to the sweatbox"); + throw new Exception("Cannot connect to the CPDLC server on the sweatbox"); + } + + // Check the token first, so that an expired token gives a clear error + var token = await mediator.Send(new CheckAuthenticationRequest(request.ServerEndpoint), cancellationToken); + if (token is null) + { + logger.Warning("Cannot connect to server: not authenticated"); + throw new Exception("Not authenticated with the CPDLC server. Open SETUP and select Authenticate."); + } + + logger.Verbose("Creating SignalR connection"); + var downlinkHandler = new MediatorMessageHandler(mediator, errorReporter); + plugin.ConnectionManager = new SignalRConnectionManager( + request.ServerEndpoint, + token, + downlinkHandler, + logger.ForContext()); + + // Initialize the connection with the station ID and current callsign + logger.Information("Initializing SignalR connection"); + await plugin.ConnectionManager.InitializeAsync(request.StationId, Network.Callsign); + + // Start the connection + logger.Information("Starting SignalR connection"); + await plugin.ConnectionManager.StartAsync(); + + logger.Information("Connected to server"); + await mediator.Publish(new ConnectedNotification(), cancellationToken); + } +} diff --git a/source/CPDLCPlugin/Messages/ConnectedNotification.cs b/source/CPDLCPlugin/Messages/ConnectedNotification.cs index c958715..30e1c79 100644 --- a/source/CPDLCPlugin/Messages/ConnectedNotification.cs +++ b/source/CPDLCPlugin/Messages/ConnectedNotification.cs @@ -14,7 +14,6 @@ public class ConnectedNotificationHandler( AdscContractStore adscContractStore, AdscReportStore adscReportStore, AdscTrackDisplay adscTrackDisplay, - AtsuSettingsStore atsuSettingsStore, IJurisdictionChecker jurisdictionChecker, IMediator mediator, ILogger logger) @@ -29,15 +28,6 @@ public async Task Handle(ConnectedNotification notification, CancellationToken c return; } - // Load ATSU settings - logger.Verbose("Loading ATSU settings"); - var atsuSettings = await plugin.ConnectionManager.GetAtsuSettings(cancellationToken); - atsuSettingsStore.Set(atsuSettings); - logger.Information( - "Loaded ATSU settings for {StationId} (Default ADS-C reporting interval: {DefaultAdscReportingInterval})", - atsuSettings.StationId, - atsuSettings.DefaultAdscReportingInterval); - // Load dialogues logger.Verbose("Loading all dialogues"); var dialogues = await plugin.ConnectionManager.GetAllDialogues(cancellationToken); diff --git a/source/CPDLCPlugin/Messages/DisconnectedNotification.cs b/source/CPDLCPlugin/Messages/DisconnectedNotification.cs index 9afc7e2..0bdb414 100644 --- a/source/CPDLCPlugin/Messages/DisconnectedNotification.cs +++ b/source/CPDLCPlugin/Messages/DisconnectedNotification.cs @@ -13,7 +13,6 @@ public class DisconnectedNotificationBridge( AdscContractStore adscContractStore, AdscReportStore adscReportStore, AdscTrackDisplay adscTrackDisplay, - AtsuSettingsStore atsuSettingsStore, ILogger logger) : INotificationHandler { public async Task Handle(DisconnectedNotification notification, CancellationToken cancellationToken) @@ -36,9 +35,6 @@ public async Task Handle(DisconnectedNotification notification, CancellationToke logger.Information("Clearing ADS-C tracks"); adscTrackDisplay.Clear(); - logger.Information("Clearing ATSU settings"); - atsuSettingsStore.Clear(); - WeakReferenceMessenger.Default.Send(notification); } } diff --git a/source/CPDLCPlugin/Messages/LogOutRequest.cs b/source/CPDLCPlugin/Messages/LogOutRequest.cs new file mode 100644 index 0000000..e211759 --- /dev/null +++ b/source/CPDLCPlugin/Messages/LogOutRequest.cs @@ -0,0 +1,42 @@ +using CommunityToolkit.Mvvm.Messaging; +using CPDLCPlugin.Server; +using MediatR; +using Serilog; + +namespace CPDLCPlugin.Messages; + +// Revokes the token on the CPDLC server, and deletes it from this computer +public record LogOutRequest(string ServerEndpoint) : IRequest; + +public class LogOutRequestHandler( + PluginAuthenticator authenticator, + TokenStore tokenStore, + AuthenticationState authenticationState, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(LogOutRequest request, CancellationToken cancellationToken) + { + var server = ServerAddress.GetBaseUri(request.ServerEndpoint); + + var token = tokenStore.Get(server); + tokenStore.Delete(server); + authenticationState.Set(server, null); + WeakReferenceMessenger.Default.Send(new AuthenticationChangedNotification()); + + if (token is null) + return; + + try + { + await authenticator.Logout(server, token, cancellationToken); + } + catch (Exception ex) + { + // The token is deleted from this computer. It expires on the server later. + logger.Warning(ex, "Failed to revoke the token on {Server}", server); + } + + logger.Information("Logged out from {Server}", server); + } +} diff --git a/source/CPDLCPlugin/Messages/OpenADSContractWindowRequest.cs b/source/CPDLCPlugin/Messages/OpenADSContractWindowRequest.cs index 29e2438..ef83b01 100644 --- a/source/CPDLCPlugin/Messages/OpenADSContractWindowRequest.cs +++ b/source/CPDLCPlugin/Messages/OpenADSContractWindowRequest.cs @@ -2,6 +2,8 @@ using CPDLCPlugin.Windows; using MediatR; using Serilog; +using vatSysToolbox; +using vatSysToolbox.Windows; namespace CPDLCPlugin.Messages; @@ -12,10 +14,10 @@ public class OpenADSContractWindowRequestHandler( Plugin plugin, AdscContractStore adscContractStore, AdscReportStore adscReportStore, - AtsuSettingsStore atsuSettingsStore, IMediator mediator, IGuiInvoker guiInvoker, IErrorReporter errorReporter, + WindowEvents windowEvents, ILogger logger) : IRequestHandler { @@ -28,28 +30,25 @@ public Task Handle(OpenADSContractWindowRequest request, CancellationToken cance throw new Exception("Cannot open the ADS Contract window: not connected to the CPDLC server"); } - windowManager.FocusOrCreateWindow( + windowManager.OpenOrFocus( WindowKeys.ADSContract, "ADS Contract", windowHandle => { + windowEvents.Broadcast(windowHandle, CpdlcMessages.AdsContractWindowOpened, CpdlcMessages.AdsContractWindowClosed); + var viewModel = new ADSContractViewModel( plugin, adscContractStore, adscReportStore, - atsuSettingsStore, mediator, guiInvoker, errorReporter, request.Callsign); - return new ADSContractView(viewModel, windowHandle); + return new ADSContractView(viewModel); }, - configureForm: form => - { - form.HasMinimizeButton = false; - form.MinimizeBox = false; - }); + new WindowOptions { CanMinimise = false }); return Task.CompletedTask; } diff --git a/source/CPDLCPlugin/Messages/OpenConnectionRequestWindowRequest.cs b/source/CPDLCPlugin/Messages/OpenConnectionRequestWindowRequest.cs index e0ecb12..9f8e389 100644 --- a/source/CPDLCPlugin/Messages/OpenConnectionRequestWindowRequest.cs +++ b/source/CPDLCPlugin/Messages/OpenConnectionRequestWindowRequest.cs @@ -2,6 +2,8 @@ using CPDLCPlugin.ViewModels; using CPDLCPlugin.Windows; using MediatR; +using vatSysToolbox; +using vatSysToolbox.Windows; namespace CPDLCPlugin.Messages; @@ -18,9 +20,9 @@ public class OpenConnectionRequestWindowRequestHandler( public Task Handle(OpenConnectionRequestWindowRequest request, CancellationToken cancellationToken) { // Each window is specific to a callsign, so we always want a fresh window - windowManager.TryRemoveWindow(WindowKeys.ConnectionRequest); + windowManager.Close(WindowKeys.ConnectionRequest); - windowManager.FocusOrCreateWindow( + windowManager.OpenOrFocus( WindowKeys.ConnectionRequest, "CPDLC Connection Request", windowHandle => @@ -37,12 +39,7 @@ public Task Handle(OpenConnectionRequestWindowRequest request, CancellationToken var control = new ConnectionRequestView(viewModel); return control; }, - configureForm: form => - { - form.HasMinimizeButton = false; - form.MinimizeBox = false; - form.HasSendBackButton = false; - }); + new WindowOptions { CanMinimise = false, CanSendToBack = false }); return Task.CompletedTask; } diff --git a/source/CPDLCPlugin/Messages/OpenCurrentMessagesWindowRequest.cs b/source/CPDLCPlugin/Messages/OpenCurrentMessagesWindowRequest.cs index ff0d514..7f481d2 100644 --- a/source/CPDLCPlugin/Messages/OpenCurrentMessagesWindowRequest.cs +++ b/source/CPDLCPlugin/Messages/OpenCurrentMessagesWindowRequest.cs @@ -2,8 +2,10 @@ using CPDLCPlugin.Configuration; using CPDLCPlugin.ViewModels; using CPDLCPlugin.Windows; -using System.Drawing; +using System.Windows; using MediatR; +using vatSysToolbox; +using vatSysToolbox.Windows; namespace CPDLCPlugin.Messages; @@ -25,7 +27,7 @@ public Task Handle(OpenCurrentMessagesWindowRequest request, CancellationToken c // If the window is already open, tell it how it was opened WeakReferenceMessenger.Default.Send(request); - windowManager.FocusOrCreateWindow( + windowManager.OpenOrFocus( WindowKeys.CurrentMessages, "Current Messages", windowHandle => @@ -40,13 +42,12 @@ public Task Handle(OpenCurrentMessagesWindowRequest request, CancellationToken c jurisdictionChecker, closeWhenEmpty: request.OpenedAutomatically); - return new CurrentMessagesView(viewModel, windowHandle); + return new CurrentMessagesView(viewModel); }, - sizeToContent: false, - configureForm: form => + new WindowOptions { - form.Size = new Size(467, 320); - form.MinimumSize = new Size(140, 24); + Size = WindowSize.Absolute(467, 320), + MinimumSize = new Size(140, 24) }); return Task.CompletedTask; diff --git a/source/CPDLCPlugin/Messages/OpenEditorWindowRequest.cs b/source/CPDLCPlugin/Messages/OpenEditorWindowRequest.cs index 5e1924f..4cfe682 100644 --- a/source/CPDLCPlugin/Messages/OpenEditorWindowRequest.cs +++ b/source/CPDLCPlugin/Messages/OpenEditorWindowRequest.cs @@ -3,6 +3,8 @@ using CPDLCPlugin.Windows; using MediatR; using Serilog; +using vatSysToolbox; +using vatSysToolbox.Windows; namespace CPDLCPlugin.Messages; @@ -23,9 +25,9 @@ public Task Handle(OpenEditorWindowRequest request, CancellationToken cancellati { // Close any existing editor window before opening a new one // Each editor is specific to a callsign, so we always want a fresh window - windowManager.TryRemoveWindow(WindowKeys.Editor); + windowManager.Close(WindowKeys.Editor); - windowManager.FocusOrCreateWindow( + windowManager.OpenOrFocus( WindowKeys.Editor, request.Callsign, windowHandle => diff --git a/source/CPDLCPlugin/Messages/OpenHistoryWindowRequest.cs b/source/CPDLCPlugin/Messages/OpenHistoryWindowRequest.cs index cbb69ea..651ebde 100644 --- a/source/CPDLCPlugin/Messages/OpenHistoryWindowRequest.cs +++ b/source/CPDLCPlugin/Messages/OpenHistoryWindowRequest.cs @@ -1,9 +1,11 @@ using CPDLCPlugin.Configuration; using CPDLCPlugin.ViewModels; using CPDLCPlugin.Windows; -using System.Drawing; +using System.Windows; using System.Windows.Forms; using MediatR; +using vatSysToolbox; +using vatSysToolbox.Windows; namespace CPDLCPlugin.Messages; @@ -14,16 +16,19 @@ public class OpenHistoryWindowRequestHandler( PluginConfiguration pluginConfiguration, DialogueStore dialogueStore, IErrorReporter errorReporter, - IGuiInvoker guiInvoker) + IGuiInvoker guiInvoker, + WindowEvents windowEvents) : IRequestHandler { public Task Handle(OpenHistoryWindowRequest request, CancellationToken cancellationToken) { - windowManager.FocusOrCreateWindow( + windowManager.OpenOrFocus( WindowKeys.History, "CPDLC History", windowHandle => { + windowEvents.Broadcast(windowHandle, CpdlcMessages.HistoryWindowOpened, CpdlcMessages.HistoryWindowClosed); + var viewModel = new HistoryViewModel( pluginConfiguration, dialogueStore, @@ -33,13 +38,12 @@ public Task Handle(OpenHistoryWindowRequest request, CancellationToken cancellat return new HistoryView(viewModel, windowHandle); }, - sizeToContent: false, - configureForm: form => + new WindowOptions { // Only the height can change - form.Size = new Size(467, 320); - form.MinimumSize = new Size(467, 24); - form.MaximumSize = new Size(467, SystemInformation.VirtualScreen.Height); + Size = WindowSize.Absolute(467, 320), + MinimumSize = new Size(467, 24), + MaximumSize = new Size(467, SystemInformation.VirtualScreen.Height) }); return Task.CompletedTask; diff --git a/source/CPDLCPlugin/Messages/OpenSetupWindowRequest.cs b/source/CPDLCPlugin/Messages/OpenSetupWindowRequest.cs index 298955a..3797230 100644 --- a/source/CPDLCPlugin/Messages/OpenSetupWindowRequest.cs +++ b/source/CPDLCPlugin/Messages/OpenSetupWindowRequest.cs @@ -1,7 +1,10 @@ using CPDLCPlugin.Configuration; +using CPDLCPlugin.Server; using CPDLCPlugin.ViewModels; using CPDLCPlugin.Windows; using MediatR; +using vatSysToolbox; +using vatSysToolbox.Windows; namespace CPDLCPlugin.Messages; @@ -12,22 +15,29 @@ public class OpenSetupWindowRequestHandler( PluginConfiguration pluginConfiguration, IMediator mediator, Plugin plugin, - IErrorReporter errorReporter) + IErrorReporter errorReporter, + AuthenticationState authenticationState, + IGuiInvoker guiInvoker, + WindowEvents windowEvents) : IRequestHandler { public Task Handle(OpenSetupWindowRequest request, CancellationToken cancellationToken) { - windowManager.FocusOrCreateWindow( + windowManager.OpenOrFocus( WindowKeys.Setup, "CPDLC Setup", windowHandle => { + windowEvents.Broadcast(windowHandle, CpdlcMessages.SetupWindowOpened, CpdlcMessages.SetupWindowClosed); + // Create the view model with current configuration and connection state var isConnected = plugin.ConnectionManager?.IsConnected ?? false; var viewModel = new SetupViewModel( mediator, errorReporter, windowHandle, + authenticationState, + guiInvoker, plugin.ConnectionManager?.ServerEndpoint ?? pluginConfiguration.ServerEndpoint, pluginConfiguration.Stations, isConnected ? plugin.ConnectionManager!.StationIdentifier : pluginConfiguration.Stations.First(), diff --git a/source/CPDLCPlugin/Messages/RebuildCpdlcStatusLabelItemsRequest.cs b/source/CPDLCPlugin/Messages/RebuildCpdlcStatusLabelItemsRequest.cs index feb5399..5c5fb5c 100644 --- a/source/CPDLCPlugin/Messages/RebuildCpdlcStatusLabelItemsRequest.cs +++ b/source/CPDLCPlugin/Messages/RebuildCpdlcStatusLabelItemsRequest.cs @@ -4,6 +4,7 @@ using Serilog; using vatsys; using vatsys.Plugin; +using vatSysToolbox; namespace CPDLCPlugin.Messages; diff --git a/source/CPDLCPlugin/Messages/SelectAdscReportingIntervalRequest.cs b/source/CPDLCPlugin/Messages/SelectAdscReportingIntervalRequest.cs index bcfe059..0fa7542 100644 --- a/source/CPDLCPlugin/Messages/SelectAdscReportingIntervalRequest.cs +++ b/source/CPDLCPlugin/Messages/SelectAdscReportingIntervalRequest.cs @@ -3,8 +3,8 @@ namespace CPDLCPlugin.Messages; -// A null reporting interval ends the selected contract and requests the default contract again -public record SelectAdscReportingIntervalRequest(string Callsign, TimeSpan? ReportingInterval) : IRequest; +// The default reporting interval of the ATSU requests the default contract. Any other interval requests a selected contract. +public record SelectAdscReportingIntervalRequest(string Callsign, TimeSpan ReportingInterval) : IRequest; public class SelectAdscReportingIntervalRequestHandler( Plugin plugin, @@ -15,13 +15,13 @@ public async Task Handle(SelectAdscReportingIntervalRequest request, Cancellatio { logger.Verbose( "Selecting ADS-C reporting interval {ReportingInterval} for {Callsign}", - request.ReportingInterval?.ToString() ?? "Default", + request.ReportingInterval, request.Callsign); if (plugin.ConnectionManager is null || !plugin.ConnectionManager.IsConnected) { logger.Warning( "Cannot select ADS-C reporting interval {ReportingInterval} for {Callsign}: not connected to server", - request.ReportingInterval?.ToString() ?? "Default", + request.ReportingInterval, request.Callsign); return; } @@ -32,7 +32,7 @@ await plugin.ConnectionManager.RequestPeriodicAdscContract( cancellationToken); logger.Information( "Selected ADS-C reporting interval {ReportingInterval} for {Callsign}", - request.ReportingInterval?.ToString() ?? "Default", + request.ReportingInterval, request.Callsign); } } diff --git a/source/CPDLCPlugin/Messages/ToggleAdsContractWindowNotification.cs b/source/CPDLCPlugin/Messages/ToggleAdsContractWindowNotification.cs new file mode 100644 index 0000000..f594c67 --- /dev/null +++ b/source/CPDLCPlugin/Messages/ToggleAdsContractWindowNotification.cs @@ -0,0 +1,35 @@ +using CPDLCPlugin.Windows; +using MediatR; +using vatsys; +using vatSysToolbox.BackgroundWork; +using vatSysToolbox.MediatR; +using vatSysToolbox.Windows; + +namespace CPDLCPlugin.Messages; + +// Other plugins send this message to the mailbox of the plugin. See CpdlcMessages.ToggleAdsContractWindow. +public record ToggleAdsContractWindowNotification : INotification; + +// The messenger receives the messages on a background thread. The menu items open the windows on the work queue, thus +// this handler uses the work queue too. +[PluginMessageHandler(CpdlcMessages.ToggleAdsContractWindow)] +public class ToggleAdsContractWindowNotificationHandler(WindowManager windowManager, WorkQueue workQueue, IMediator mediator) + : INotificationHandler +{ + public Task Handle(ToggleAdsContractWindowNotification notification, CancellationToken cancellationToken) + { + workQueue.Enqueue(async workCancellationToken => + { + if (windowManager.IsOpen(WindowKeys.ADSContract)) + { + windowManager.Close(WindowKeys.ADSContract); + return; + } + + var selectedCallsign = MMI.SelectedTrack?.GetFDR()?.Callsign; + await mediator.Send(new OpenADSContractWindowRequest(selectedCallsign), workCancellationToken); + }); + + return Task.CompletedTask; + } +} diff --git a/source/CPDLCPlugin/Messages/ToggleHistoryWindowNotification.cs b/source/CPDLCPlugin/Messages/ToggleHistoryWindowNotification.cs new file mode 100644 index 0000000..f25cf47 --- /dev/null +++ b/source/CPDLCPlugin/Messages/ToggleHistoryWindowNotification.cs @@ -0,0 +1,35 @@ +using CPDLCPlugin.Windows; +using MediatR; +using vatsys; +using vatSysToolbox.BackgroundWork; +using vatSysToolbox.MediatR; +using vatSysToolbox.Windows; + +namespace CPDLCPlugin.Messages; + +// Other plugins send this message to the mailbox of the plugin. See CpdlcMessages.ToggleHistoryWindow. +public record ToggleHistoryWindowNotification : INotification; + +// The messenger receives the messages on a background thread. The menu items open the windows on the work queue, thus +// this handler uses the work queue too. +[PluginMessageHandler(CpdlcMessages.ToggleHistoryWindow)] +public class ToggleHistoryWindowNotificationHandler(WindowManager windowManager, WorkQueue workQueue, IMediator mediator) + : INotificationHandler +{ + public Task Handle(ToggleHistoryWindowNotification notification, CancellationToken cancellationToken) + { + workQueue.Enqueue(async workCancellationToken => + { + if (windowManager.IsOpen(WindowKeys.History)) + { + windowManager.Close(WindowKeys.History); + return; + } + + var selectedCallsign = MMI.SelectedTrack?.GetFDR()?.Callsign; + await mediator.Send(new OpenHistoryWindowRequest(selectedCallsign), workCancellationToken); + }); + + return Task.CompletedTask; + } +} diff --git a/source/CPDLCPlugin/Messages/ToggleSetupWindowNotification.cs b/source/CPDLCPlugin/Messages/ToggleSetupWindowNotification.cs new file mode 100644 index 0000000..774b48f --- /dev/null +++ b/source/CPDLCPlugin/Messages/ToggleSetupWindowNotification.cs @@ -0,0 +1,33 @@ +using CPDLCPlugin.Windows; +using MediatR; +using vatSysToolbox.BackgroundWork; +using vatSysToolbox.MediatR; +using vatSysToolbox.Windows; + +namespace CPDLCPlugin.Messages; + +// Other plugins send this message to the mailbox of the plugin. See CpdlcMessages.ToggleSetupWindow. +public record ToggleSetupWindowNotification : INotification; + +// The messenger receives the messages on a background thread. The menu items open the windows on the work queue, thus +// this handler uses the work queue too. +[PluginMessageHandler(CpdlcMessages.ToggleSetupWindow)] +public class ToggleSetupWindowNotificationHandler(WindowManager windowManager, WorkQueue workQueue, IMediator mediator) + : INotificationHandler +{ + public Task Handle(ToggleSetupWindowNotification notification, CancellationToken cancellationToken) + { + workQueue.Enqueue(async workCancellationToken => + { + if (windowManager.IsOpen(WindowKeys.Setup)) + { + windowManager.Close(WindowKeys.Setup); + return; + } + + await mediator.Send(new OpenSetupWindowRequest(), workCancellationToken); + }); + + return Task.CompletedTask; + } +} diff --git a/source/CPDLCPlugin/Messages/UpdateNextDataAuthorityRequest.cs b/source/CPDLCPlugin/Messages/UpdateNextDataAuthorityRequest.cs index 3f202d1..4b2c123 100644 --- a/source/CPDLCPlugin/Messages/UpdateNextDataAuthorityRequest.cs +++ b/source/CPDLCPlugin/Messages/UpdateNextDataAuthorityRequest.cs @@ -4,6 +4,7 @@ using MediatR; using Newtonsoft.Json; using Serilog; +using vatSysToolbox; namespace CPDLCPlugin.Messages; diff --git a/source/CPDLCPlugin/Plugin.cs b/source/CPDLCPlugin/Plugin.cs index 15c8ebb..8031669 100644 --- a/source/CPDLCPlugin/Plugin.cs +++ b/source/CPDLCPlugin/Plugin.cs @@ -1,734 +1,777 @@ -using System.ComponentModel.Composition; -using System.IO; -using System.Threading.Channels; -using System.Windows; -using System.Windows.Forms; -using System.Windows.Media; -using CommunityToolkit.Mvvm.Messaging; -using CPDLCPlugin.Configuration; -using CPDLCPlugin.Extensions; -using CPDLCPlugin.LabelItems; -using CPDLCPlugin.Messages; -using CPDLCPlugin.Server; -using CPDLCPlugin.Windows; -using MediatR; -using Microsoft.Extensions.DependencyInjection; -using Serilog; -using vatsys; -using vatsys.Plugin; - -namespace CPDLCPlugin; - -// TODO: Complex variable entry (popups and validation) -// TODO: Text message fallback -// TODO: window frame styling -// TODO: ADS-C - -[Export(typeof(IPlugin))] -public class Plugin : ILabelPlugin, IStripPlugin, IRecipient, IRecipient -{ -#if DEBUG - public const string Name = "CPDLC Plugin - Debug"; -#else - public const string Name = "CPDLC Plugin"; -#endif - - static readonly Dictionary ErrorMessages = new(); - - readonly CpdlcStatusLabelItemProvider _cpdlcStatusProvider; - readonly TextStatusLabelItemProvider _textStatusProvider; - readonly ColourCache _colourCache; - - readonly WorkQueue _workQueue; - PluginConfiguration? _configuration; - - BackgroundWorker? _ndaRecalculationWorker; - - ToolStripMenuItem? _installationMenuItem; - bool _labelsInstalled; - - const string InstallMenuLabel = "Install label items"; - const string UninstallMenuLabel = "Uninstall label items"; - - string IPlugin.Name => Name; - - IServiceProvider ServiceProvider { get; set; } - - public SignalRConnectionManager? ConnectionManager { get; set; } - - public Plugin() - { - DpiAwareness.EnsureDpiAwareness(); - - ConfigureTheme(); - _colourCache = CacheLabelColours(); - _cpdlcStatusProvider = new CpdlcStatusLabelItemProvider(); - _textStatusProvider = new TextStatusLabelItemProvider(_colourCache); - - var configuration = ConfigurationLoader.Load(); - _configuration = configuration; - ConfigureServices(configuration); - - ApplyAdscTrackPatches(); - ApplyFakeAdscReportPatch(); - - AddToolbarItems(); - - CheckXmlInstallation(); - - Network.Connected += NetworkConnected; - Network.Disconnected += NetworkDisconnected; - - WeakReferenceMessenger.Default.Register(this); - WeakReferenceMessenger.Default.Register(this); - - _workQueue = new WorkQueue(AddError, Log.Logger, new SystemClock()); - } - - void ConfigureServices(PluginConfiguration pluginConfiguration) - { - var logger = ConfigureLogger(pluginConfiguration); - - ServiceProvider = new ServiceCollection() - .AddSingleton(logger) - .AddSingleton(this) // TODO: Ick... Whatever we're relying on this for, move it into a separate service please. - .AddSingleton(pluginConfiguration) - .AddSingleton(new SystemClock()) - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton(_cpdlcStatusProvider) - .AddSingleton(_colourCache) - .AddMediatR(c => c.RegisterServicesFromAssemblies(typeof(Plugin).Assembly)) - .BuildServiceProvider(); - } - - ILogger ConfigureLogger(PluginConfiguration configuration) - { - var logFileName = Path.Combine(Helpers.GetFilesFolder(), "cpdlc_log.txt"); - - var logger = new LoggerConfiguration() - .WriteTo.File( - path: logFileName, - rollingInterval: RollingInterval.Day, - retainedFileCountLimit: configuration.MaxLogFileAgeDays, - outputTemplate: "{Timestamp:u} [{Level:u3}] {Message:lj}{NewLine}{Exception}") - .MinimumLevel.Is(configuration.LogLevel) - .CreateLogger(); - - Log.Logger = logger; - - return logger; - } - - void ApplyAdscTrackPatches() - { - try - { - AdscTrackPatches.Apply(ServiceProvider.GetRequiredService()); - } - catch (Exception ex) - { - AddError(ex, "Cannot show ADS-C tracks on the ASD"); - } - } - - void ApplyFakeAdscReportPatch() - { - try - { - FakeAdscReportPatch.Apply(SendFakeAdscReport); - } - catch (Exception ex) - { - AddError(ex, "Cannot use fake ADS-C reports"); - } - } - - // Runs on the UI thread when the ASD is clicked - void SendFakeAdscReport(Coordinate position) - { - var fdr = MMI.SelectedTrack?.GetFDR(); - if (fdr is null) - throw new InvalidOperationException("Select a track with a flight plan before you send a fake ADS-C report"); - - if (fdr.PRL == -1) - throw new InvalidOperationException($"{fdr.Callsign} has no reported level"); - - var now = DateTimeOffset.UtcNow; - var report = new CPDLCServer.Contracts.AdscReportDto( - fdr.Callsign, - ConnectionManager?.StationIdentifier ?? string.Empty, - now, - position.Latitude, - position.Longitude, - fdr.PRL, - now, - CPDLCServer.Contracts.AdscReportSource.Hoppie); - - Log.Information("Sending fake ADS-C report for {Callsign} at {Latitude} {Longitude} {Altitude}", - report.Callsign, - report.Latitude, - report.Longitude, - report.Altitude); - - _workQueue.Enqueue(async () => - { - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Publish(new AdscReportReceivedNotification(report)); - }); - } - - void NetworkConnected(object sender, EventArgs e) - { - Log.Information("Connected to VATSIM as {Callsign}", Network.Callsign); - _workQueue.Enqueue(() => - { - StartNdaRecalculationWorker(); - return Task.CompletedTask; - }); - - // TODO: Connect if auto-connect enabled - } - - void NetworkDisconnected(object sender, EventArgs e) - { - Log.Information("Disconnected from VATSIM"); - - try - { - _workQueue.Enqueue(StopNdaRecalculationWorker); - - _workQueue.Enqueue(async () => - { - var mediator = ServiceProvider.GetService(); - if (mediator is null) - return; - - await mediator.Send(new DisconnectRequest()).ConfigureAwait(false); - }); - } - catch (Exception ex) - { - AddError(ex); - } - } - - void StartNdaRecalculationWorker() - { - var interval = TimeSpan.FromMinutes(_configuration?.NdaRecalculationIntervalMinutes ?? 1); - Log.Information("Starting NDA recalculation worker (interval: {Interval})", interval); - _ndaRecalculationWorker = new BackgroundWorker(async cancellationToken => - { - while (!cancellationToken.IsCancellationRequested) - { - try - { - await Task.Delay(interval, cancellationToken); - await RecalculateNextDataAuthorityForAllAircraft(); - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - Log.Verbose("NDA recalculation worker cancellation requested"); - } - catch (Exception ex) - { - AddError(ex); - } - } - }); - } - - async Task StopNdaRecalculationWorker() - { - if (_ndaRecalculationWorker is null) - return; - - Log.Information("Stopping NDA recalculation worker"); - await _ndaRecalculationWorker.DisposeAsync(); - _ndaRecalculationWorker = null; - } - - async Task RecalculateNextDataAuthorityForAllAircraft() - { - var store = ServiceProvider.GetRequiredService(); - var connections = await store.All(CancellationToken.None); - - var ourAircraft = connections - .Where(c => c.StationId == ConnectionManager?.StationIdentifier && - c.DataAuthorityState == CPDLCServer.Contracts.DataAuthorityState.CurrentDataAuthority); - - foreach (var aircraft in ourAircraft) - { - var fdr = FDP2.GetFDRs.FirstOrDefault(f => f.Callsign == aircraft.Callsign); - if (fdr is null || !fdr.IsTrackedByMe) - continue; - - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Send(new UpdateNextDataAuthorityRequest(fdr.Callsign, fdr.GetSectorEntries())); - } - } - - public static void AddError(Exception exception) - { - Log.Error(exception, "An error has occurred"); - TryAddErrorInternal(exception); - } - - public static void AddError(Exception exception, string message) - { - Log.Error(exception, message); - TryAddErrorInternal(exception); - } - - static void TryAddErrorInternal(Exception exception) - { - lock (ErrorMessages) - { - // Don't flood the error window with the same message over and over again - if (ErrorMessages.TryGetValue(exception.Message, out var lastShown) && - DateTimeOffset.Now - lastShown <= TimeSpan.FromMinutes(1)) - return; - - Errors.Add(exception, Name); - ErrorMessages[exception.Message] = DateTimeOffset.Now; - } - } - - void ConfigureTheme() - { - Theme.BackgroundColor = GetColour(Colours.Identities.WindowBackground); - Theme.GenericTextColor = GetColour(Colours.Identities.GenericText); - Theme.InteractiveTextColor = GetColour(Colours.Identities.InteractiveText); - Theme.NonInteractiveTextColor = GetColour(Colours.Identities.NonInteractiveText); - Theme.SelectedButtonColor = GetColour(Colours.Identities.WindowButtonSelected); - - Theme.CPDLCBackgroundColor = GetColour(Colours.Identities.CPDLCMessageBackground); - Theme.CPDLCUplinkColor = GetColour(Colours.Identities.CPDLCUplink); - Theme.CPDLCDownlinkColor = GetColour(Colours.Identities.CPDLCDownlink); - Theme.CPDLCSendBackgroundColor = GetColour(Colours.Identities.CPDLCSendButton); - Theme.CPDLCHotButtonBackgroundColor = GetColour(Colours.Identities.CPDLCSendButton); - - Theme.FontFamily = new FontFamily(MMI.eurofont_xsml.FontFamily.Name); - Theme.FontSize = MMI.eurofont_xsml.Size; - Theme.FontWeight = MMI.eurofont_xsml.Bold ? FontWeights.Bold : FontWeights.Regular; - - SolidColorBrush GetColour(Colours.Identities identity) - { - return new SolidColorBrush(Colours.GetColour(identity).ToWindowsColor()); - } - } - - ColourCache CacheLabelColours() - { - // Need to cache these for thread-safe access - - var downlinkColor = Theme.CPDLCDownlinkColor.Color; - var customDownlinkColor = new CustomColour(downlinkColor.R, downlinkColor.G, downlinkColor.B); - - var unableColor = Theme.CPDLCUnableDownlinkColor.Color; - var customUnableDownlinkColor = new CustomColour(unableColor.R, unableColor.G, unableColor.B); - - var suspendedColor = Theme.CPDLCSuspendedColor.Color; - var customSuspendedColor = new CustomColour(suspendedColor.R, suspendedColor.G, suspendedColor.B); - - return new ColourCache - { - DownlinkBackgroundColour = customDownlinkColor, - UnableBackgroundColour = customUnableDownlinkColor, - SuspendedForegroundColour = customSuspendedColor - }; - } - - void AddToolbarItems() - { - const string menuItemCategory = "CPDLC"; - - var setupMenuItem = new CustomToolStripMenuItem( - CustomToolStripMenuItemWindowType.Main, - menuItemCategory, - new ToolStripMenuItem("Setup")); - setupMenuItem.Item.Click += (_, _) => - { - _workQueue.Enqueue(async () => - { - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Send(new OpenSetupWindowRequest()); - }); - }; - - MMI.AddCustomMenuItem(setupMenuItem); - - var currentMessagesMenuItem = new CustomToolStripMenuItem( - CustomToolStripMenuItemWindowType.Main, - menuItemCategory, - new ToolStripMenuItem("Current Messages")); - currentMessagesMenuItem.Item.Click += (_, _) => - { - _workQueue.Enqueue(async () => - { - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Send(new OpenCurrentMessagesWindowRequest(OpenedAutomatically: false)); - }); - }; - - MMI.AddCustomMenuItem(currentMessagesMenuItem); - - var historyMenuItem = new CustomToolStripMenuItem( - CustomToolStripMenuItemWindowType.Main, - menuItemCategory, - new ToolStripMenuItem("History")); - historyMenuItem.Item.Click += (_, _) => - { - _workQueue.Enqueue(async () => - { - var selectedCallsign = MMI.SelectedTrack?.GetFDR()?.Callsign; - - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Send(new OpenHistoryWindowRequest(selectedCallsign)); - }); - }; - - MMI.AddCustomMenuItem(historyMenuItem); - - var adsContractMenuItem = new CustomToolStripMenuItem( - CustomToolStripMenuItemWindowType.Main, - menuItemCategory, - new ToolStripMenuItem("ADS Contract")); - adsContractMenuItem.Item.Click += (_, _) => - { - _workQueue.Enqueue(async () => - { - var selectedCallsign = MMI.SelectedTrack?.GetFDR()?.Callsign; - - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Send(new OpenADSContractWindowRequest(selectedCallsign)); - }); - }; - - MMI.AddCustomMenuItem(adsContractMenuItem); - -#if DEBUG - var editorMenuItem = new CustomToolStripMenuItem( - CustomToolStripMenuItemWindowType.Main, - menuItemCategory, - new ToolStripMenuItem("CPDLC Editor")); - editorMenuItem.Item.Click += (_, _) => - { - _workQueue.Enqueue(async () => - { - var selectedCallsign = MMI.SelectedTrack?.GetFDR()?.Callsign; - if (selectedCallsign is null) - throw new InvalidOperationException("Select a track with a flight plan before you open the CPDLC Editor"); - - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Send(new OpenEditorWindowRequest(selectedCallsign)); - }); - }; - - MMI.AddCustomMenuItem(editorMenuItem); - - var fakeAdscReportMenuItem = new CustomToolStripMenuItem( - CustomToolStripMenuItemWindowType.Main, - menuItemCategory, - new ToolStripMenuItem("Fake ADS-C Report")); - fakeAdscReportMenuItem.Item.Click += (_, _) => FakeAdscReportPatch.Arm(); - - MMI.AddCustomMenuItem(fakeAdscReportMenuItem); -#endif - - if (_configuration?.ShowInstallationMenuItems ?? true) - { - var status = XmlInstaller.GetStatus(); - if (!string.IsNullOrEmpty(status.ErrorMessage)) - return; - - _labelsInstalled = status.IsInstalled; - - var toolStripItem = new ToolStripMenuItem(_labelsInstalled ? UninstallMenuLabel : InstallMenuLabel); - toolStripItem.Click += (_, _) => - { - if (_labelsInstalled) - RunUninstall(); - else - RunInstall(); - }; - - _installationMenuItem = toolStripItem; - - var menuItem = new CustomToolStripMenuItem( - CustomToolStripMenuItemWindowType.Main, - menuItemCategory, - toolStripItem); - MMI.AddCustomMenuItem(menuItem); - } - } - - void CheckXmlInstallation() - { - try - { - var status = XmlInstaller.GetStatus(); - if (!string.IsNullOrEmpty(status.ErrorMessage)) - { - Log.Warning("Could not verify Labels.xml/Strips.xml installation: {Error}", status.ErrorMessage); - return; - } - - if (!status.IsInstalled) - { - AddError(new InvalidOperationException("CPDLC Label and Strip items must be installed. Please install them from the CPDLC menu.")); - } - } - catch (Exception ex) - { - AddError(ex, "Failed to verify Labels.xml/Strips.xml installation"); - } - } - - void RunInstall() - { - try - { - var result = XmlInstaller.Install(); - if (result.Succeeded) - { - SetInstallationMenuState(installed: true); - System.Windows.Forms.MessageBox.Show( - "CPDLC label & strip items installed successfully.\n\nPlease restart vatSys to apply the changes.", - Name, - MessageBoxButtons.OK, - MessageBoxIcon.Information); - } - else - { - System.Windows.Forms.MessageBox.Show( - $"Failed to install CPDLC label & strip items.\n\n{result.ErrorMessage}", - Name, - MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } - catch (Exception ex) - { - AddError(ex, "Failed to install label & strip items"); - } - } - - void SetInstallationMenuState(bool installed) - { - _labelsInstalled = installed; - if (_installationMenuItem is not null) - _installationMenuItem.Text = installed ? UninstallMenuLabel : InstallMenuLabel; - } - - void RunUninstall() - { - try - { - var result = XmlInstaller.Uninstall(); - if (result.Succeeded) - { - SetInstallationMenuState(installed: false); - System.Windows.Forms.MessageBox.Show( - "CPDLC label & strip items uninstalled successfully.\n\nPlease restart vatSys to apply the changes.", - Name, - MessageBoxButtons.OK, - MessageBoxIcon.Information); - } - else - { - System.Windows.Forms.MessageBox.Show( - $"Failed to uninstall CPDLC label & strip items.\n\n{result.ErrorMessage}", - Name, - MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } - catch (Exception ex) - { - AddError(ex, "Failed to uninstall label & strip items"); - } - } - - public void OnFDRUpdate(FDP2.FDR updated) - { - try - { - // Record the last known owner of each FDR - _workQueue.Enqueue(async () => - { - Log.Verbose( - "{Callsign}: IsTracked {IsTracked}; IsTrackedByMe: {IsTrackedByMe}; Controller Tracking: {CurrentController}; Handoff Controller: {HandoffController}", - updated.Callsign, - updated.IsTracked, - updated.IsTrackedByMe, - updated.ControllerTracking?.Callsign, - updated.HandoffController?.Callsign); - - var jurisdictionChecker = ServiceProvider.GetRequiredService(); - - var previousRecord = jurisdictionChecker.GetOwnershipRecord(updated.Callsign); - jurisdictionChecker.RecordFdrOwner(updated.Callsign, updated.ControllerTracking?.Callsign); - - var record = jurisdictionChecker.GetOwnershipRecord(updated.Callsign); - - // Tell the Current Messages Window that the dialogues it must show can be different - if (previousRecord?.CurrentOwner != record?.CurrentOwner) - WeakReferenceMessenger.Default.Send(new FdrOwnerChanged(updated.Callsign)); - - if (record?.PreviousOwner != Network.Callsign) - return; - - // We were the previous owner, process the handoff - Log.Information("{Callsign} handoff to {NextController}", updated.Callsign, record.CurrentOwner); - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Publish(new HandoffCompletedNotification(updated.Callsign, record.CurrentOwner)); - }); - - // Ensure the next data authority is up-to-date - _workQueue.Enqueue(async () => - { - var handoffMediator = ServiceProvider.GetRequiredService(); - await handoffMediator.Send(new UpdateNextDataAuthorityRequest(updated.Callsign, updated.GetSectorEntries())); - }); - - // Re-build the CPDLC status label items - _workQueue.Enqueue(() => RebuildCpdlcStatusLabelItems()); - - // If this flight has any dialogues that we have jurisdiction over, open the current messages window - // Ensures flights handed off to us open the window so we can see their requests - // A closed dialogue stays in the window until it is archived (e.g. a downlink that needs no response) - _workQueue.Enqueue(async () => - { - var store = ServiceProvider.GetRequiredService(); - var jurisdictionChecker = ServiceProvider.GetRequiredService(); - - var hasDialoguesToDisplay = (await store.All(CancellationToken.None)) - .Where(d => d.AircraftCallsign == updated.Callsign) - .Any(d => !d.IsArchived && jurisdictionChecker.ShouldDisplayDialogue(d)); - - if (hasDialoguesToDisplay) - { - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Send(new OpenCurrentMessagesWindowRequest(OpenedAutomatically: true)); - } - }); - } - catch (Exception ex) - { - AddError(ex); - } - } - - public void OnRadarTrackUpdate(RDP.RadarTrack updated) {} - - public CustomLabelItem? GetCustomLabelItem( - string itemType, - Track track, - FDP2.FDR flightDataRecord, - RDP.RadarTrack radarTrack) - { - try - { - if (itemType.StartsWith("CPDLCPLUGIN_TEXTSTATUS")) - return _textStatusProvider.GetLabelItem(itemType, flightDataRecord); - - if (itemType.StartsWith("CPDLCPLUGIN_CPDLCSTATUS")) - return _cpdlcStatusProvider.GetLabelItem(itemType, flightDataRecord); - } - catch (Exception ex) - { - AddError(ex, "Failed to generate custom label item"); - } - - return null; - } - - public CustomStripItem? GetCustomStripItem( - string itemType, - Track track, - FDP2.FDR flightDataRecord, - RDP.RadarTrack radarTrack) - { - try - { - if (itemType.StartsWith("CPDLCPLUGIN_TEXTSTATUS")) - return _textStatusProvider.GetStripItem(itemType, flightDataRecord); - - if (itemType.StartsWith("CPDLCPLUGIN_CPDLCSTATUS")) - return _cpdlcStatusProvider.GetStripItem(itemType, flightDataRecord); - } - catch (Exception ex) - { - AddError(ex, "Failed to generate custom strip item"); - } - - return null; - } - - public CustomColour? SelectASDTrackColour(Track track) => null; - - public CustomColour? SelectGroundTrackColour(Track track) => null; - - async Task RebuildCpdlcStatusLabelItems(CancellationToken cancellationToken = default) - { - try - { - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Send(new RebuildCpdlcStatusLabelItemsRequest(), cancellationToken); - } - catch (Exception ex) - { - AddError(ex); - } - } - - public void Receive(ConnectedAircraftChanged _) - { - try - { - _workQueue.Enqueue(() => RebuildCpdlcStatusLabelItems()); - } - catch (Exception ex) - { - AddError(ex); - } - } - - public void Receive(DialogueChangedNotification dialogueChangedNotification) - { - try - { - _workQueue.Enqueue(async () => - { - await RebuildCpdlcStatusLabelItems().ConfigureAwait(false); - - // Try to open the Current Messages Window if this dialogue is relevant to the controller - var jurisdictionChecker = ServiceProvider.GetRequiredService(); - if (dialogueChangedNotification.Dialogue.IsArchived || - !jurisdictionChecker.ShouldDisplayDialogue(dialogueChangedNotification.Dialogue)) - { - return; - } - - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Send(new OpenCurrentMessagesWindowRequest(OpenedAutomatically: true)); - }); - } - catch (Exception ex) - { - AddError(ex); - } - } -} +using System.ComponentModel.Composition; +using System.IO; +using System.Windows.Forms; +using CommunityToolkit.Mvvm.Messaging; +using CPDLCPlugin.Configuration; +using CPDLCPlugin.Extensions; +using CPDLCPlugin.LabelItems; +using CPDLCPlugin.Messages; +using CPDLCPlugin.Server; +using CPDLCPlugin.Windows; +using MediatR; +using Microsoft.Extensions.DependencyInjection; +using Serilog; +using vatsys; +using vatsys.Plugin; +using vatSysToolbox; +using vatSysToolbox.BackgroundWork; +using vatSysToolbox.MediatR; +using vatSysToolbox.Messaging; +using vatSysToolbox.Windows; + +namespace CPDLCPlugin; + +// TODO: Complex variable entry (popups and validation) +// TODO: Text message fallback +// TODO: window frame styling +// TODO: ADS-C + +[Export(typeof(IPlugin))] +public class Plugin : ILabelPlugin, IStripPlugin, IRecipient, IRecipient +{ +#if DEBUG + public const string Name = "CPDLC Plugin - Debug"; +#else + public const string Name = "CPDLC Plugin"; +#endif + + /// + /// The name that other plugins use to send messages to this plugin. See . + /// + public const string MailboxName = "dev.eoinmotherway.cpdlc"; + + readonly CpdlcStatusLabelItemProvider _cpdlcStatusProvider; + readonly TextStatusLabelItemProvider _textStatusProvider; + readonly ColourCache _colourCache; + + readonly IErrorReporter _errorReporter; + readonly WorkQueue _workQueue; + + // 1 if a rebuild of the CPDLC status label items is in the work queue, and 0 if not + int _isLabelRebuildQueued; + + PluginConfiguration? _configuration; + + BackgroundTask? _ndaRecalculationWorker; + + ToolStripMenuItem? _installationMenuItem; + bool _labelsInstalled; + + const string InstallMenuLabel = "Install label items"; + const string UninstallMenuLabel = "Uninstall label items"; + + string IPlugin.Name => Name; + + IServiceProvider ServiceProvider { get; set; } + + public SignalRConnectionManager? ConnectionManager { get; set; } + + public Plugin() + { + _colourCache = CacheLabelColours(); + _cpdlcStatusProvider = new CpdlcStatusLabelItemProvider(); + + var configuration = ConfigurationLoader.Load(); + _configuration = configuration; + ConfigureServices(configuration); + + _errorReporter = ServiceProvider.GetRequiredService(); + _workQueue = ServiceProvider.GetRequiredService(); + _textStatusProvider = new TextStatusLabelItemProvider(_colourCache, _errorReporter); + + EnsureDpiAwareness(); + + ApplyAdscTrackPatches(); + ApplyFakeAdscReportPatch(); + + AddToolbarItems(); + + CheckXmlInstallation(); + + Network.Connected += NetworkConnected; + Network.Disconnected += NetworkDisconnected; + + WeakReferenceMessenger.Default.Register(this); + WeakReferenceMessenger.Default.Register(this); + + StartPluginMessenger(); + + // Check the saved token, so that the SETUP window shows the user. + // The server can be unavailable when vatSys starts, so a failure is not an error. + _workQueue.Enqueue(async cancellationToken => + { + try + { + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new CheckAuthenticationRequest(configuration.ServerEndpoint), cancellationToken); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to check the authentication with the CPDLC server"); + } + }); + } + + void ConfigureServices(PluginConfiguration pluginConfiguration) + { + var logger = ConfigureLogger(pluginConfiguration); + + ServiceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddSerilog(logger)) + .AddErrorReporter(Name) + .AddWindowManager() + .AddWorkQueue() + .AddPluginMessenger(MailboxName) + .AddSingleton(logger) + .AddSingleton(this) // TODO: Ick... Whatever we're relying on this for, move it into a separate service please. + .AddSingleton(pluginConfiguration) + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton(_cpdlcStatusProvider) + .AddSingleton(_colourCache) + .AddMediatR(c => c.RegisterServicesFromAssemblies(typeof(Plugin).Assembly)) + .BuildServiceProvider(); + } + + ILogger ConfigureLogger(PluginConfiguration configuration) + { + var logFileName = Path.Combine(Helpers.GetFilesFolder(), "cpdlc_log.txt"); + + var logger = new LoggerConfiguration() + .WriteTo.File( + path: logFileName, + rollingInterval: RollingInterval.Day, + retainedFileCountLimit: configuration.MaxLogFileAgeDays, + outputTemplate: "{Timestamp:u} [{Level:u3}] {Message:lj}{NewLine}{Exception}") + .MinimumLevel.Is(configuration.LogLevel) + .CreateLogger(); + + Log.Logger = logger; + + return logger; + } + + void EnsureDpiAwareness() + { + try + { + DpiAwareness.EnsureDpiAwareness(); + } + catch (Exception ex) + { + _errorReporter.ReportError(ex, "Cannot set the DPI awareness of vatSys"); + } + } + + // Handles the messages from other plugins. See CpdlcMessages. + void StartPluginMessenger() + { + try + { + var messenger = ServiceProvider.GetRequiredService(); + var mediator = ServiceProvider.GetRequiredService(); + messenger.SubscribeHandlers(typeof(Plugin).Assembly, mediator, new JsonMessageSerializer()); + messenger.Start(); + } + catch (Exception ex) + { + _errorReporter.ReportError(ex, "Cannot receive the messages from other plugins"); + } + } + + void ApplyAdscTrackPatches() + { + try + { + AdscTrackPatches.Apply(ServiceProvider.GetRequiredService()); + } + catch (Exception ex) + { + _errorReporter.ReportError(ex, "Cannot show ADS-C tracks on the ASD"); + } + } + + void ApplyFakeAdscReportPatch() + { + try + { + FakeAdscReportPatch.Apply(SendFakeAdscReport, _errorReporter); + } + catch (Exception ex) + { + _errorReporter.ReportError(ex, "Cannot use fake ADS-C reports"); + } + } + + // Runs on the UI thread when the ASD is clicked + void SendFakeAdscReport(Coordinate position) + { + var fdr = MMI.SelectedTrack?.GetFDR(); + if (fdr is null) + throw new InvalidOperationException("Select a track with a flight plan before you send a fake ADS-C report"); + + if (fdr.PRL == -1) + throw new InvalidOperationException($"{fdr.Callsign} has no reported level"); + + var now = DateTimeOffset.UtcNow; + var report = new CPDLCServer.Contracts.AdscReportDto( + fdr.Callsign, + ConnectionManager?.StationIdentifier ?? string.Empty, + now, + position.Latitude, + position.Longitude, + fdr.PRL, + now, + CPDLCServer.Contracts.AdscReportSource.Hoppie); + + Log.Information("Sending fake ADS-C report for {Callsign} at {Latitude} {Longitude} {Altitude}", + report.Callsign, + report.Latitude, + report.Longitude, + report.Altitude); + + _workQueue.Enqueue(async cancellationToken => + { + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Publish(new AdscReportReceivedNotification(report), cancellationToken); + }); + } + + void NetworkConnected(object sender, EventArgs e) + { + Log.Information("Connected to VATSIM as {Callsign}", Network.Callsign); + _workQueue.Enqueue(_ => + { + StartNdaRecalculationWorker(); + return Task.CompletedTask; + }); + + if (_configuration is { AutoConnect: true }) + { + var configuration = _configuration; + _workQueue.Enqueue(async cancellationToken => + { + Log.Information("Connecting to the CPDLC server automatically"); + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new ConnectRequest(configuration.ServerEndpoint, configuration.Stations.First()), cancellationToken); + }); + } + } + + void NetworkDisconnected(object sender, EventArgs e) + { + Log.Information("Disconnected from VATSIM"); + + try + { + _workQueue.Enqueue(_ => StopNdaRecalculationWorker()); + + _workQueue.Enqueue(async cancellationToken => + { + var mediator = ServiceProvider.GetService(); + if (mediator is null) + return; + + await mediator.Send(new DisconnectRequest(), cancellationToken).ConfigureAwait(false); + }); + } + catch (Exception ex) + { + _errorReporter.ReportError(ex); + } + } + + void StartNdaRecalculationWorker() + { + var interval = TimeSpan.FromMinutes(_configuration?.NdaRecalculationIntervalMinutes ?? 1); + Log.Information("Starting NDA recalculation worker (interval: {Interval})", interval); + _ndaRecalculationWorker = new BackgroundTask(async cancellationToken => + { + while (!cancellationToken.IsCancellationRequested) + { + try + { + await Task.Delay(interval, cancellationToken); + await RecalculateNextDataAuthorityForAllAircraft(); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + Log.Verbose("NDA recalculation worker cancellation requested"); + } + catch (Exception ex) + { + _errorReporter.ReportError(ex); + } + } + }); + _ndaRecalculationWorker.Start(); + } + + async Task StopNdaRecalculationWorker() + { + if (_ndaRecalculationWorker is null) + return; + + Log.Information("Stopping NDA recalculation worker"); + await _ndaRecalculationWorker.DisposeAsync(); + _ndaRecalculationWorker = null; + } + + async Task RecalculateNextDataAuthorityForAllAircraft() + { + var store = ServiceProvider.GetRequiredService(); + var connections = await store.All(CancellationToken.None); + + var ourAircraft = connections + .Where(c => c.StationId == ConnectionManager?.StationIdentifier && + c.DataAuthorityState == CPDLCServer.Contracts.DataAuthorityState.CurrentDataAuthority); + + foreach (var aircraft in ourAircraft) + { + var fdr = FDP2.GetFDRs.FirstOrDefault(f => f.Callsign == aircraft.Callsign); + if (fdr is null || !fdr.IsTrackedByMe) + continue; + + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new UpdateNextDataAuthorityRequest(fdr.Callsign, fdr.GetSectorEntries())); + } + } + + ColourCache CacheLabelColours() + { + // Need to cache these for thread-safe access + + var downlinkColor = VatSysColours.GetColour(Colours.Identities.CPDLCDownlink).Color; + var customDownlinkColor = new CustomColour(downlinkColor.R, downlinkColor.G, downlinkColor.B); + + var unableColor = Theme.CPDLCUnableDownlinkColor.Color; + var customUnableDownlinkColor = new CustomColour(unableColor.R, unableColor.G, unableColor.B); + + var suspendedColor = Theme.CPDLCSuspendedColor.Color; + var customSuspendedColor = new CustomColour(suspendedColor.R, suspendedColor.G, suspendedColor.B); + + return new ColourCache + { + DownlinkBackgroundColour = customDownlinkColor, + UnableBackgroundColour = customUnableDownlinkColor, + SuspendedForegroundColour = customSuspendedColor + }; + } + + void AddToolbarItems() + { + const string menuItemCategory = "CPDLC"; + + var setupMenuItem = new CustomToolStripMenuItem( + CustomToolStripMenuItemWindowType.Main, + menuItemCategory, + new ToolStripMenuItem("Setup")); + setupMenuItem.Item.Click += (_, _) => + { + _workQueue.Enqueue(async cancellationToken => + { + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new OpenSetupWindowRequest(), cancellationToken); + }); + }; + + MMI.AddCustomMenuItem(setupMenuItem); + + var currentMessagesMenuItem = new CustomToolStripMenuItem( + CustomToolStripMenuItemWindowType.Main, + menuItemCategory, + new ToolStripMenuItem("Current Messages")); + currentMessagesMenuItem.Item.Click += (_, _) => + { + _workQueue.Enqueue(async cancellationToken => + { + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new OpenCurrentMessagesWindowRequest(OpenedAutomatically: false), cancellationToken); + }); + }; + + MMI.AddCustomMenuItem(currentMessagesMenuItem); + + var historyMenuItem = new CustomToolStripMenuItem( + CustomToolStripMenuItemWindowType.Main, + menuItemCategory, + new ToolStripMenuItem("History")); + historyMenuItem.Item.Click += (_, _) => + { + _workQueue.Enqueue(async cancellationToken => + { + var selectedCallsign = MMI.SelectedTrack?.GetFDR()?.Callsign; + + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new OpenHistoryWindowRequest(selectedCallsign), cancellationToken); + }); + }; + + MMI.AddCustomMenuItem(historyMenuItem); + + var adsContractMenuItem = new CustomToolStripMenuItem( + CustomToolStripMenuItemWindowType.Main, + menuItemCategory, + new ToolStripMenuItem("ADS Contract")); + adsContractMenuItem.Item.Click += (_, _) => + { + _workQueue.Enqueue(async cancellationToken => + { + var selectedCallsign = MMI.SelectedTrack?.GetFDR()?.Callsign; + + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new OpenADSContractWindowRequest(selectedCallsign), cancellationToken); + }); + }; + + MMI.AddCustomMenuItem(adsContractMenuItem); + +#if DEBUG + var editorMenuItem = new CustomToolStripMenuItem( + CustomToolStripMenuItemWindowType.Main, + menuItemCategory, + new ToolStripMenuItem("CPDLC Editor")); + editorMenuItem.Item.Click += (_, _) => + { + _workQueue.Enqueue(async cancellationToken => + { + var selectedCallsign = MMI.SelectedTrack?.GetFDR()?.Callsign; + if (selectedCallsign is null) + throw new InvalidOperationException("Select a track with a flight plan before you open the CPDLC Editor"); + + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new OpenEditorWindowRequest(selectedCallsign), cancellationToken); + }); + }; + + MMI.AddCustomMenuItem(editorMenuItem); + + var fakeAdscReportMenuItem = new CustomToolStripMenuItem( + CustomToolStripMenuItemWindowType.Main, + menuItemCategory, + new ToolStripMenuItem("Fake ADS-C Report")); + fakeAdscReportMenuItem.Item.Click += (_, _) => FakeAdscReportPatch.Arm(); + + MMI.AddCustomMenuItem(fakeAdscReportMenuItem); +#endif + + if (_configuration?.ShowInstallationMenuItems ?? true) + { + var status = XmlInstaller.GetStatus(); + if (!string.IsNullOrEmpty(status.ErrorMessage)) + return; + + _labelsInstalled = status.IsInstalled; + + var toolStripItem = new ToolStripMenuItem(_labelsInstalled ? UninstallMenuLabel : InstallMenuLabel); + toolStripItem.Click += (_, _) => + { + if (_labelsInstalled) + RunUninstall(); + else + RunInstall(); + }; + + _installationMenuItem = toolStripItem; + + var menuItem = new CustomToolStripMenuItem( + CustomToolStripMenuItemWindowType.Main, + menuItemCategory, + toolStripItem); + MMI.AddCustomMenuItem(menuItem); + } + } + + void CheckXmlInstallation() + { + try + { + var status = XmlInstaller.GetStatus(); + if (!string.IsNullOrEmpty(status.ErrorMessage)) + { + Log.Warning("Could not verify Labels.xml/Strips.xml installation: {Error}", status.ErrorMessage); + return; + } + + if (!status.IsInstalled) + { + _errorReporter.ReportError(new InvalidOperationException("CPDLC Label and Strip items must be installed. Please install them from the CPDLC menu.")); + } + } + catch (Exception ex) + { + _errorReporter.ReportError(ex, "Failed to verify Labels.xml/Strips.xml installation"); + } + } + + void RunInstall() + { + try + { + var result = XmlInstaller.Install(); + if (result.Succeeded) + { + SetInstallationMenuState(installed: true); + System.Windows.Forms.MessageBox.Show( + "CPDLC label & strip items installed successfully.\n\nPlease restart vatSys to apply the changes.", + Name, + MessageBoxButtons.OK, + MessageBoxIcon.Information); + } + else + { + System.Windows.Forms.MessageBox.Show( + $"Failed to install CPDLC label & strip items.\n\n{result.ErrorMessage}", + Name, + MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + catch (Exception ex) + { + _errorReporter.ReportError(ex, "Failed to install label & strip items"); + } + } + + void SetInstallationMenuState(bool installed) + { + _labelsInstalled = installed; + if (_installationMenuItem is not null) + _installationMenuItem.Text = installed ? UninstallMenuLabel : InstallMenuLabel; + } + + void RunUninstall() + { + try + { + var result = XmlInstaller.Uninstall(); + if (result.Succeeded) + { + SetInstallationMenuState(installed: false); + System.Windows.Forms.MessageBox.Show( + "CPDLC label & strip items uninstalled successfully.\n\nPlease restart vatSys to apply the changes.", + Name, + MessageBoxButtons.OK, + MessageBoxIcon.Information); + } + else + { + System.Windows.Forms.MessageBox.Show( + $"Failed to uninstall CPDLC label & strip items.\n\n{result.ErrorMessage}", + Name, + MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + catch (Exception ex) + { + _errorReporter.ReportError(ex, "Failed to uninstall label & strip items"); + } + } + + public void OnFDRUpdate(FDP2.FDR updated) + { + try + { + // Record the last known owner of each FDR + _workQueue.Enqueue(async cancellationToken => + { + Log.Verbose( + "{Callsign}: IsTracked {IsTracked}; IsTrackedByMe: {IsTrackedByMe}; Controller Tracking: {CurrentController}; Handoff Controller: {HandoffController}", + updated.Callsign, + updated.IsTracked, + updated.IsTrackedByMe, + updated.ControllerTracking?.Callsign, + updated.HandoffController?.Callsign); + + var jurisdictionChecker = ServiceProvider.GetRequiredService(); + + var previousRecord = jurisdictionChecker.GetOwnershipRecord(updated.Callsign); + jurisdictionChecker.RecordFdrOwner(updated.Callsign, updated.ControllerTracking?.Callsign); + + var record = jurisdictionChecker.GetOwnershipRecord(updated.Callsign); + + // Tell the Current Messages Window that the dialogues it must show can be different + if (previousRecord?.CurrentOwner != record?.CurrentOwner) + WeakReferenceMessenger.Default.Send(new FdrOwnerChanged(updated.Callsign)); + + if (record?.PreviousOwner != Network.Callsign) + return; + + // We were the previous owner, process the handoff + Log.Information("{Callsign} handoff to {NextController}", updated.Callsign, record.CurrentOwner); + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Publish(new HandoffCompletedNotification(updated.Callsign, record.CurrentOwner), cancellationToken); + }); + + // Ensure the next data authority is up-to-date + _workQueue.Enqueue(async cancellationToken => + { + var handoffMediator = ServiceProvider.GetRequiredService(); + await handoffMediator.Send(new UpdateNextDataAuthorityRequest(updated.Callsign, updated.GetSectorEntries()), cancellationToken); + }); + + // Re-build the CPDLC status label items + QueueLabelRebuild(); + + // If this flight has any dialogues that we have jurisdiction over, open the current messages window + // Ensures flights handed off to us open the window so we can see their requests + // A closed dialogue stays in the window until it is archived (e.g. a downlink that needs no response) + _workQueue.Enqueue(async cancellationToken => + { + var store = ServiceProvider.GetRequiredService(); + var jurisdictionChecker = ServiceProvider.GetRequiredService(); + + var hasDialoguesToDisplay = (await store.All(cancellationToken)) + .Where(d => d.AircraftCallsign == updated.Callsign) + .Any(d => !d.IsArchived && jurisdictionChecker.ShouldDisplayDialogue(d)); + + // vatSys updates the FDRs often. If the window is open, do not post to the UI thread to open it again. + var windowManager = ServiceProvider.GetRequiredService(); + if (hasDialoguesToDisplay && !windowManager.IsOpen(WindowKeys.CurrentMessages)) + { + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new OpenCurrentMessagesWindowRequest(OpenedAutomatically: true), cancellationToken); + } + }); + } + catch (Exception ex) + { + _errorReporter.ReportError(ex); + } + } + + public void OnRadarTrackUpdate(RDP.RadarTrack updated) {} + + public CustomLabelItem? GetCustomLabelItem( + string itemType, + Track track, + FDP2.FDR flightDataRecord, + RDP.RadarTrack radarTrack) + { + try + { + if (itemType.StartsWith("CPDLCPLUGIN_TEXTSTATUS")) + return _textStatusProvider.GetLabelItem(itemType, flightDataRecord); + + if (itemType.StartsWith("CPDLCPLUGIN_CPDLCSTATUS")) + return _cpdlcStatusProvider.GetLabelItem(itemType, flightDataRecord); + } + catch (Exception ex) + { + _errorReporter.ReportError(ex, "Failed to generate custom label item"); + } + + return null; + } + + public CustomStripItem? GetCustomStripItem( + string itemType, + Track track, + FDP2.FDR flightDataRecord, + RDP.RadarTrack radarTrack) + { + try + { + if (itemType.StartsWith("CPDLCPLUGIN_TEXTSTATUS")) + return _textStatusProvider.GetStripItem(itemType, flightDataRecord); + + if (itemType.StartsWith("CPDLCPLUGIN_CPDLCSTATUS")) + return _cpdlcStatusProvider.GetStripItem(itemType, flightDataRecord); + } + catch (Exception ex) + { + _errorReporter.ReportError(ex, "Failed to generate custom strip item"); + } + + return null; + } + + public CustomColour? SelectASDTrackColour(Track track) => null; + + public CustomColour? SelectGroundTrackColour(Track track) => null; + + // vatSys updates the FDRs often, and each rebuild reads all the FDRs. A rebuild reads the state when it runs. Thus, + // if a rebuild is already in the work queue, do not queue another one. + void QueueLabelRebuild() + { + if (Interlocked.Exchange(ref _isLabelRebuildQueued, 1) == 1) + return; + + _workQueue.Enqueue(cancellationToken => + { + // Clear the flag before the rebuild reads the state. Then a change during the rebuild queues a new rebuild. + Interlocked.Exchange(ref _isLabelRebuildQueued, 0); + return RebuildCpdlcStatusLabelItems(cancellationToken); + }); + } + + async Task RebuildCpdlcStatusLabelItems(CancellationToken cancellationToken = default) + { + try + { + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new RebuildCpdlcStatusLabelItemsRequest(), cancellationToken); + } + catch (Exception ex) + { + _errorReporter.ReportError(ex); + } + } + + public void Receive(ConnectedAircraftChanged _) + { + try + { + QueueLabelRebuild(); + } + catch (Exception ex) + { + _errorReporter.ReportError(ex); + } + } + + public void Receive(DialogueChangedNotification dialogueChangedNotification) + { + try + { + // The rebuild is in the work queue before the next work item. Thus, the labels are rebuilt before the window + // opens. + QueueLabelRebuild(); + + _workQueue.Enqueue(async cancellationToken => + { + // Try to open the Current Messages Window if this dialogue is relevant to the controller + var jurisdictionChecker = ServiceProvider.GetRequiredService(); + if (dialogueChangedNotification.Dialogue.IsArchived || + !jurisdictionChecker.ShouldDisplayDialogue(dialogueChangedNotification.Dialogue)) + { + return; + } + + // If the window is open, do not post to the UI thread to open and activate it again + var windowManager = ServiceProvider.GetRequiredService(); + if (windowManager.IsOpen(WindowKeys.CurrentMessages)) + return; + + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new OpenCurrentMessagesWindowRequest(OpenedAutomatically: true), cancellationToken); + }); + } + catch (Exception ex) + { + _errorReporter.ReportError(ex); + } + } +} diff --git a/source/CPDLCPlugin/Server/AuthenticationState.cs b/source/CPDLCPlugin/Server/AuthenticationState.cs new file mode 100644 index 0000000..890e316 --- /dev/null +++ b/source/CPDLCPlugin/Server/AuthenticationState.cs @@ -0,0 +1,28 @@ +using CPDLCServer.Contracts; + +namespace CPDLCPlugin.Server; + +// The user that the plugin is authenticated as on a CPDLC server. The SETUP window shows it. +public class AuthenticationState +{ + readonly object _lock = new(); + Uri? _server; + PluginUserDto? _user; + + public PluginUserDto? GetUser(Uri server) + { + lock (_lock) + { + return _server == server ? _user : null; + } + } + + public void Set(Uri server, PluginUserDto? user) + { + lock (_lock) + { + _server = server; + _user = user; + } + } +} diff --git a/source/CPDLCPlugin/Server/IDownlinkHandlerDelegate.cs b/source/CPDLCPlugin/Server/IDownlinkHandlerDelegate.cs index 8e9b134..eaf5030 100644 --- a/source/CPDLCPlugin/Server/IDownlinkHandlerDelegate.cs +++ b/source/CPDLCPlugin/Server/IDownlinkHandlerDelegate.cs @@ -11,5 +11,6 @@ public interface IDownlinkHandlerDelegate Task AdscContractUpdated(AdscContractDto adscContractDto, CancellationToken cancellationToken); Task AdscContractRemoved(string callsign, string stationId, CancellationToken cancellationToken); Task AdscReportReceived(AdscReportDto adscReportDto, CancellationToken cancellationToken); + Task AdscReportExpired(string callsign, string stationId, CancellationToken cancellationToken); void Error(Exception exception); } diff --git a/source/CPDLCPlugin/Server/MediatorMessageHandler.cs b/source/CPDLCPlugin/Server/MediatorMessageHandler.cs index 3cb9099..33e883f 100644 --- a/source/CPDLCPlugin/Server/MediatorMessageHandler.cs +++ b/source/CPDLCPlugin/Server/MediatorMessageHandler.cs @@ -1,10 +1,11 @@ using CPDLCPlugin.Messages; using CPDLCServer.Contracts; using MediatR; +using vatSysToolbox; namespace CPDLCPlugin.Server; -public class MediatorMessageHandler(IMediator mediator) : IDownlinkHandlerDelegate +public class MediatorMessageHandler(IMediator mediator, IErrorReporter errorReporter) : IDownlinkHandlerDelegate { int _isDisconnecting; @@ -20,7 +21,7 @@ public async Task DialogueChanged(DialogueDto dialogue, CancellationToken cancel } catch (Exception ex) { - Plugin.AddError(ex, "Failed to handle DialogueChanged notification"); + errorReporter.ReportError(ex, "Failed to handle DialogueChanged notification"); } } @@ -36,7 +37,7 @@ public async Task AircraftConnectionUpdated(AircraftConnectionDto aircraftConnec } catch (Exception ex) { - Plugin.AddError(ex, "Failed to handle AircraftConnectionUpdated notification"); + errorReporter.ReportError(ex, "Failed to handle AircraftConnectionUpdated notification"); } } @@ -52,7 +53,7 @@ public async Task AircraftConnectionRemoved(string callsign, string stationId, C } catch (Exception ex) { - Plugin.AddError(ex, "Failed to handle AircraftConnectionRemoved notification"); + errorReporter.ReportError(ex, "Failed to handle AircraftConnectionRemoved notification"); } } @@ -68,7 +69,7 @@ public async Task AcarsStationsUpdated(string[] callsigns, CancellationToken can } catch (Exception ex) { - Plugin.AddError(ex, "Failed to handle AcarsStationsUpdated notification"); + errorReporter.ReportError(ex, "Failed to handle AcarsStationsUpdated notification"); } } @@ -84,7 +85,7 @@ public async Task AdscContractUpdated(AdscContractDto adscContractDto, Cancellat } catch (Exception ex) { - Plugin.AddError(ex, "Failed to handle AdscContractUpdated notification"); + errorReporter.ReportError(ex, "Failed to handle AdscContractUpdated notification"); } } @@ -100,7 +101,7 @@ public async Task AdscContractRemoved(string callsign, string stationId, Cancell } catch (Exception ex) { - Plugin.AddError(ex, "Failed to handle AdscContractRemoved notification"); + errorReporter.ReportError(ex, "Failed to handle AdscContractRemoved notification"); } } @@ -116,13 +117,29 @@ public async Task AdscReportReceived(AdscReportDto adscReportDto, CancellationTo } catch (Exception ex) { - Plugin.AddError(ex, "Failed to handle AdscReportReceived notification"); + errorReporter.ReportError(ex, "Failed to handle AdscReportReceived notification"); + } + } + + public async Task AdscReportExpired(string callsign, string stationId, CancellationToken cancellationToken) + { + try + { + await mediator.Publish(new AdscReportExpiredNotification(callsign, stationId), cancellationToken); + } + catch (OperationCanceledException) + { + // Expected when cancellation is requested + } + catch (Exception ex) + { + errorReporter.ReportError(ex, "Failed to handle AdscReportExpired notification"); } } public void Error(Exception error) { - Plugin.AddError(error, "Error from SignalR connection"); + errorReporter.ReportError(error, "Error from SignalR connection"); if (Interlocked.CompareExchange(ref _isDisconnecting, 1, 0) == 0) { _ = DisconnectAsync(); @@ -137,7 +154,7 @@ async Task DisconnectAsync() } catch (Exception ex) { - Plugin.AddError(ex, "Failed to disconnect after SignalR error"); + errorReporter.ReportError(ex, "Failed to disconnect after SignalR error"); } finally { diff --git a/source/CPDLCPlugin/Server/PluginAuthenticator.cs b/source/CPDLCPlugin/Server/PluginAuthenticator.cs new file mode 100644 index 0000000..d15dcea --- /dev/null +++ b/source/CPDLCPlugin/Server/PluginAuthenticator.cs @@ -0,0 +1,245 @@ +using System.Diagnostics; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Sockets; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using CPDLCServer.Contracts; +using Serilog; + +namespace CPDLCPlugin.Server; + +/// +/// Gets a token from the CPDLC server with the browser (OAuth authorization code with PKCE and a loopback redirect). +/// The plugin opens the login page in the browser. After the login, the browser goes to a port on this computer with a +/// one-use code. Then the plugin changes the code for a token. +/// +public class PluginAuthenticator(ILogger logger) +{ + static readonly TimeSpan LoginTimeout = TimeSpan.FromMinutes(5); + static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); + + readonly HttpClient _httpClient = CreateHttpClient(); + + public async Task Authenticate(Uri server, CancellationToken cancellationToken) + { + // A TcpListener does not need the URL reservation that an HttpListener needs + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + + try + { + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + var redirectUri = $"http://127.0.0.1:{port}/callback"; + var codeVerifier = Base64Url(RandomBytes(32)); + var codeChallenge = Base64Url(Sha256(codeVerifier)); + var state = Base64Url(RandomBytes(16)); + + var authorizeUri = new Uri( + server, + "plugin/authorize" + + $"?redirect_uri={Uri.EscapeDataString(redirectUri)}" + + $"&state={state}" + + $"&code_challenge={codeChallenge}" + + "&code_challenge_method=S256"); + + logger.Information("Opening the browser to authenticate with {Server}", server); + Process.Start(new ProcessStartInfo(authorizeUri.ToString()) { UseShellExecute = true }); + + var code = await WaitForCode(listener, state, cancellationToken); + + logger.Information("Getting a token from {Server}", server); + var response = await _httpClient.PostAsync( + new Uri(server, "plugin/token"), + new FormUrlEncodedContent(new Dictionary + { + ["code"] = code, + ["code_verifier"] = codeVerifier, + ["redirect_uri"] = redirectUri + }), + cancellationToken); + + if (!response.IsSuccessStatusCode) + throw new Exception($"The CPDLC server did not give a token ({(int)response.StatusCode})"); + + var json = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(json, JsonOptions) + ?? throw new Exception("The CPDLC server sent an empty token"); + } + finally + { + listener.Stop(); + } + } + + // Returns null when the server does not accept the token + public async Task GetUser(Uri server, string token, CancellationToken cancellationToken) + { + using var request = new HttpRequestMessage(HttpMethod.Get, new Uri(server, "plugin/me")); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + + using var response = await _httpClient.SendAsync(request, cancellationToken); + if (response.StatusCode == HttpStatusCode.Unauthorized) + return null; + + response.EnsureSuccessStatusCode(); + + var json = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(json, JsonOptions); + } + + public async Task Logout(Uri server, string token, CancellationToken cancellationToken) + { + using var request = new HttpRequestMessage(HttpMethod.Post, new Uri(server, "plugin/logout")); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + + using var response = await _httpClient.SendAsync(request, cancellationToken); + + // The token is not valid any more, so it is already logged out + if (response.StatusCode == HttpStatusCode.Unauthorized) + return; + + response.EnsureSuccessStatusCode(); + } + + async Task WaitForCode(TcpListener listener, string expectedState, CancellationToken cancellationToken) + { + using var timeoutCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeoutCancellationTokenSource.CancelAfter(LoginTimeout); + + // AcceptTcpClientAsync has no cancellation token in .NET Framework. Stopping the listener ends the wait. + using var _ = timeoutCancellationTokenSource.Token.Register(listener.Stop); + + while (true) + { + TcpClient client; + try + { + client = await listener.AcceptTcpClientAsync(); + } + catch (Exception ex) when ((ex is ObjectDisposedException or SocketException) && timeoutCancellationTokenSource.IsCancellationRequested) + { + cancellationToken.ThrowIfCancellationRequested(); + throw new TimeoutException("The authentication was not completed in 5 minutes"); + } + + using (client) + { + var stream = client.GetStream(); + var query = await ReadCallbackQuery(stream); + + // For example, the browser asks for /favicon.ico + if (query is null) + { + await WriteResponse(stream, "404 Not Found", "Not found."); + continue; + } + + query.TryGetValue("state", out var state); + query.TryGetValue("code", out var code); + + if (state != expectedState || string.IsNullOrEmpty(code)) + { + await WriteResponse(stream, "400 Bad Request", "The authentication failed. Try again from the SETUP window in vatSys."); + throw new Exception("The CPDLC server sent a response that is not valid"); + } + + await WriteResponse(stream, "200 OK", "The CPDLC plugin is authenticated. You can close this window and go back to vatSys."); + return code!; + } + } + } + + // Reads the request line, for example "GET /callback?code=...&state=... HTTP/1.1". + // Returns null when the request is not for the callback. + static async Task?> ReadCallbackQuery(Stream stream) + { + var reader = new StreamReader(stream, Encoding.ASCII, false, 1024, leaveOpen: true); + var requestLine = await reader.ReadLineAsync(); + + // Read the headers, so that the browser has sent all of the request before the response + string? header; + do + { + header = await reader.ReadLineAsync(); + } + while (!string.IsNullOrEmpty(header)); + + var parts = requestLine?.Split(' '); + if (parts is not { Length: 3 } || parts[0] != "GET") + return null; + + var target = parts[1]; + var queryStart = target.IndexOf('?'); + var path = queryStart < 0 ? target : target.Substring(0, queryStart); + if (path != "/callback" || queryStart < 0) + return null; + + var query = new Dictionary(); + foreach (var pair in target.Substring(queryStart + 1).Split('&')) + { + var separator = pair.IndexOf('='); + if (separator <= 0) + continue; + + var name = Uri.UnescapeDataString(pair.Substring(0, separator)); + var value = Uri.UnescapeDataString(pair.Substring(separator + 1).Replace('+', ' ')); + query[name] = value; + } + + return query; + } + + static async Task WriteResponse(Stream stream, string status, string message) + { + var body = "CPDLC plugin" + + "

" + WebUtility.HtmlEncode(message) + "

"; + var bodyBytes = Encoding.UTF8.GetBytes(body); + + var headers = $"HTTP/1.1 {status}\r\n" + + "Content-Type: text/html; charset=utf-8\r\n" + + $"Content-Length: {bodyBytes.Length}\r\n" + + "Connection: close\r\n\r\n"; + var headerBytes = Encoding.ASCII.GetBytes(headers); + + await stream.WriteAsync(headerBytes, 0, headerBytes.Length); + await stream.WriteAsync(bodyBytes, 0, bodyBytes.Length); + await stream.FlushAsync(); + } + + static byte[] RandomBytes(int count) + { + var bytes = new byte[count]; + using var random = RandomNumberGenerator.Create(); + random.GetBytes(bytes); + return bytes; + } + + static byte[] Sha256(string text) + { + using var sha256 = SHA256.Create(); + return sha256.ComputeHash(Encoding.ASCII.GetBytes(text)); + } + + static string Base64Url(byte[] bytes) + { + return Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + } + + static HttpClient CreateHttpClient() + { +#if DEBUG + // In DEBUG mode, bypass SSL certificate validation for local development + var handler = new HttpClientHandler + { + ServerCertificateCustomValidationCallback = (_, _, _, _) => true + }; + return new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(30) }; +#else + return new HttpClient { Timeout = TimeSpan.FromSeconds(30) }; +#endif + } +} diff --git a/source/CPDLCPlugin/Server/ServerAddress.cs b/source/CPDLCPlugin/Server/ServerAddress.cs new file mode 100644 index 0000000..65151a1 --- /dev/null +++ b/source/CPDLCPlugin/Server/ServerAddress.cs @@ -0,0 +1,14 @@ +namespace CPDLCPlugin.Server; + +public static class ServerAddress +{ + // The configuration has the URL of the hub, for example https://cpdlc.example.com/hubs/controller. + // The authentication endpoints are at the root of the same server. + public static Uri GetBaseUri(string serverEndpoint) + { + if (!Uri.TryCreate(serverEndpoint, UriKind.Absolute, out var endpoint)) + throw new ArgumentException($"The server URL {serverEndpoint} is not valid", nameof(serverEndpoint)); + + return new Uri(endpoint.GetLeftPart(UriPartial.Authority) + "/"); + } +} diff --git a/source/CPDLCPlugin/Server/SignalRConnectionManager.cs b/source/CPDLCPlugin/Server/SignalRConnectionManager.cs index ba93224..5e592a9 100644 --- a/source/CPDLCPlugin/Server/SignalRConnectionManager.cs +++ b/source/CPDLCPlugin/Server/SignalRConnectionManager.cs @@ -1,421 +1,419 @@ -using CPDLCServer.Contracts; -using Microsoft.AspNetCore.SignalR.Client; -using Microsoft.Extensions.DependencyInjection; -using Serilog; - -namespace CPDLCPlugin.Server; - -// TODO: Register this in the IoC container - -/// -/// Manages the SignalR connection to the CPDLC server. -/// -public class SignalRConnectionManager( - string serverEndpoint, - IDownlinkHandlerDelegate downlinkHandlerDelegate, - ILogger logger) - : IDisposable -{ - HubConnection? _connection; - int _isDisposed; - bool _isStopping; - - /// - /// Gets the current connection state. - /// - public HubConnectionState ConnectionState => _connection?.State ?? HubConnectionState.Disconnected; - - /// - /// Gets whether the connection is currently active. - /// - public bool IsConnected => ConnectionState == HubConnectionState.Connected; - - public string ServerEndpoint { get; } = serverEndpoint; - public string StationIdentifier { get; set; } = string.Empty; - - /// - /// Initializes the SignalR connection. - /// - public async Task InitializeAsync(string stationId, string callsign) - { - if (_connection != null) - { - logger.Verbose("Disposing existing connection before re-initialization"); - await DisposeConnectionAsync(); - } - - var url = $"{ServerEndpoint}?callsign={callsign}&stationId={stationId}"; - logger.Verbose("Building SignalR connection to {Url}", url); - - var hubConnectionBuilder = new HubConnectionBuilder() - .WithUrl(url, options => - { -#if DEBUG - // In DEBUG mode, bypass SSL certificate validation for local development - options.HttpMessageHandlerFactory = _ => - { - var handler = new System.Net.Http.HttpClientHandler - { - ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true - }; - return handler; - }; -#endif - }) - .AddJsonProtocol() - .WithAutomaticReconnect(); - - _connection = hubConnectionBuilder.Build(); - - RegisterHandlers(); - RegisterConnectionEvents(); - - StationIdentifier = stationId; - } - - /// - /// Starts the connection to the server. - /// - public async Task StartAsync() - { - if (_connection == null) - { - throw new InvalidOperationException("Connection not initialized. Call InitializeAsync first."); - } - - if (_connection.State == HubConnectionState.Connected) - { - logger.Warning("Connection already active, skipping start"); - return; - } - - await _connection.StartAsync(); - OnConnectionStateChanged(HubConnectionState.Connected); - } - - /// - /// Stops the connection to the server. - /// - public async Task StopAsync() - { - var connection = _connection; - if (connection == null || connection.State == HubConnectionState.Disconnected) - { - logger.Warning("Connection already stopped or not initialized, skipping stop"); - return; - } - - await connection.StopAsync(); - OnConnectionStateChanged(HubConnectionState.Disconnected); - } - - void RegisterHandlers() - { - if (_connection == null) return; - - logger.Verbose("Registering SignalR message handlers"); - _connection.On("DialogueChanged", downlink => - WithCancellationToken(downlinkHandlerDelegate.DialogueChanged)(downlink)); - _connection.On("AircraftConnectionUpdated", connectedAircraftInfo => - WithCancellationToken(downlinkHandlerDelegate.AircraftConnectionUpdated)(connectedAircraftInfo)); - _connection.On("AircraftConnectionRemoved", (callsign, stationId) => - WithCancellationToken(downlinkHandlerDelegate.AircraftConnectionRemoved)(callsign, stationId)); - _connection.On("AcarsStationsUpdated", callsigns => - WithCancellationToken(downlinkHandlerDelegate.AcarsStationsUpdated)(callsigns)); - _connection.On("AdscContractUpdated", adscContract => - WithCancellationToken(downlinkHandlerDelegate.AdscContractUpdated)(adscContract)); - _connection.On("AdscContractRemoved", (callsign, stationId) => - WithCancellationToken(downlinkHandlerDelegate.AdscContractRemoved)(callsign, stationId)); - _connection.On("AdscReportReceived", adscReport => - WithCancellationToken(downlinkHandlerDelegate.AdscReportReceived)(adscReport)); - } - - Func WithCancellationToken(Func action) - { - // TODO: Make configurable - return async x => - { - using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10)); - await action(x, cancellationTokenSource.Token); - }; - } - - Func WithCancellationToken(Func action) - { - // TODO: Make configurable - return async (x, y) => - { - using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10)); - await action(x, y, cancellationTokenSource.Token); - }; - } - - public async Task BeginDialogue(string recipient, - CpdlcUplinkResponseType responseType, - string content, - CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync( - "BeginDialogue", - recipient, - responseType, - content, - cancellationToken: cancellationToken); - } - - public async Task ReplyToDownlink(Guid dialogueId, - int downlinkMessageId, - CpdlcUplinkResponseType responseType, - string content, - CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync( - "ReplyToDownlink", - dialogueId, - downlinkMessageId, - responseType, - content, - cancellationToken: cancellationToken); - } - - public async Task RequestConnection(string callsign, string stationId, CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync( - "RequestConnection", - callsign, - stationId, - cancellationToken); - } - - public async Task GetConnectedAircraft(CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - return await connection.InvokeAsync( - "GetConnectedAircraft", - cancellationToken); - } - - public async Task GetAcarsStations(CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - return await connection.InvokeAsync( - "GetAcarsStations", - cancellationToken); - } - - public async Task AcknowledgeDownlink(Guid dialogueId, int downlinkMessageId, CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync( - "AcknowledgeDownlink", - dialogueId, - downlinkMessageId, - cancellationToken); - } - - public async Task AcknowledgeUplink(Guid dialogueId, int uplinkMessageId, CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync( - "AcknowledgeUplink", - dialogueId, - uplinkMessageId, - cancellationToken); - } - - public async Task ArchiveDialogue(Guid dialogueId, CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync("ArchiveDialogue", dialogueId, cancellationToken); - } - - public async Task UpdateNextDataAuthority( - string callsign, - string? nextDataAuthority, - DateTimeOffset? expectedTransferTime, - CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync( - "UpdateNextDataAuthority", - callsign, - nextDataAuthority, - expectedTransferTime, - cancellationToken: cancellationToken); - } - - public async Task GetAtsuSettings(CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - return await connection.InvokeAsync( - "GetAtsuSettings", - cancellationToken); - } - - // A null reporting interval ends the selected contract and requests the default contract again - public async Task RequestPeriodicAdscContract( - string callsign, - TimeSpan? reportingInterval, - CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync( - "RequestPeriodicAdscContract", - callsign, - reportingInterval, - cancellationToken: cancellationToken); - } - - public async Task RequestAdscDemandReport(string callsign, CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync("RequestAdscDemandReport", callsign, cancellationToken); - } - - public async Task CancelAdscContract(string callsign, CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync("CancelAdscContract", callsign, cancellationToken); - } - - public async Task GetAdscContracts(CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - return await connection.InvokeAsync( - "GetAdscContracts", - cancellationToken); - } - - public async Task GetAdscReports(CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - return await connection.InvokeAsync( - "GetAdscReports", - cancellationToken); - } - - public async Task GetAllDialogues(CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - return await connection.InvokeAsync( - "GetAllDialogues", - cancellationToken); - } - - /// - /// Registers connection lifecycle event handlers. - /// - void RegisterConnectionEvents() - { - if (_connection == null) return; - - logger.Verbose("Registering SignalR connection lifecycle event handlers"); - - _connection.Closed += error => - { - if (error != null) - { - if (_isStopping) - { - logger.Verbose(error, "SignalR connection closed with error during intentional stop"); - } - else - { - logger.Warning(error, "SignalR connection closed with error"); - OnConnectionError(error); - } - } - else - { - logger.Verbose("SignalR connection closed"); - } - - OnConnectionStateChanged(HubConnectionState.Disconnected); - return Task.CompletedTask; - }; - - _connection.Reconnecting += error => - { - if (error != null) - { - logger.Warning(error, "SignalR connection lost, attempting to reconnect"); - } - else - { - logger.Information("SignalR connection reconnecting"); - } - - OnConnectionStateChanged(HubConnectionState.Reconnecting); - return Task.CompletedTask; - }; - - _connection.Reconnected += connectionId => - { - logger.Information("SignalR connection reconnected successfully (ConnectionId: {ConnectionId})", connectionId); - OnConnectionStateChanged(HubConnectionState.Connected); - return Task.CompletedTask; - }; - } - - void OnConnectionStateChanged(HubConnectionState newState) - { - logger.Verbose("Connection state changed to {State}", newState); - } - - void OnConnectionError(Exception error) - { - logger.Error(error, "SignalR connection error occurred"); - downlinkHandlerDelegate.Error(error); - } - - HubConnection GetConnectedOrThrow() - { - var connection = _connection ?? throw new InvalidOperationException("Connection not initialized. Call InitializeAsync first."); - if (connection.State != HubConnectionState.Connected) - { - throw new InvalidOperationException($"Connection is not active. Current state: {connection.State}"); - } - - return connection; - } - - public void Dispose() - { - if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) != 0) return; - - logger.Verbose("Disposing SignalR connection manager"); - DisposeConnectionAsync().GetAwaiter().GetResult(); - logger.Verbose("SignalR connection manager disposed"); - GC.SuppressFinalize(this); - } - - async Task DisposeConnectionAsync() - { - if (_connection != null) - { - try - { - if (_connection.State != HubConnectionState.Disconnected) - { - logger.Verbose("Stopping connection during disposal"); - _isStopping = true; - await _connection.StopAsync(); - } - } - catch (Exception ex) - { - logger.Verbose(ex, "Error stopping connection during disposal (ignoring)"); - // Ignore errors during disposal - } - finally - { - _isStopping = false; - await _connection.DisposeAsync(); - _connection = null; - } - } - } -} +using CPDLCServer.Contracts; +using Microsoft.AspNetCore.SignalR.Client; +using Microsoft.Extensions.DependencyInjection; +using Serilog; + +namespace CPDLCPlugin.Server; + +// TODO: Register this in the IoC container + +/// +/// Manages the SignalR connection to the CPDLC server. +/// +public class SignalRConnectionManager( + string serverEndpoint, + string accessToken, + IDownlinkHandlerDelegate downlinkHandlerDelegate, + ILogger logger) + : IDisposable +{ + HubConnection? _connection; + int _isDisposed; + bool _isStopping; + + /// + /// Gets the current connection state. + /// + public HubConnectionState ConnectionState => _connection?.State ?? HubConnectionState.Disconnected; + + /// + /// Gets whether the connection is currently active. + /// + public bool IsConnected => ConnectionState == HubConnectionState.Connected; + + public string ServerEndpoint { get; } = serverEndpoint; + public string StationIdentifier { get; set; } = string.Empty; + + /// + /// Initializes the SignalR connection. + /// + public async Task InitializeAsync(string stationId, string callsign) + { + if (_connection != null) + { + logger.Verbose("Disposing existing connection before re-initialization"); + await DisposeConnectionAsync(); + } + + var url = $"{ServerEndpoint}?callsign={callsign}&stationId={stationId}"; + logger.Verbose("Building SignalR connection to {Url}", url); + + var hubConnectionBuilder = new HubConnectionBuilder() + .WithUrl(url, options => + { + // The server accepts only an authenticated plugin + options.AccessTokenProvider = () => Task.FromResult(accessToken); + +#if DEBUG + // In DEBUG mode, bypass SSL certificate validation for local development + options.HttpMessageHandlerFactory = _ => + { + var handler = new System.Net.Http.HttpClientHandler + { + ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true + }; + return handler; + }; +#endif + }) + .AddJsonProtocol() + .WithAutomaticReconnect(); + + _connection = hubConnectionBuilder.Build(); + + RegisterHandlers(); + RegisterConnectionEvents(); + + StationIdentifier = stationId; + } + + /// + /// Starts the connection to the server. + /// + public async Task StartAsync() + { + if (_connection == null) + { + throw new InvalidOperationException("Connection not initialized. Call InitializeAsync first."); + } + + if (_connection.State == HubConnectionState.Connected) + { + logger.Warning("Connection already active, skipping start"); + return; + } + + await _connection.StartAsync(); + OnConnectionStateChanged(HubConnectionState.Connected); + } + + /// + /// Stops the connection to the server. + /// + public async Task StopAsync() + { + var connection = _connection; + if (connection == null || connection.State == HubConnectionState.Disconnected) + { + logger.Warning("Connection already stopped or not initialized, skipping stop"); + return; + } + + await connection.StopAsync(); + OnConnectionStateChanged(HubConnectionState.Disconnected); + } + + void RegisterHandlers() + { + if (_connection == null) return; + + logger.Verbose("Registering SignalR message handlers"); + _connection.On("DialogueChanged", downlink => + WithCancellationToken(downlinkHandlerDelegate.DialogueChanged)(downlink)); + _connection.On("AircraftConnectionUpdated", connectedAircraftInfo => + WithCancellationToken(downlinkHandlerDelegate.AircraftConnectionUpdated)(connectedAircraftInfo)); + _connection.On("AircraftConnectionRemoved", (callsign, stationId) => + WithCancellationToken(downlinkHandlerDelegate.AircraftConnectionRemoved)(callsign, stationId)); + _connection.On("AcarsStationsUpdated", callsigns => + WithCancellationToken(downlinkHandlerDelegate.AcarsStationsUpdated)(callsigns)); + _connection.On("AdscContractUpdated", adscContract => + WithCancellationToken(downlinkHandlerDelegate.AdscContractUpdated)(adscContract)); + _connection.On("AdscContractRemoved", (callsign, stationId) => + WithCancellationToken(downlinkHandlerDelegate.AdscContractRemoved)(callsign, stationId)); + _connection.On("AdscReportReceived", adscReport => + WithCancellationToken(downlinkHandlerDelegate.AdscReportReceived)(adscReport)); + _connection.On("AdscReportExpired", (callsign, stationId) => + WithCancellationToken(downlinkHandlerDelegate.AdscReportExpired)(callsign, stationId)); + } + + Func WithCancellationToken(Func action) + { + // TODO: Make configurable + return async x => + { + using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + await action(x, cancellationTokenSource.Token); + }; + } + + Func WithCancellationToken(Func action) + { + // TODO: Make configurable + return async (x, y) => + { + using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + await action(x, y, cancellationTokenSource.Token); + }; + } + + public async Task BeginDialogue(string recipient, + CpdlcUplinkResponseType responseType, + string content, + CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync( + "BeginDialogue", + recipient, + responseType, + content, + cancellationToken: cancellationToken); + } + + public async Task ReplyToDownlink(Guid dialogueId, + int downlinkMessageId, + CpdlcUplinkResponseType responseType, + string content, + CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync( + "ReplyToDownlink", + dialogueId, + downlinkMessageId, + responseType, + content, + cancellationToken: cancellationToken); + } + + public async Task RequestConnection(string callsign, string stationId, CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync( + "RequestConnection", + callsign, + stationId, + cancellationToken); + } + + public async Task GetConnectedAircraft(CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + return await connection.InvokeAsync( + "GetConnectedAircraft", + cancellationToken); + } + + public async Task GetAcarsStations(CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + return await connection.InvokeAsync( + "GetAcarsStations", + cancellationToken); + } + + public async Task AcknowledgeDownlink(Guid dialogueId, int downlinkMessageId, CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync( + "AcknowledgeDownlink", + dialogueId, + downlinkMessageId, + cancellationToken); + } + + public async Task AcknowledgeUplink(Guid dialogueId, int uplinkMessageId, CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync( + "AcknowledgeUplink", + dialogueId, + uplinkMessageId, + cancellationToken); + } + + public async Task ArchiveDialogue(Guid dialogueId, CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync("ArchiveDialogue", dialogueId, cancellationToken); + } + + public async Task UpdateNextDataAuthority( + string callsign, + string? nextDataAuthority, + DateTimeOffset? expectedTransferTime, + CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync( + "UpdateNextDataAuthority", + callsign, + nextDataAuthority, + expectedTransferTime, + cancellationToken: cancellationToken); + } + + // The default reporting interval of the ATSU requests the default contract. Any other interval requests a selected contract. + public async Task RequestPeriodicAdscContract( + string callsign, + TimeSpan reportingInterval, + CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync( + "RequestPeriodicAdscContract", + callsign, + reportingInterval, + cancellationToken: cancellationToken); + } + + public async Task RequestAdscDemandReport(string callsign, CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync("RequestAdscDemandReport", callsign, cancellationToken); + } + + public async Task CancelAdscContract(string callsign, CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync("CancelAdscContract", callsign, cancellationToken); + } + + public async Task GetAdscContracts(CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + return await connection.InvokeAsync( + "GetAdscContracts", + cancellationToken); + } + + public async Task GetAdscReports(CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + return await connection.InvokeAsync( + "GetAdscReports", + cancellationToken); + } + + public async Task GetAllDialogues(CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + return await connection.InvokeAsync( + "GetAllDialogues", + cancellationToken); + } + + /// + /// Registers connection lifecycle event handlers. + /// + void RegisterConnectionEvents() + { + if (_connection == null) return; + + logger.Verbose("Registering SignalR connection lifecycle event handlers"); + + _connection.Closed += error => + { + if (error != null) + { + if (_isStopping) + { + logger.Verbose(error, "SignalR connection closed with error during intentional stop"); + } + else + { + logger.Warning(error, "SignalR connection closed with error"); + OnConnectionError(error); + } + } + else + { + logger.Verbose("SignalR connection closed"); + } + + OnConnectionStateChanged(HubConnectionState.Disconnected); + return Task.CompletedTask; + }; + + _connection.Reconnecting += error => + { + if (error != null) + { + logger.Warning(error, "SignalR connection lost, attempting to reconnect"); + } + else + { + logger.Information("SignalR connection reconnecting"); + } + + OnConnectionStateChanged(HubConnectionState.Reconnecting); + return Task.CompletedTask; + }; + + _connection.Reconnected += connectionId => + { + logger.Information("SignalR connection reconnected successfully (ConnectionId: {ConnectionId})", connectionId); + OnConnectionStateChanged(HubConnectionState.Connected); + return Task.CompletedTask; + }; + } + + void OnConnectionStateChanged(HubConnectionState newState) + { + logger.Verbose("Connection state changed to {State}", newState); + } + + void OnConnectionError(Exception error) + { + logger.Error(error, "SignalR connection error occurred"); + downlinkHandlerDelegate.Error(error); + } + + HubConnection GetConnectedOrThrow() + { + var connection = _connection ?? throw new InvalidOperationException("Connection not initialized. Call InitializeAsync first."); + if (connection.State != HubConnectionState.Connected) + { + throw new InvalidOperationException($"Connection is not active. Current state: {connection.State}"); + } + + return connection; + } + + public void Dispose() + { + if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) != 0) return; + + logger.Verbose("Disposing SignalR connection manager"); + DisposeConnectionAsync().GetAwaiter().GetResult(); + logger.Verbose("SignalR connection manager disposed"); + GC.SuppressFinalize(this); + } + + async Task DisposeConnectionAsync() + { + if (_connection != null) + { + try + { + if (_connection.State != HubConnectionState.Disconnected) + { + logger.Verbose("Stopping connection during disposal"); + _isStopping = true; + await _connection.StopAsync(); + } + } + catch (Exception ex) + { + logger.Verbose(ex, "Error stopping connection during disposal (ignoring)"); + // Ignore errors during disposal + } + finally + { + _isStopping = false; + await _connection.DisposeAsync(); + _connection = null; + } + } + } +} diff --git a/source/CPDLCPlugin/Server/TokenStore.cs b/source/CPDLCPlugin/Server/TokenStore.cs new file mode 100644 index 0000000..92ccd09 --- /dev/null +++ b/source/CPDLCPlugin/Server/TokenStore.cs @@ -0,0 +1,70 @@ +using System.IO; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using vatsys; + +namespace CPDLCPlugin.Server; + +/// +/// Keeps the token for each CPDLC server, so that the user does not have to authenticate each time that vatSys starts. +/// The tokens are encrypted with the Windows account of the user (DPAPI), so a different account cannot read them. +/// +public class TokenStore +{ + readonly string _filePath = Path.Combine(Helpers.GetFilesFolder(), "cpdlc_tokens.json"); + readonly object _lock = new(); + + public string? Get(Uri server) + { + lock (_lock) + { + var tokens = Load(); + if (!tokens.TryGetValue(Key(server), out var encryptedToken)) + return null; + + try + { + var bytes = ProtectedData.Unprotect(Convert.FromBase64String(encryptedToken), null, DataProtectionScope.CurrentUser); + return Encoding.UTF8.GetString(bytes); + } + catch (CryptographicException) + { + // A different Windows account encrypted the token + return null; + } + } + } + + public void Save(Uri server, string token) + { + lock (_lock) + { + var tokens = Load(); + var bytes = ProtectedData.Protect(Encoding.UTF8.GetBytes(token), null, DataProtectionScope.CurrentUser); + tokens[Key(server)] = Convert.ToBase64String(bytes); + File.WriteAllText(_filePath, JsonSerializer.Serialize(tokens)); + } + } + + public void Delete(Uri server) + { + lock (_lock) + { + var tokens = Load(); + if (tokens.Remove(Key(server))) + File.WriteAllText(_filePath, JsonSerializer.Serialize(tokens)); + } + } + + Dictionary Load() + { + if (!File.Exists(_filePath)) + return new Dictionary(); + + return JsonSerializer.Deserialize>(File.ReadAllText(_filePath)) + ?? new Dictionary(); + } + + static string Key(Uri server) => server.GetLeftPart(UriPartial.Authority).ToLowerInvariant(); +} diff --git a/source/CPDLCPlugin/Styles.xaml b/source/CPDLCPlugin/Styles.xaml deleted file mode 100644 index 524fcd4..0000000 --- a/source/CPDLCPlugin/Styles.xaml +++ /dev/null @@ -1,560 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/source/CPDLCPlugin/Theme.cs b/source/CPDLCPlugin/Theme.cs index 9ba9395..c49d925 100644 --- a/source/CPDLCPlugin/Theme.cs +++ b/source/CPDLCPlugin/Theme.cs @@ -1,46 +1,24 @@ -using System.Windows; -using System.Windows.Media; +using System.Windows.Media; using CPDLCPlugin.Extensions; namespace CPDLCPlugin; +// The CPDLC colours that the vatSys profile does not have. +// For the colours in the profile, use VatSysColours or the VatSysColour markup extension. public static class Theme { - public static float Alpha = 0.4f; - public static Brush LightBrush = new SolidColorBrush(Color.FromScRgb(Alpha, 255, 255, 255)); - public static Brush DarkBrush = new SolidColorBrush(Color.FromScRgb(Alpha, 0, 0, 0)); - - public static SolidColorBrush BackgroundColor { get; set; } = CreateColor(255, 160, 170, 170); - public static SolidColorBrush GenericTextColor { get; set; } = CreateColor(255, 96, 0, 0); - public static SolidColorBrush InteractiveTextColor { get; set; } = CreateColor(255, 0, 0, 96); - public static SolidColorBrush NonInteractiveTextColor { get; set; } = CreateColor(255, 90, 90, 90); - public static SolidColorBrush SelectedButtonColor { get; set; } = CreateColor(255, 0, 0, 96); - - public static SolidColorBrush CPDLCBackgroundColor { get; set; } = CreateColor(255, 230, 210, 190); - public static SolidColorBrush CPDLCUplinkColor { get; set; } = CreateColor(255, 000, 000, 096); - public static SolidColorBrush CPDLCDownlinkColor { get; set; } = CreateColor(255, 000,105,000); public static SolidColorBrush CPDLCSelectedDownlinkBackgroundColor { get; set; } = CreateColor(255, 220, 220, 220); public static SolidColorBrush CPDLCClosedColor { get; set; } = CreateColor(255, 000, 000, 000); public static SolidColorBrush CPDLCControllerLateColor { get; set; } = CreateColor(255, 170, 255, 170); public static SolidColorBrush CPDLCPilotLateColor { get; set; } = CreateColor(255, 000, 255 ,255); public static SolidColorBrush CPDLCUrgentColor { get; set; } = CreateColor(255, 209, 046, 046); public static SolidColorBrush CPDLCFailedColor { get; set; } = CreateColor(255, 255, 255, 0); - public static SolidColorBrush CPDLCHotButtonBackgroundColor { get; set; } = CreateColor(255, 101,101,255); - public static SolidColorBrush CPDLCSendBackgroundColor { get; set; } = CreateColor(255, 101,101,255); public static SolidColorBrush CPDLCUnableDownlinkColor { get; set; } = CreateColor(255, 230, 127, 127); public static SolidColorBrush CPDLCSuspendedColor { get; set; } = CreateColor(255, 255, 255, 255); public static SolidColorBrush SelectedUtilityColor { get; set; } = CreateColor(255, 0, 255, 255); - // TODO: Support live updating font sizes - public static FontFamily FontFamily { get; set; } = new("Terminus (TTF)"); - public static double FontSize { get; set; } = 16.0; - public static FontWeight FontWeight { get; set; } = FontWeights.Bold; - - public static Thickness BeveledBorderThickness = new(2); - public static double BeveledLineWidth = 4; - static SolidColorBrush CreateColor(int alpha, int red, int green, int blue) { return new SolidColorBrush(System.Drawing.Color.FromArgb(alpha, red, green, blue).ToWindowsColor()); diff --git a/source/CPDLCPlugin/ViewModels/ADSContractViewModel.cs b/source/CPDLCPlugin/ViewModels/ADSContractViewModel.cs index 7e044d4..c1dbd83 100644 --- a/source/CPDLCPlugin/ViewModels/ADSContractViewModel.cs +++ b/source/CPDLCPlugin/ViewModels/ADSContractViewModel.cs @@ -4,6 +4,8 @@ using CPDLCPlugin.Messages; using CPDLCServer.Contracts; using MediatR; +using vatSysToolbox; +using vatSysToolbox.Windows; namespace CPDLCPlugin.ViewModels; @@ -11,12 +13,12 @@ public partial class ADSContractViewModel : ObservableObject, IRecipient, IRecipient, IRecipient, + IRecipient, IDisposable { readonly Plugin _plugin; readonly AdscContractStore _adscContractStore; readonly AdscReportStore _adscReportStore; - readonly AtsuSettingsStore _atsuSettingsStore; readonly IMediator _mediator; readonly IGuiInvoker _guiInvoker; readonly IErrorReporter _errorReporter; @@ -26,7 +28,6 @@ public ADSContractViewModel( Plugin plugin, AdscContractStore adscContractStore, AdscReportStore adscReportStore, - AtsuSettingsStore atsuSettingsStore, IMediator mediator, IGuiInvoker guiInvoker, IErrorReporter errorReporter, @@ -35,7 +36,6 @@ public ADSContractViewModel( _plugin = plugin; _adscContractStore = adscContractStore; _adscReportStore = adscReportStore; - _atsuSettingsStore = atsuSettingsStore; _mediator = mediator; _guiInvoker = guiInvoker; _errorReporter = errorReporter; @@ -45,6 +45,7 @@ public ADSContractViewModel( WeakReferenceMessenger.Default.Register(this); WeakReferenceMessenger.Default.Register(this); WeakReferenceMessenger.Default.Register(this); + WeakReferenceMessenger.Default.Register(this); if (!string.IsNullOrWhiteSpace(initialCallsign)) { @@ -58,7 +59,6 @@ public ADSContractViewModel() _plugin = null!; _adscContractStore = null!; _adscReportStore = null!; - _atsuSettingsStore = null!; _mediator = null!; _guiInvoker = null!; _errorReporter = null!; @@ -73,7 +73,6 @@ public ADSContractViewModel() SelectedPeriod = 5; SelectedPeriodTransmissionState = AdscContractState.Sent; - SelectedPeriodEndTime = DateTimeOffset.UtcNow.AddMinutes(60); DemandContractTransmissionState = AdscContractState.Rejected; } @@ -101,7 +100,6 @@ public ADSContractViewModel() public int[] PeriodOptions { get; } = [3, 5, 10, 15, 20, 24, 30, 60]; [ObservableProperty] AdscContractState? _selectedPeriodTransmissionState; - [ObservableProperty] DateTimeOffset? _selectedPeriodEndTime; [ObservableProperty] AdscContractState? _demandContractTransmissionState; @@ -109,8 +107,6 @@ async Task LoadContractAsync() { try { - DefaultPeriod = (int?)_atsuSettingsStore.Settings?.DefaultAdscReportingInterval.TotalMinutes; - if (string.IsNullOrWhiteSpace(Callsign)) { ShowContract(null); @@ -139,16 +135,16 @@ void ShowContract(AdscContractDto? contract) { CurrentPeriodMinutes = (int?)contract?.ReportingInterval?.TotalMinutes; + DefaultPeriod = (int?)contract?.DefaultReportingInterval.TotalMinutes; DefaultPeriodTransmissionState = contract?.DefaultContractState; SelectedPeriod = (int?)contract?.SelectedReportingInterval?.TotalMinutes; SelectedPeriodTransmissionState = contract?.SelectedContractState; - SelectedPeriodEndTime = contract?.SelectedContractEnds; DemandContractTransmissionState = contract?.DemandContractState; } - // A null period requests the default contract + // A null period (DEF) requests the default contract. The server sees the default period as the default contract. [RelayCommand] async Task SelectPeriod(int? minutes) { @@ -157,8 +153,14 @@ async Task SelectPeriod(int? minutes) if (string.IsNullOrWhiteSpace(Callsign)) return; - var reportingInterval = minutes is null ? (TimeSpan?)null : TimeSpan.FromMinutes(minutes.Value); - await _mediator.Send(new SelectAdscReportingIntervalRequest(Callsign, reportingInterval)); + var period = minutes ?? DefaultPeriod; + if (period is null) + { + _errorReporter.ReportError(new InvalidOperationException($"The default period for {Callsign} is not known, because {Callsign} has no ADS-C contract. Select a period.")); + return; + } + + await _mediator.Send(new SelectAdscReportingIntervalRequest(Callsign, TimeSpan.FromMinutes(period.Value))); } catch (Exception ex) { @@ -223,11 +225,19 @@ public void Receive(AdscReportReceivedNotification notification) ReloadIfShown(notification.AdscReportDto.Callsign); } + public void Receive(AdscReportExpiredNotification notification) + { + ReloadIfShown(notification.Callsign); + } + void ReloadIfShown(string callsign) { - if (_disposed) + // The ADS-C reports come for all the aircraft. Do not post to the UI thread for an aircraft that this window + // does not show. The UI thread checks again, because the callsign can change before the action runs. + if (_disposed || callsign != Callsign) return; + // LoadContractAsync changes the properties that the view binds to _guiInvoker.InvokeOnGUI(mainForm => { if (_disposed) @@ -255,6 +265,7 @@ public void Dispose() WeakReferenceMessenger.Default.Unregister(this); WeakReferenceMessenger.Default.Unregister(this); WeakReferenceMessenger.Default.Unregister(this); + WeakReferenceMessenger.Default.Unregister(this); _disposed = true; } } diff --git a/source/CPDLCPlugin/ViewModels/ConnectionRequestViewModel.cs b/source/CPDLCPlugin/ViewModels/ConnectionRequestViewModel.cs index f570ca2..ca11246 100644 --- a/source/CPDLCPlugin/ViewModels/ConnectionRequestViewModel.cs +++ b/source/CPDLCPlugin/ViewModels/ConnectionRequestViewModel.cs @@ -2,6 +2,8 @@ using CommunityToolkit.Mvvm.Input; using CPDLCPlugin.Messages; using MediatR; +using vatSysToolbox; +using vatSysToolbox.Windows; namespace CPDLCPlugin.ViewModels; diff --git a/source/CPDLCPlugin/ViewModels/CurrentMessageViewModel.cs b/source/CPDLCPlugin/ViewModels/CurrentMessageViewModel.cs index 67f8f79..2952ab8 100644 --- a/source/CPDLCPlugin/ViewModels/CurrentMessageViewModel.cs +++ b/source/CPDLCPlugin/ViewModels/CurrentMessageViewModel.cs @@ -3,6 +3,8 @@ using CommunityToolkit.Mvvm.ComponentModel; using CPDLCPlugin.Extensions; using CPDLCServer.Contracts; +using vatsys; +using vatSysToolbox; namespace CPDLCPlugin.ViewModels; @@ -66,10 +68,10 @@ public void UpdateMessage(DialogueDto dialogue, CpdlcMessageDto newMessage) bool isDownlink; [ObservableProperty] - SolidColorBrush foregroundColor = Theme.GenericTextColor; + SolidColorBrush foregroundColor = VatSysColours.GetColour(Colours.Identities.GenericText); [ObservableProperty] - SolidColorBrush backgroundColor = Theme.BackgroundColor; + SolidColorBrush backgroundColor = VatSysColours.GetColour(Colours.Identities.WindowBackground); string GetCallsignFromMessage(CpdlcMessageDto message) { diff --git a/source/CPDLCPlugin/ViewModels/CurrentMessagesViewModel.cs b/source/CPDLCPlugin/ViewModels/CurrentMessagesViewModel.cs index 8362b2b..a964cf1 100644 --- a/source/CPDLCPlugin/ViewModels/CurrentMessagesViewModel.cs +++ b/source/CPDLCPlugin/ViewModels/CurrentMessagesViewModel.cs @@ -6,6 +6,8 @@ using CPDLCPlugin.Messages; using CPDLCServer.Contracts; using MediatR; +using vatSysToolbox; +using vatSysToolbox.Windows; namespace CPDLCPlugin.ViewModels; @@ -25,7 +27,8 @@ public partial class CurrentMessagesViewModel : readonly IErrorReporter _errorReporter; readonly IWindowHandle _windowHandle; readonly IJurisdictionChecker _jurisdictionChecker; - bool _closeWhenEmpty; + // The UI thread reads this field. Another thread can set it to false (see Receive(OpenCurrentMessagesWindowRequest)). + volatile bool _closeWhenEmpty; bool _disposed; public CurrentMessagesViewModel( @@ -590,6 +593,8 @@ public void Receive(DialogueChangedNotification message) if (_disposed) return; + // The message comes on a background thread. LoadDialoguesAsync changes Dialogues, which the view binds to, and it + // can close the window. Both must be on the UI thread. _guiInvoker.InvokeOnGUI(async _ => { if (_disposed) @@ -605,6 +610,8 @@ public void Receive(FdrOwnerChanged message) if (_disposed) return; + // The message comes on a background thread. LoadDialoguesAsync changes Dialogues, which the view binds to, and it + // can close the window. Both must be on the UI thread. _guiInvoker.InvokeOnGUI(async _ => { if (_disposed) @@ -620,6 +627,8 @@ public void Receive(ConnectedNotification message) if (_disposed) return; + // The message comes on a background thread. LoadDialoguesAsync changes Dialogues, which the view binds to, and it + // can close the window. Both must be on the UI thread. _guiInvoker.InvokeOnGUI(async _ => { if (_disposed) @@ -629,13 +638,14 @@ public void Receive(ConnectedNotification message) }); } - // The window must not close automatically after the controller opens it manually + // The window must not close automatically after the controller opens it manually. The view does not bind to this + // field. Thus, set it on this thread. public void Receive(OpenCurrentMessagesWindowRequest message) { if (_disposed || message.OpenedAutomatically) return; - _guiInvoker.InvokeOnGUI(_ => _closeWhenEmpty = false); + _closeWhenEmpty = false; } [RelayCommand] diff --git a/source/CPDLCPlugin/ViewModels/EditorViewModel.cs b/source/CPDLCPlugin/ViewModels/EditorViewModel.cs index 050edd5..838a8f7 100644 --- a/source/CPDLCPlugin/ViewModels/EditorViewModel.cs +++ b/source/CPDLCPlugin/ViewModels/EditorViewModel.cs @@ -8,6 +8,8 @@ using MediatR; using Serilog; using Serilog.Core; +using vatSysToolbox; +using vatSysToolbox.Windows; namespace CPDLCPlugin.ViewModels; @@ -747,6 +749,12 @@ IUplinkMessageElementComponentViewModel[] ConvertToViewModel(UplinkMessageRefere public void Receive(DialogueChangedNotification message) { + // The dialogues change for all the aircraft. The editor shows the dialogues of one aircraft only. Do not post to + // the UI thread for the other aircraft. + if (message.Dialogue.AircraftCallsign != Callsign) + return; + + // LoadDownlinkMessagesAsync changes the downlink messages, which the view binds to _guiInvoker.InvokeOnGUI(async _ => await LoadDownlinkMessagesAsync()); } diff --git a/source/CPDLCPlugin/ViewModels/HistoryMessageViewModel.cs b/source/CPDLCPlugin/ViewModels/HistoryMessageViewModel.cs index f96357e..f60241a 100644 --- a/source/CPDLCPlugin/ViewModels/HistoryMessageViewModel.cs +++ b/source/CPDLCPlugin/ViewModels/HistoryMessageViewModel.cs @@ -3,6 +3,8 @@ using CommunityToolkit.Mvvm.ComponentModel; using CPDLCPlugin.Extensions; using CPDLCServer.Contracts; +using vatsys; +using vatSysToolbox; namespace CPDLCPlugin.ViewModels; @@ -55,10 +57,10 @@ public HistoryMessageViewModel(CpdlcMessageDto message, int maxMessageDisplayLen bool isExtended; [ObservableProperty] - SolidColorBrush foregroundColor = Theme.GenericTextColor; + SolidColorBrush foregroundColor = VatSysColours.GetColour(Colours.Identities.GenericText); [ObservableProperty] - SolidColorBrush backgroundColor = Theme.BackgroundColor; + SolidColorBrush backgroundColor = VatSysColours.GetColour(Colours.Identities.WindowBackground); string GetCallsignFromMessage(CpdlcMessageDto message) { diff --git a/source/CPDLCPlugin/ViewModels/HistoryViewModel.cs b/source/CPDLCPlugin/ViewModels/HistoryViewModel.cs index be06a1d..c8926de 100644 --- a/source/CPDLCPlugin/ViewModels/HistoryViewModel.cs +++ b/source/CPDLCPlugin/ViewModels/HistoryViewModel.cs @@ -4,6 +4,8 @@ using CommunityToolkit.Mvvm.Messaging; using CPDLCPlugin.Configuration; using CPDLCPlugin.Messages; +using vatSysToolbox; +using vatSysToolbox.Windows; namespace CPDLCPlugin.ViewModels; @@ -105,9 +107,12 @@ async Task LoadMessages() public void Receive(DialogueChangedNotification notification) { - if (_disposed) + // The dialogues change for all the aircraft. Do not post to the UI thread for an aircraft that this window does + // not show. The UI thread checks again, because the callsign can change before the action runs. + if (_disposed || notification.Dialogue.AircraftCallsign != Callsign) return; + // LoadDialoguesAsync changes Dialogues, which the view binds to _guiInvoker.InvokeOnGUI(mainForm => { if (_disposed) diff --git a/source/CPDLCPlugin/ViewModels/MessageColours.cs b/source/CPDLCPlugin/ViewModels/MessageColours.cs index 62c9ae5..ee06b82 100644 --- a/source/CPDLCPlugin/ViewModels/MessageColours.cs +++ b/source/CPDLCPlugin/ViewModels/MessageColours.cs @@ -1,5 +1,7 @@ using System.Windows.Media; using CPDLCServer.Contracts; +using vatsys; +using vatSysToolbox; namespace CPDLCPlugin.ViewModels; @@ -7,7 +9,7 @@ public class MessageColours { public static ColorPair GetMessageColors(CpdlcMessageDto message) { - var background = Theme.CPDLCBackgroundColor; + var background = VatSysColours.GetColour(Colours.Identities.CPDLCMessageBackground); if (IsUrgent(message)) { @@ -59,12 +61,12 @@ public static ColorPair GetMessageColors(CpdlcMessageDto message) if (message is DownlinkMessageDto) { - return new ColorPair(background, Theme.CPDLCDownlinkColor).InvertIf(!message.IsAcknowledged); + return new ColorPair(background, VatSysColours.GetColour(Colours.Identities.CPDLCDownlink)).InvertIf(!message.IsAcknowledged); } if (message is UplinkMessageDto) { - return new ColorPair(background, Theme.CPDLCUplinkColor).InvertIf(!message.IsAcknowledged); + return new ColorPair(background, VatSysColours.GetColour(Colours.Identities.CPDLCUplink)).InvertIf(!message.IsAcknowledged); } return new ColorPair(background, Theme.CPDLCClosedColor); diff --git a/source/CPDLCPlugin/ViewModels/SetupViewModel.cs b/source/CPDLCPlugin/ViewModels/SetupViewModel.cs index acf507e..79acd68 100644 --- a/source/CPDLCPlugin/ViewModels/SetupViewModel.cs +++ b/source/CPDLCPlugin/ViewModels/SetupViewModel.cs @@ -2,27 +2,38 @@ using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Messaging; using CPDLCPlugin.Messages; +using CPDLCPlugin.Server; using MediatR; +using vatSysToolbox; +using vatSysToolbox.Windows; namespace CPDLCPlugin.ViewModels; public partial class SetupViewModel : ObservableObject, IRecipient, - IRecipient + IRecipient, + IRecipient { readonly IMediator _mediator; readonly IErrorReporter _errorReporter; readonly IWindowHandle _windowHandle; + readonly AuthenticationState _authenticationState; + readonly IGuiInvoker _guiInvoker; [ObservableProperty] string serverEndpoint; [ObservableProperty] string[] availableStationIdentifiers; [ObservableProperty] string selectedStationIdentifier; [ObservableProperty] bool connected; + [ObservableProperty] bool authenticated; + [ObservableProperty] string authenticationStatus = string.Empty; + [ObservableProperty] bool authenticating; public SetupViewModel( IMediator mediator, IErrorReporter errorReporter, IWindowHandle windowHandle, + AuthenticationState authenticationState, + IGuiInvoker guiInvoker, string serverEndpoint, string[] availableStationIdentifiers, string selectedStationIdentifier, @@ -31,14 +42,18 @@ public SetupViewModel( _mediator = mediator; _errorReporter = errorReporter; _windowHandle = windowHandle; + _authenticationState = authenticationState; + _guiInvoker = guiInvoker; ServerEndpoint = serverEndpoint; AvailableStationIdentifiers = availableStationIdentifiers; SelectedStationIdentifier = selectedStationIdentifier; Connected = connected; + UpdateAuthenticationStatus(); // Register for connection notifications WeakReferenceMessenger.Default.Register(this); WeakReferenceMessenger.Default.Register(this); + WeakReferenceMessenger.Default.Register(this); } [RelayCommand] @@ -61,12 +76,65 @@ async Task ConnectOrDisconnect() } } + [RelayCommand] + async Task AuthenticateOrLogOut() + { + try + { + Authenticating = true; + + if (Authenticated) + { + await _mediator.Send(new LogOutRequest(ServerEndpoint)); + } + else + { + await _mediator.Send(new AuthenticateRequest(ServerEndpoint)); + } + } + catch (Exception e) + { + _errorReporter.ReportError(e); + } + finally + { + Authenticating = false; + } + } + [RelayCommand] void Close() { _windowHandle.Close(); } + // The status is for the server in the text box, so it changes when the URL changes + partial void OnServerEndpointChanged(string value) + { + UpdateAuthenticationStatus(); + } + + void UpdateAuthenticationStatus() + { + Uri server; + try + { + server = ServerAddress.GetBaseUri(ServerEndpoint); + } + catch (ArgumentException) + { + Authenticated = false; + AuthenticationStatus = "The server URL is not valid"; + return; + } + + var user = _authenticationState.GetUser(server); + Authenticated = user is not null; + AuthenticationStatus = user is null + ? "Not authenticated" + : $"Authenticated as {user.Name} ({user.Cid})"; + } + public void Receive(ConnectedNotification message) { Connected = true; @@ -76,4 +144,10 @@ public void Receive(DisconnectedNotification message) { Connected = false; } + + // The notification can come from a background thread + public void Receive(AuthenticationChangedNotification message) + { + _guiInvoker.InvokeOnGUI(_ => UpdateAuthenticationStatus()); + } } diff --git a/source/CPDLCPlugin/WindowEvents.cs b/source/CPDLCPlugin/WindowEvents.cs new file mode 100644 index 0000000..ee1dc07 --- /dev/null +++ b/source/CPDLCPlugin/WindowEvents.cs @@ -0,0 +1,42 @@ +using vatSysToolbox; +using vatSysToolbox.Messaging; +using vatSysToolbox.Windows; + +namespace CPDLCPlugin; + +/// +/// Tells the other plugins (for example, the CPDLC buttons of the Eurocat Menus plugin) when a window opens or closes. +/// +public class WindowEvents(IPluginMessenger messenger, IErrorReporter errorReporter) +{ + // The messages have no data + static readonly MessageContent EmptyContent = new("application/json", "{}"u8.ToArray()); + + /// + /// Sends the opened message now, and the closed message when the window closes. Call this method when the window + /// is made. + /// + public void Broadcast(IWindowHandle windowHandle, string openedMessageType, string closedMessageType) + { + // The handle has no Closed event. A close that no handler cancels closes the window. + windowHandle.BeforeClose += (_, e) => + { + if (!e.Cancel) + Broadcast(closedMessageType); + }; + + Broadcast(openedMessageType); + } + + void Broadcast(string messageType) + { + try + { + messenger.Broadcast(messageType, EmptyContent); + } + catch (Exception ex) + { + errorReporter.ReportError(ex, $"Cannot send the message {messageType}"); + } + } +} diff --git a/source/CPDLCPlugin/Windows/ADSContractView.xaml b/source/CPDLCPlugin/Windows/ADSContractView.xaml index 95b23a6..4ba47b5 100644 --- a/source/CPDLCPlugin/Windows/ADSContractView.xaml +++ b/source/CPDLCPlugin/Windows/ADSContractView.xaml @@ -3,17 +3,17 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" - xmlns:local="clr-namespace:CPDLCPlugin" + xmlns:toolbox="clr-namespace:vatSysToolbox;assembly=vatSysToolbox" + xmlns:toolboxControls="clr-namespace:vatSysToolbox.Controls;assembly=vatSysToolbox" xmlns:viewModels="clr-namespace:CPDLCPlugin.ViewModels" - xmlns:controls="clr-namespace:CPDLCPlugin.Controls" xmlns:converters="clr-namespace:CPDLCPlugin.Converters" - Background="{x:Static local:Theme.BackgroundColor}" + Background="{toolbox:VatSysColour WindowBackground}" d:DataContext="{d:DesignInstance Type=viewModels:ADSContractViewModel, IsDesignTimeCreatable=True}" mc:Ignorable="d"> - + @@ -38,7 +38,7 @@ @@ -97,14 +97,13 @@ - + - @@ -137,8 +136,8 @@ Placement="Bottom" StaysOpen="False" AllowsTransparency="True"> - - + + + + @@ -65,21 +98,6 @@ SelectedItem="{Binding SelectedStationIdentifier}"/> - - - - - - - - - - - - - - - diff --git a/source/CPDLCPlugin/Windows/VatSysForm.cs b/source/CPDLCPlugin/Windows/VatSysForm.cs deleted file mode 100644 index a7b74c6..0000000 --- a/source/CPDLCPlugin/Windows/VatSysForm.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System.Windows; -using System.Windows.Controls; -using System.Windows.Forms; -using System.Windows.Forms.Integration; -using vatsys; - -namespace CPDLCPlugin.Windows; - -// A vatSys form that hosts WPF content -public class VatSysForm : BaseForm -{ - public VatSysForm(string title, Func createView, bool sizeToContent) - { - MiddleClickClose = false; - - Text = title; - - var view = createView(new FormWindowHandle(this)); - - var elementHost = new ElementHost - { - Dock = DockStyle.Fill - }; - - if (sizeToContent) - { - // A Canvas measures its child with no size limit. The view then always has its natural size, - // and SizeChanged occurs each time the content changes size. - var canvas = new Canvas(); - canvas.Children.Add(view); - elementHost.Child = canvas; - - view.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); - ResizeToContent(view.DesiredSize); - view.SizeChanged += (_, e) => ResizeToContent(e.NewSize); - - FormBorderStyle = FormBorderStyle.FixedSingle; - } - else - { - elementHost.Child = view; - - FormBorderStyle = FormBorderStyle.Sizable; - Resizeable = true; - } - - Controls.Add(elementHost); - - Padding = new Padding(0); - Margin = new Padding(0); - } - - void ResizeToContent(Size contentSize) - { - if (WindowState != FormWindowState.Normal) - return; - - // vatSys draws its own border and title bar. The ClientSize setter uses the standard Windows border to - // calculate the form size, so it can give the wrong size. Use the real size of the border and title bar. - var borderWidth = Width - ClientSize.Width; - var borderHeight = Height - ClientSize.Height; - - Size = new System.Drawing.Size( - (int)Math.Ceiling(contentSize.Width) + borderWidth, - (int)Math.Ceiling(contentSize.Height) + borderHeight); - } -} diff --git a/source/CPDLCPlugin/Windows/WindowManager.cs b/source/CPDLCPlugin/Windows/WindowManager.cs deleted file mode 100644 index 2a8bd7b..0000000 --- a/source/CPDLCPlugin/Windows/WindowManager.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System.Windows; -using System.Windows.Forms; - -namespace CPDLCPlugin.Windows; - -public class WindowManager(IGuiInvoker guiInvoker) -{ - readonly IDictionary _forms = new Dictionary(); - readonly object _gate = new(); - - public void FocusOrCreateWindow( - string key, - string title, - Func createView, - bool sizeToContent = true, - Action? configureForm = null) - { - guiInvoker.InvokeOnGUI(mainForm => - { - try - { - lock (_gate) - { - if (_forms.TryGetValue(key, out var existingForm)) - { - existingForm.WindowState = FormWindowState.Normal; - existingForm.Activate(); - return; - } - - var form = new VatSysForm(title, createView, sizeToContent) - { - StartPosition = FormStartPosition.CenterParent - }; - - configureForm?.Invoke(form); - - form.Closed += (_, _) => TryRemoveWindowInternal(key); - form.Show(mainForm); - - _forms[key] = form; - } - } - catch (Exception ex) - { - Plugin.AddError(ex, "Failed to open window"); - } - }); - } - - public void TryRemoveWindow(string key) - { - guiInvoker.InvokeOnGUI(_ => - { - lock (_gate) - { - if (!_forms.TryGetValue(key, out var form)) - return; - - try - { - form.Close(); - } - catch (ObjectDisposedException) - { - // Form may have already been closed or disposed - } - } - }); - } - - void TryRemoveWindowInternal(string key) - { - lock (_gate) - { - _forms.Remove(key); - } - } -} diff --git a/source/CPDLCPlugin/WorkQueue.cs b/source/CPDLCPlugin/WorkQueue.cs deleted file mode 100644 index d2fcb6c..0000000 --- a/source/CPDLCPlugin/WorkQueue.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Threading.Channels; -using Serilog; - -namespace CPDLCPlugin; - -public class WorkQueue : IAsyncDisposable -{ - readonly Action _onError; - readonly ILogger _logger; - readonly IClock _clock; - readonly Channel> _workQueue = Channel.CreateUnbounded>(); - - readonly CancellationTokenSource _cancellationTokenSource; - readonly Task _worker; - - static readonly TimeSpan WaitWarningThreshold = TimeSpan.FromSeconds(2); - static readonly TimeSpan ExecutionWarningThreshold = TimeSpan.FromSeconds(5); - - public WorkQueue(Action onError, ILogger logger, IClock clock) - { - _onError = onError; - _logger = logger; - _clock = clock; - - _cancellationTokenSource = new CancellationTokenSource(); - _worker = Worker(_cancellationTokenSource.Token); - } - - public bool Enqueue(Func work, [CallerMemberName] string caller = "") - { - var enqueueTime = _clock.UtcNow(); - return _workQueue.Writer.TryWrite(async () => - { - var waitTime = _clock.UtcNow() - enqueueTime; - if (waitTime > WaitWarningThreshold) - _logger.Warning("[{Caller}] Work item waited {WaitMs}ms in queue", caller, (long)waitTime.TotalMilliseconds); - - var sw = Stopwatch.StartNew(); - await work(); - sw.Stop(); - - if (sw.Elapsed > ExecutionWarningThreshold) - _logger.Warning("[{Caller}] Work item took {ElapsedMs}ms to complete", caller, sw.ElapsedMilliseconds); - }); - } - - async Task Worker(CancellationToken cancellationToken) - { - while (!cancellationToken.IsCancellationRequested) - { - try - { - var work = await _workQueue.Reader.ReadAsync(cancellationToken).ConfigureAwait(false); - await work().ConfigureAwait(false); - } - catch (OperationCanceledException) - { - // Expected during shutdown - break; - } - catch (Exception ex) - { - try - { - _onError(ex); - } - catch - { - // Ignore errors during error reporting - } - } - } - } - - public async ValueTask DisposeAsync() - { - _cancellationTokenSource.Cancel(); - await _worker.ConfigureAwait(false); - - _worker.Dispose(); - _cancellationTokenSource.Dispose(); - } -} diff --git a/source/CPDLCServer.Contracts/AcarsMessages.cs b/source/CPDLCServer.Contracts/AcarsMessages.cs index a707285..1757df5 100644 --- a/source/CPDLCServer.Contracts/AcarsMessages.cs +++ b/source/CPDLCServer.Contracts/AcarsMessages.cs @@ -35,12 +35,7 @@ public enum AlertType None } -public record ControllerConnectionDto(string StationId, string Callsign, string VatsimCid); - -// Read-only settings of the ATSU the controller is connected to -public record AtsuSettingsDto( - string StationId, - TimeSpan DefaultAdscReportingInterval); +public record ControllerConnectionDto(string StationId, string Callsign); // ADS-C DTOs for SignalR API @@ -52,15 +47,15 @@ public enum AdscContractState } // ReportingInterval is the interval of the latest periodic request. It is null when no periodic contract was requested. -// SelectedContractEnds is null when no selected contract is in use. +// DefaultReportingInterval is the default reporting interval of the ATSU. public record AdscContractDto( string Callsign, string StationId, TimeSpan? ReportingInterval, + TimeSpan DefaultReportingInterval, AdscContractState? DefaultContractState, TimeSpan? SelectedReportingInterval, AdscContractState? SelectedContractState, - DateTimeOffset? SelectedContractEnds, AdscContractState? DemandContractState); public enum AdscReportSource @@ -149,3 +144,8 @@ public class DownlinkMessageDto : CpdlcMessageDto } + +// Plugin authentication DTOs +public record PluginTokenResponse(string AccessToken, DateTimeOffset Expires, string Cid, string Name); + +public record PluginUserDto(string Cid, string Name, DateTimeOffset Expires); diff --git a/source/CPDLCServer.Tests/AcarsConnections/ConnectionSettings/AcarsConnectionCommandHandlerTests.cs b/source/CPDLCServer.Tests/AcarsConnections/ConnectionSettings/AcarsConnectionCommandHandlerTests.cs new file mode 100644 index 0000000..4524d7f --- /dev/null +++ b/source/CPDLCServer.Tests/AcarsConnections/ConnectionSettings/AcarsConnectionCommandHandlerTests.cs @@ -0,0 +1,197 @@ +using System.Security.Cryptography; +using CPDLCServer.AcarsConnections.ConnectionSettings; +using CPDLCServer.Security; +using CPDLCServer.Tests.Mocks; +using Microsoft.EntityFrameworkCore; +using Serilog.Core; + +namespace CPDLCServer.Tests.AcarsConnections.ConnectionSettings; + +public sealed class AcarsConnectionCommandHandlerTests : IDisposable +{ + readonly MasterKeyEncryption _masterKeyEncryption = new(Convert.ToBase64String(RandomNumberGenerator.GetBytes(32))); + readonly TestDatabase _database = new(); + readonly TestAcarsConnectionManager _acarsConnectionManager = new(); + + [Fact] + public async Task Create_SavesSettingsWithEncryptedCode_AndStartsConnection() + { + // Arrange + var connection = new AcarsConnectionSettings { StationIdentifier = "ybbb" }; + + // Act + Guid id; + await using (var dbContext = _database.CreateDbContext()) + { + var handler = new CreateAcarsConnectionCommandHandler(dbContext, _masterKeyEncryption, _acarsConnectionManager, new TestUnitOfWork(), Logger.None); + id = await handler.Handle(new CreateAcarsConnectionCommand(connection, "LOGON123"), CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Assert + var saved = Assert.Single(await AllSettings()); + Assert.Equal(id, saved.Id); + Assert.Equal("YBBB", saved.StationIdentifier); + Assert.NotEqual("LOGON123", saved.EncryptedAuthenticationCode); + Assert.Equal("LOGON123", _masterKeyEncryption.Decrypt(saved.EncryptedAuthenticationCode)); + Assert.Equal([id], _acarsConnectionManager.StartedConnections.Select(s => s.Id)); + } + + [Fact] + public async Task Create_WhenDisabled_DoesNotStartConnection() + { + // Arrange + var connection = new AcarsConnectionSettings { StationIdentifier = "YBBB", Enabled = false }; + + // Act + await using (var dbContext = _database.CreateDbContext()) + { + var handler = new CreateAcarsConnectionCommandHandler(dbContext, _masterKeyEncryption, _acarsConnectionManager, new TestUnitOfWork(), Logger.None); + await handler.Handle(new CreateAcarsConnectionCommand(connection, "LOGON123"), CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Assert + Assert.Single(await AllSettings()); + Assert.Empty(_acarsConnectionManager.StartedConnections); + } + + [Fact] + public async Task Create_WithoutAuthenticationCode_Throws() + { + // Arrange + await using var dbContext = _database.CreateDbContext(); + var handler = new CreateAcarsConnectionCommandHandler(dbContext, _masterKeyEncryption, _acarsConnectionManager, new TestUnitOfWork(), Logger.None); + var connection = new AcarsConnectionSettings { StationIdentifier = "YBBB" }; + + // Act & Assert + await Assert.ThrowsAsync(() => handler.Handle(new CreateAcarsConnectionCommand(connection, null), CancellationToken.None)); + Assert.Empty(dbContext.AcarsConnections.Local); + } + + [Fact] + public async Task Update_StopsThenStartsConnectionWithNewSettings() + { + // Arrange + var id = await AddSettings(enabled: true); + var changes = new AcarsConnectionSettings { StationIdentifier = "YBBB", DefaultAdscReportingInterval = 5, Notes = "Brisbane FIR" }; + + // Act + await Update(id, changes, null); + + // Assert + Assert.Equal([$"Stop {id}", $"Start {id}"], _acarsConnectionManager.StartStopCalls); + var saved = Assert.Single(await AllSettings()); + Assert.Equal(5, saved.DefaultAdscReportingInterval); + Assert.Equal("Brisbane FIR", saved.Notes); + } + + [Fact] + public async Task Update_WhenDisabled_StopsConnection() + { + // Arrange + var id = await AddSettings(enabled: true); + + // Act + await Update(id, new AcarsConnectionSettings { StationIdentifier = "YBBB", Enabled = false }, null); + + // Assert + Assert.Equal([$"Stop {id}"], _acarsConnectionManager.StartStopCalls); + Assert.False(Assert.Single(await AllSettings()).Enabled); + } + + [Fact] + public async Task Update_WithoutAuthenticationCode_KeepsCurrentCode() + { + // Arrange + var id = await AddSettings(enabled: true); + + // Act + await Update(id, new AcarsConnectionSettings { StationIdentifier = "YBBB" }, ""); + + // Assert + var saved = Assert.Single(await AllSettings()); + Assert.Equal("LOGON123", _masterKeyEncryption.Decrypt(saved.EncryptedAuthenticationCode)); + } + + [Fact] + public async Task Update_WithAuthenticationCode_ReplacesCode() + { + // Arrange + var id = await AddSettings(enabled: true); + + // Act + await Update(id, new AcarsConnectionSettings { StationIdentifier = "YBBB" }, "NEWCODE"); + + // Assert + var saved = Assert.Single(await AllSettings()); + Assert.Equal("NEWCODE", _masterKeyEncryption.Decrypt(saved.EncryptedAuthenticationCode)); + } + + [Fact] + public async Task Delete_RemovesSettingsAndStopsConnection() + { + // Arrange + var id = await AddSettings(enabled: true); + + // Act + await using (var dbContext = _database.CreateDbContext()) + { + var handler = new DeleteAcarsConnectionCommandHandler(dbContext, _acarsConnectionManager, new TestUnitOfWork(), Logger.None); + await handler.Handle(new DeleteAcarsConnectionCommand(id), CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Assert + Assert.Empty(await AllSettings()); + Assert.Equal([id], _acarsConnectionManager.StoppedConnections); + } + + [Fact] + public async Task Delete_WhenNotFound_DoesNothing() + { + // Arrange + await using var dbContext = _database.CreateDbContext(); + var handler = new DeleteAcarsConnectionCommandHandler(dbContext, _acarsConnectionManager, new TestUnitOfWork(), Logger.None); + + // Act + await handler.Handle(new DeleteAcarsConnectionCommand(Guid.NewGuid()), CancellationToken.None); + + // Assert + Assert.Empty(_acarsConnectionManager.StoppedConnections); + } + + async Task Update(Guid id, AcarsConnectionSettings changes, string? authenticationCode) + { + await using var dbContext = _database.CreateDbContext(); + var handler = new UpdateAcarsConnectionCommandHandler(dbContext, _masterKeyEncryption, _acarsConnectionManager, new TestUnitOfWork(), Logger.None); + await handler.Handle(new UpdateAcarsConnectionCommand(id, changes, authenticationCode), CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + async Task AddSettings(bool enabled) + { + var settings = new AcarsConnectionSettings + { + Enabled = enabled, + StationIdentifier = "YBBB", + EncryptedAuthenticationCode = _masterKeyEncryption.Encrypt("LOGON123") + }; + + await using var dbContext = _database.CreateDbContext(); + dbContext.AcarsConnections.Add(settings); + await dbContext.SaveChangesAsync(); + return settings.Id; + } + + async Task AllSettings() + { + await using var dbContext = _database.CreateDbContext(); + return await dbContext.AcarsConnections.ToArrayAsync(); + } + + public void Dispose() + { + _database.Dispose(); + } +} diff --git a/source/CPDLCServer.Tests/Clients/HoppieAcarsClientTests.cs b/source/CPDLCServer.Tests/AcarsConnections/Hoppie/HoppieAcarsConnectionTests.cs similarity index 78% rename from source/CPDLCServer.Tests/Clients/HoppieAcarsClientTests.cs rename to source/CPDLCServer.Tests/AcarsConnections/Hoppie/HoppieAcarsConnectionTests.cs index 88db370..05b209b 100644 --- a/source/CPDLCServer.Tests/Clients/HoppieAcarsClientTests.cs +++ b/source/CPDLCServer.Tests/AcarsConnections/Hoppie/HoppieAcarsConnectionTests.cs @@ -1,32 +1,37 @@ using System.Net; -using CPDLCServer.Clients; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AcarsConnections; +using CPDLCServer.AcarsConnections.Hoppie; +using CPDLCServer.AcarsConnections.Traffic; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.MessageLog; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Tests.Mocks; using Serilog.Core; -namespace CPDLCServer.Tests.Clients; +namespace CPDLCServer.Tests.AcarsConnections.Hoppie; -public class HoppieAcarsClientTests : IDisposable +public class HoppieAcarsConnectionTests : IDisposable { private readonly HoppiesConfiguration _configuration = new() { Url = new Uri("http://test.hoppie.nl/acars"), AuthenticationCode = "TEST123", - FlightSimulationNetwork = "VATSIM", StationIdentifier = "YBBB" }; - private readonly List _clients = new(); + private readonly List _connections = new(); private readonly TestAdscMessageLogRepository _adscMessageLogRepository = new(); + private readonly AcarsTrafficLog _trafficLog = new(); public void Dispose() { - foreach (var client in _clients) + foreach (var connection in _connections) { try { - client.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(1)); + connection.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(1)); } catch (ObjectDisposedException) { @@ -39,17 +44,18 @@ public void Dispose() } } - private HoppieAcarsClient CreateClient(TestHttpMessageHandler httpHandler, TestClock? clock = null) + private HoppieAcarsConnection CreateConnection(TestHttpMessageHandler httpHandler, TestClock? clock = null) { var httpClient = new HttpClient(httpHandler) { BaseAddress = _configuration.Url }; - var client = new HoppieAcarsClient( + var connection = new HoppieAcarsConnection( _configuration, httpClient, clock ?? new TestClock(), _adscMessageLogRepository, + _trafficLog, Logger.None); - _clients.Add(client); - return client; + _connections.Add(connection); + return connection; } [Fact] @@ -59,9 +65,9 @@ public async Task Send_CpdlcMessage_FormatsPayloadCorrectly() var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); var clock = new TestClock(); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); var message = new UplinkMessage( Guid.NewGuid(), @@ -75,7 +81,7 @@ public async Task Send_CpdlcMessage_FormatsPayloadCorrectly() clock.UtcNow()); // Act - await client.Send(message, CancellationToken.None); + await connection.Send(message, CancellationToken.None); // Assert var sendRequest = httpHandler.Requests.FirstOrDefault(r => @@ -98,9 +104,9 @@ public async Task Send_CpdlcReply_IncludesReplyToId() var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); var clock = new TestClock(); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); var reply = new UplinkMessage( Guid.NewGuid(), @@ -114,7 +120,7 @@ public async Task Send_CpdlcReply_IncludesReplyToId() clock.UtcNow()); // Act - await client.Send(reply, CancellationToken.None); + await connection.Send(reply, CancellationToken.None); // Assert var sendRequest = httpHandler.Requests.FirstOrDefault(r => @@ -139,9 +145,9 @@ public async Task Send_CpdlcMessage_MapsResponseTypesCorrectly(CpdlcUplinkRespon var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); var clock = new TestClock(); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); var message = new UplinkMessage( Guid.NewGuid(), @@ -155,7 +161,7 @@ public async Task Send_CpdlcMessage_MapsResponseTypesCorrectly(CpdlcUplinkRespon clock.UtcNow()); // Act - await client.Send(message, CancellationToken.None); + await connection.Send(message, CancellationToken.None); // Assert var sendRequest = httpHandler.Requests.FirstOrDefault(r => @@ -168,8 +174,8 @@ public async Task Send_CpdlcMessage_MapsResponseTypesCorrectly(CpdlcUplinkRespon var formData = await ParseFormDataFromRequest(sendRequest); Assert.Equal($"/data2/1//{expectedCode}/TEST", formData["packet"]); - await client.DisposeAsync(); - _clients.Remove(client); + await connection.DisposeAsync(); + _connections.Remove(connection); } [Fact] @@ -179,9 +185,9 @@ public async Task Send_CpdlcMessage_TranslatesContent() var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); var clock = new TestClock(); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); var message = new UplinkMessage( Guid.NewGuid(), @@ -195,7 +201,7 @@ public async Task Send_CpdlcMessage_TranslatesContent() clock.UtcNow()); // Act - await client.Send(message, CancellationToken.None); + await connection.Send(message, CancellationToken.None); // Assert var sendRequest = httpHandler.Requests.FirstOrDefault(r => @@ -216,9 +222,9 @@ public async Task Send_CpdlcMessage_UrlEncodesContent() var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); var clock = new TestClock(); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); var message = new UplinkMessage( Guid.NewGuid(), @@ -232,7 +238,7 @@ public async Task Send_CpdlcMessage_UrlEncodesContent() clock.UtcNow()); // Act - await client.Send(message, CancellationToken.None); + await connection.Send(message, CancellationToken.None); // Assert var sendRequest = httpHandler.Requests.FirstOrDefault(r => @@ -253,14 +259,14 @@ public async Task Poll_CpdlcMessage_ParsesCorrectly() var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, "ok {UAL123 cpdlc {/data2/5//Y/REQUEST DESCENT}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.MessageReader.ReadAsync(cts.Token); + var message = await connection.MessageReader.ReadAsync(cts.Token); // Assert Assert.Equal("UAL123", message.Sender); @@ -276,14 +282,14 @@ public async Task Poll_CpdlcReply_ParsesCorrectly() var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, "ok {UAL123 cpdlc {/data2/7/3/N/WILCO}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.MessageReader.ReadAsync(cts.Token); + var message = await connection.MessageReader.ReadAsync(cts.Token); // Assert Assert.Equal("UAL123", message.Sender); @@ -301,15 +307,15 @@ public async Task Poll_MultipleMessages_ParsesAllCorrectly() var response = "ok {UAL123 cpdlc {/data2/1//Y/REQUEST DESCENT}} {DAL456 cpdlc {/data2/2//Y/REQUEST CLIMB}}"; httpHandler.QueueResponse(HttpStatusCode.OK, response); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message1 = await client.MessageReader.ReadAsync(cts.Token); - var message2 = await client.MessageReader.ReadAsync(cts.Token); + var message1 = await connection.MessageReader.ReadAsync(cts.Token); + var message2 = await connection.MessageReader.ReadAsync(cts.Token); // Assert Assert.Equal("UAL123", message1.Sender); @@ -327,14 +333,14 @@ public async Task Poll_MessageWithSeparator_ParsesCorrectly() var response = "ok {UAL123 cpdlc {/data2/1//Y/REQUEST CLIMB DUE TO A/C PERFORMANCE}}"; httpHandler.QueueResponse(HttpStatusCode.OK, response); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.MessageReader.ReadAsync(cts.Token); + var message = await connection.MessageReader.ReadAsync(cts.Token); // Assert Assert.Equal("REQUEST CLIMB DUE TO A/C PERFORMANCE", message.Content); @@ -349,20 +355,20 @@ public async Task Poll_ResponseTypeCodes_MapCorrectly(string code, CpdlcDownlink var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, $"ok {{UAL123 cpdlc {{/data2/1//{code}/TEST}}}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.MessageReader.ReadAsync(cts.Token); + var message = await connection.MessageReader.ReadAsync(cts.Token); // Assert Assert.Equal(expectedType, message.ResponseType); - await client.DisposeAsync(); - _clients.Remove(client); + await connection.DisposeAsync(); + _connections.Remove(connection); } [Fact] @@ -372,20 +378,20 @@ public async Task Poll_WithoutMessageReferenceNumbers_MapsCorrectly() var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, $"ok {{UAL123 cpdlc {{/data2///N/LOGOFF}}}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.MessageReader.ReadAsync(cts.Token); + var message = await connection.MessageReader.ReadAsync(cts.Token); // Assert Assert.Equal(-1, message.MessageId); - await client.DisposeAsync(); - _clients.Remove(client); + await connection.DisposeAsync(); + _connections.Remove(connection); } [Fact] @@ -397,14 +403,14 @@ public async Task Poll_Data1PositionReport_ParsesCorrectly() HttpStatusCode.OK, "ok {UAL123 cpdlc {/DATA1/*/*/*/*/FL380/*/0.84/\n\nOVER MEPAB AT 0501Z, FL380,\nESTIMATING ISTEM AT 0533Z,\nNEXT MISLY.\n\nETA AT 0736Z,\n39.60 X 1000 KG FUEL REMAINING.}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.MessageReader.ReadAsync(cts.Token); + var message = await connection.MessageReader.ReadAsync(cts.Token); // Assert Assert.Equal("UAL123", message.Sender); @@ -415,8 +421,8 @@ public async Task Poll_Data1PositionReport_ParsesCorrectly() "OVER MEPAB AT 0501Z, FL380, ESTIMATING ISTEM AT 0533Z, NEXT MISLY. ETA AT 0736Z, 39.60 X 1000 KG FUEL REMAINING.", message.Content); - await client.DisposeAsync(); - _clients.Remove(client); + await connection.DisposeAsync(); + _connections.Remove(connection); } [Fact] @@ -425,10 +431,10 @@ public async Task ListConnections_ReturnsCallsigns() // Arrange var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok {UAL123 DAL456 AAL789}"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - var callsigns = await client.ListConnections(CancellationToken.None); + var callsigns = await connection.ListConnections(CancellationToken.None); // Assert Assert.Equal(3, callsigns.Length); @@ -455,10 +461,10 @@ public async Task ListConnections_EmptyResponse_ReturnsEmptyArray() // Arrange var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - var callsigns = await client.ListConnections(CancellationToken.None); + var callsigns = await connection.ListConnections(CancellationToken.None); // Assert Assert.Empty(callsigns); @@ -470,10 +476,10 @@ public async Task RequestPeriodicAdscContract_FormatsPayloadCorrectly() // Arrange var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.RequestPeriodicAdscContract("UAL123", TimeSpan.FromMinutes(5), CancellationToken.None); + await connection.RequestPeriodicAdscContract("UAL123", TimeSpan.FromMinutes(5), CancellationToken.None); // Assert var formData = await ParseFormDataFromRequest(httpHandler.Requests.Single()); @@ -488,11 +494,11 @@ public async Task RequestPeriodicAdscContract_WhenIntervalIsZero_Throws() { // Arrange var httpHandler = new TestHttpMessageHandler(); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act & Assert await Assert.ThrowsAsync(() => - client.RequestPeriodicAdscContract("UAL123", TimeSpan.Zero, CancellationToken.None)); + connection.RequestPeriodicAdscContract("UAL123", TimeSpan.Zero, CancellationToken.None)); Assert.Empty(httpHandler.Requests); } @@ -502,10 +508,10 @@ public async Task RequestAdscDemandReport_FormatsPayloadCorrectly() // Arrange var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.RequestAdscDemandReport("UAL123", CancellationToken.None); + await connection.RequestAdscDemandReport("UAL123", CancellationToken.None); // Assert var formData = await ParseFormDataFromRequest(httpHandler.Requests.Single()); @@ -520,10 +526,10 @@ public async Task CancelAdscContract_FormatsPayloadCorrectly() // Arrange var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.CancelAdscContract("UAL123", CancellationToken.None); + await connection.CancelAdscContract("UAL123", CancellationToken.None); // Assert var formData = await ParseFormDataFromRequest(httpHandler.Requests.Single()); @@ -541,14 +547,14 @@ public async Task Poll_AdscReport_ParsesBasicGroup() var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, "ok {UAL123 ads-c {REPORT UAL123 131155 -33.946100 151.177200 37000}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.AdscMessageReader.ReadAsync(cts.Token); + var message = await connection.AdscMessageReader.ReadAsync(cts.Token); // Assert var reportMessage = Assert.IsType(message); @@ -569,14 +575,14 @@ public async Task Poll_AdscReportWithOptionalGroups_ParsesBasicGroup() var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, "ok {UAL123 ads-c {REPORT UAL123 131155 -33.946100 151.177200 37000 045 480 270/35 -56 LVL}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.AdscMessageReader.ReadAsync(cts.Token); + var message = await connection.AdscMessageReader.ReadAsync(cts.Token); // Assert var reportMessage = Assert.IsType(message); @@ -594,14 +600,14 @@ public async Task Poll_AdscReportFromPreviousMonth_ParsesTimestamp() var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, "ok {UAL123 ads-c {REPORT UAL123 312359 -33.946100 151.177200 37000}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.AdscMessageReader.ReadAsync(cts.Token); + var message = await connection.AdscMessageReader.ReadAsync(cts.Token); // Assert var reportMessage = Assert.IsType(message); @@ -622,14 +628,14 @@ public async Task Poll_AdscReportPositionFormats_ParsesPosition(string position, var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, $"ok {{UAL123 ads-c {{REPORT UAL123 131155 {position} 37000}}}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.AdscMessageReader.ReadAsync(cts.Token); + var message = await connection.AdscMessageReader.ReadAsync(cts.Token); // Assert var reportMessage = Assert.IsType(message); @@ -650,14 +656,14 @@ public async Task Poll_AdscReportAltitude_ParsesAltitudeInFeet(string altitude, var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, $"ok {{UAL123 ads-c {{REPORT UAL123 131155 -33.946100 151.177200 {altitude}}}}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.AdscMessageReader.ReadAsync(cts.Token); + var message = await connection.AdscMessageReader.ReadAsync(cts.Token); // Assert var reportMessage = Assert.IsType(message); @@ -676,14 +682,14 @@ public async Task Poll_AdscReportWithInvalidPosition_IgnoresReport(string positi var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, $"ok {{UAL123 ads-c {{REPORT UAL123 131155 {position} 37000}}}} {{DAL456 ads-c {{REJECT}}}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.AdscMessageReader.ReadAsync(cts.Token); + var message = await connection.AdscMessageReader.ReadAsync(cts.Token); // Assert var rejection = Assert.IsType(message); @@ -697,14 +703,14 @@ public async Task Poll_AdscReject_ParsesCorrectly() var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, "ok {UAL123 ads-c {REJECT}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.AdscMessageReader.ReadAsync(cts.Token); + var message = await connection.AdscMessageReader.ReadAsync(cts.Token); // Assert var rejection = Assert.IsType(message); @@ -718,21 +724,21 @@ public async Task Poll_CpdlcAndAdscMessages_AreWrittenToSeparateReaders() var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, "ok {UAL123 cpdlc {/data2/5//Y/REQUEST DESCENT}} {DAL456 ads-c {REJECT}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var downlink = await client.MessageReader.ReadAsync(cts.Token); - var adscMessage = await client.AdscMessageReader.ReadAsync(cts.Token); + var downlink = await connection.MessageReader.ReadAsync(cts.Token); + var adscMessage = await connection.AdscMessageReader.ReadAsync(cts.Token); // Assert Assert.Equal("UAL123", downlink.Sender); Assert.Equal("DAL456", adscMessage.Sender); - Assert.False(client.MessageReader.TryRead(out _)); - Assert.False(client.AdscMessageReader.TryRead(out _)); + Assert.False(connection.MessageReader.TryRead(out _)); + Assert.False(connection.AdscMessageReader.TryRead(out _)); } [Fact] @@ -742,15 +748,15 @@ public async Task RequestPeriodicAdscContract_LogsUplinkPacket() var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); var clock = new TestClock(); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); // Act - await client.RequestPeriodicAdscContract("UAL123", TimeSpan.FromMinutes(5), CancellationToken.None); + await connection.RequestPeriodicAdscContract("UAL123", TimeSpan.FromMinutes(5), CancellationToken.None); // Assert var entry = Assert.Single(await _adscMessageLogRepository.All(CancellationToken.None)); Assert.Equal(clock.UtcNow(), entry.Time); - Assert.Equal("Hoppies/YBBB", entry.AcarsClientId); + Assert.Equal("Hoppies/YBBB", entry.AcarsConnectionId); Assert.Equal("YBBB", entry.StationId); Assert.Equal("UAL123", entry.Callsign); Assert.Equal(AdscMessageDirection.Uplink, entry.Direction); @@ -763,11 +769,11 @@ public async Task RequestAdscDemandReport_WhenSendFails_DoesNotLogPacket() // Arrange var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.InternalServerError, "error"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act & Assert await Assert.ThrowsAsync(() => - client.RequestAdscDemandReport("UAL123", CancellationToken.None)); + connection.RequestAdscDemandReport("UAL123", CancellationToken.None)); Assert.Empty(await _adscMessageLogRepository.All(CancellationToken.None)); } @@ -780,15 +786,15 @@ public async Task Poll_AdscMessages_LogsDownlinkPackets() HttpStatusCode.OK, "ok {UAL123 cpdlc {/data2/5//Y/REQUEST DESCENT}} {UAL123 ads-c {REPORT UAL123 131155 ABC 151.177200 37000}} {DAL456 ads-c {REJECT}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start // The packet is logged before the message is written to the reader using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - await client.AdscMessageReader.ReadAsync(cts.Token); + await connection.AdscMessageReader.ReadAsync(cts.Token); // Assert var entries = await _adscMessageLogRepository.All(CancellationToken.None); diff --git a/source/CPDLCServer.Tests/Handlers/RefreshAcarsCallsignsRequestHandlerTests.cs b/source/CPDLCServer.Tests/AcarsConnections/Stations/RefreshAcarsCallsignsRequestHandlerTests.cs similarity index 78% rename from source/CPDLCServer.Tests/Handlers/RefreshAcarsCallsignsRequestHandlerTests.cs rename to source/CPDLCServer.Tests/AcarsConnections/Stations/RefreshAcarsCallsignsRequestHandlerTests.cs index a390738..09e1b21 100644 --- a/source/CPDLCServer.Tests/Handlers/RefreshAcarsCallsignsRequestHandlerTests.cs +++ b/source/CPDLCServer.Tests/AcarsConnections/Stations/RefreshAcarsCallsignsRequestHandlerTests.cs @@ -1,13 +1,11 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AcarsConnections.Stations; +using CPDLCServer.Cpdlc.Connections; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.AcarsConnections.Stations; public class RefreshAcarsCallsignsRequestHandlerTests { @@ -15,9 +13,9 @@ public class RefreshAcarsCallsignsRequestHandlerTests public async Task Handle_UpdatesLastSeenForConnectedAircraft() { // Arrange - var clientManager = new TestClientManager(); - var acarsClient = new TestAcarsClient("YBBB"); - clientManager.AddClient("hoppies-ybbb", acarsClient); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var acarsConnection = new TestAcarsConnection("YBBB"); + acarsConnectionManager.AddConnection("hoppies-ybbb", acarsConnection); var aircraftRepository = new TestAircraftRepository(); var acarsConnectedCallsignsRepository = new InMemoryAcarsStationRepository(); @@ -30,13 +28,13 @@ public async Task Handle_UpdatesLastSeenForConnectedAircraft() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(initialTime); aircraft.AcceptLogon(initialTime); - await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); // Simulate the aircraft being connected on the ACARS network - acarsClient.Connections.Add("UAL123"); + acarsConnection.Connections.Add("UAL123"); var handler = new RefreshAcarsCallsignsRequestHandler( - clientManager, + acarsConnectionManager, aircraftRepository, acarsConnectedCallsignsRepository, mediator, @@ -62,9 +60,9 @@ public async Task Handle_UpdatesLastSeenForConnectedAircraft() public async Task Handle_DoesNotUpdateLastSeenForDisconnectedAircraft() { // Arrange - var clientManager = new TestClientManager(); - var acarsClient = new TestAcarsClient("YBBB"); - clientManager.AddClient("hoppies-ybbb", acarsClient); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var acarsConnection = new TestAcarsConnection("YBBB"); + acarsConnectionManager.AddConnection("hoppies-ybbb", acarsConnection); var aircraftRepository = new TestAircraftRepository(); var acarsConnectedCallsignsRepository = new InMemoryAcarsStationRepository(); @@ -77,13 +75,13 @@ public async Task Handle_DoesNotUpdateLastSeenForDisconnectedAircraft() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(initialTime); aircraft.AcceptLogon(initialTime); - await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); // Aircraft is NOT in the ACARS connections list (disconnected) - // acarsClient.Connections remains empty + // acarsConnection.Connections remains empty var handler = new RefreshAcarsCallsignsRequestHandler( - clientManager, + acarsConnectionManager, aircraftRepository, acarsConnectedCallsignsRepository, mediator, @@ -106,14 +104,14 @@ public async Task Handle_DoesNotUpdateLastSeenForDisconnectedAircraft() } [Fact] - public async Task Handle_OnlyUpdatesAircraftForMatchingAcarsClient() + public async Task Handle_OnlyUpdatesAircraftForMatchingAcarsConnection() { // Arrange - var clientManager = new TestClientManager(); - var acarsClientYbbb = new TestAcarsClient("YBBB"); - var acarsClientYmmm = new TestAcarsClient("YMMM"); - clientManager.AddClient("hoppies-ybbb", acarsClientYbbb); - clientManager.AddClient("hoppies-ymmm", acarsClientYmmm); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var acarsConnectionYbbb = new TestAcarsConnection("YBBB"); + var acarsConnectionYmmm = new TestAcarsConnection("YMMM"); + acarsConnectionManager.AddConnection("hoppies-ybbb", acarsConnectionYbbb); + acarsConnectionManager.AddConnection("hoppies-ymmm", acarsConnectionYmmm); var aircraftRepository = new TestAircraftRepository(); var acarsConnectedCallsignsRepository = new InMemoryAcarsStationRepository(); @@ -127,20 +125,20 @@ public async Task Handle_OnlyUpdatesAircraftForMatchingAcarsClient() var aircraftYbbb = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraftYbbb.RequestLogon(initialTime); aircraftYbbb.AcceptLogon(initialTime); - await aircraftRepository.Add(new AircraftKey(aircraftYbbb.Callsign, aircraftYbbb.AcarsClientId), aircraftYbbb, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(aircraftYbbb.Callsign, aircraftYbbb.AcarsConnectionId), aircraftYbbb, CancellationToken.None); // Aircraft on YMMM var aircraftYmmm = new AircraftConnection("QFA456", "hoppies-ymmm", "YMMM", DataAuthorityState.CurrentDataAuthority); aircraftYmmm.RequestLogon(initialTime); aircraftYmmm.AcceptLogon(initialTime); - await aircraftRepository.Add(new AircraftKey(aircraftYmmm.Callsign, aircraftYmmm.AcarsClientId), aircraftYmmm, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(aircraftYmmm.Callsign, aircraftYmmm.AcarsConnectionId), aircraftYmmm, CancellationToken.None); // Both aircraft are connected on their respective ACARS networks - acarsClientYbbb.Connections.Add("UAL123"); - acarsClientYmmm.Connections.Add("QFA456"); + acarsConnectionYbbb.Connections.Add("UAL123"); + acarsConnectionYmmm.Connections.Add("QFA456"); var handler = new RefreshAcarsCallsignsRequestHandler( - clientManager, + acarsConnectionManager, aircraftRepository, acarsConnectedCallsignsRepository, mediator, @@ -171,9 +169,9 @@ public async Task Handle_OnlyUpdatesAircraftForMatchingAcarsClient() public async Task Handle_UpdatesRepositoryWithConnectedCallsigns() { // Arrange - var clientManager = new TestClientManager(); - var acarsClient = new TestAcarsClient("YBBB"); - clientManager.AddClient("hoppies-ybbb", acarsClient); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var acarsConnection = new TestAcarsConnection("YBBB"); + acarsConnectionManager.AddConnection("hoppies-ybbb", acarsConnection); var aircraftRepository = new TestAircraftRepository(); var acarsConnectedCallsignsRepository = new InMemoryAcarsStationRepository(); @@ -184,11 +182,11 @@ public async Task Handle_UpdatesRepositoryWithConnectedCallsigns() clock.SetUtcNow(initialTime); // Simulate aircraft connected on the ACARS network - acarsClient.Connections.Add("UAL123"); - acarsClient.Connections.Add("QFA456"); + acarsConnection.Connections.Add("UAL123"); + acarsConnection.Connections.Add("QFA456"); var handler = new RefreshAcarsCallsignsRequestHandler( - clientManager, + acarsConnectionManager, aircraftRepository, acarsConnectedCallsignsRepository, mediator, @@ -211,9 +209,9 @@ public async Task Handle_UpdatesRepositoryWithConnectedCallsigns() public async Task Handle_PublishesNotificationWhenCallsignsChange() { // Arrange - var clientManager = new TestClientManager(); - var acarsClient = new TestAcarsClient("YBBB"); - clientManager.AddClient("hoppies-ybbb", acarsClient); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var acarsConnection = new TestAcarsConnection("YBBB"); + acarsConnectionManager.AddConnection("hoppies-ybbb", acarsConnection); var aircraftRepository = new TestAircraftRepository(); var acarsConnectedCallsignsRepository = new InMemoryAcarsStationRepository(); @@ -224,10 +222,10 @@ public async Task Handle_PublishesNotificationWhenCallsignsChange() clock.SetUtcNow(initialTime); // Simulate aircraft connected on the ACARS network - acarsClient.Connections.Add("UAL123"); + acarsConnection.Connections.Add("UAL123"); var handler = new RefreshAcarsCallsignsRequestHandler( - clientManager, + acarsConnectionManager, aircraftRepository, acarsConnectedCallsignsRepository, mediator, @@ -250,9 +248,9 @@ await mediator.Received(1).Publish( public async Task Handle_DoesNotPublishNotificationWhenCallsignsUnchanged() { // Arrange - var clientManager = new TestClientManager(); - var acarsClient = new TestAcarsClient("YBBB"); - clientManager.AddClient("hoppies-ybbb", acarsClient); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var acarsConnection = new TestAcarsConnection("YBBB"); + acarsConnectionManager.AddConnection("hoppies-ybbb", acarsConnection); var aircraftRepository = new TestAircraftRepository(); var acarsConnectedCallsignsRepository = new InMemoryAcarsStationRepository(); @@ -263,13 +261,13 @@ public async Task Handle_DoesNotPublishNotificationWhenCallsignsUnchanged() clock.SetUtcNow(initialTime); // Simulate aircraft connected on the ACARS network - acarsClient.Connections.Add("UAL123"); + acarsConnection.Connections.Add("UAL123"); // Pre-populate the repository with the same callsign await acarsConnectedCallsignsRepository.Update(["UAL123"], CancellationToken.None); var handler = new RefreshAcarsCallsignsRequestHandler( - clientManager, + acarsConnectionManager, aircraftRepository, acarsConnectedCallsignsRepository, mediator, @@ -291,9 +289,9 @@ await mediator.DidNotReceive().Publish( public async Task Handle_PublishesNotificationWhenCallsignAdded() { // Arrange - var clientManager = new TestClientManager(); - var acarsClient = new TestAcarsClient("YBBB"); - clientManager.AddClient("hoppies-ybbb", acarsClient); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var acarsConnection = new TestAcarsConnection("YBBB"); + acarsConnectionManager.AddConnection("hoppies-ybbb", acarsConnection); var aircraftRepository = new TestAircraftRepository(); var acarsConnectedCallsignsRepository = new InMemoryAcarsStationRepository(); @@ -307,11 +305,11 @@ public async Task Handle_PublishesNotificationWhenCallsignAdded() await acarsConnectedCallsignsRepository.Update(["UAL123"], CancellationToken.None); // Simulate a new aircraft joining the ACARS network - acarsClient.Connections.Add("UAL123"); - acarsClient.Connections.Add("QFA456"); + acarsConnection.Connections.Add("UAL123"); + acarsConnection.Connections.Add("QFA456"); var handler = new RefreshAcarsCallsignsRequestHandler( - clientManager, + acarsConnectionManager, aircraftRepository, acarsConnectedCallsignsRepository, mediator, @@ -336,9 +334,9 @@ await mediator.Received(1).Publish( public async Task Handle_PublishesNotificationWhenCallsignRemoved() { // Arrange - var clientManager = new TestClientManager(); - var acarsClient = new TestAcarsClient("YBBB"); - clientManager.AddClient("hoppies-ybbb", acarsClient); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var acarsConnection = new TestAcarsConnection("YBBB"); + acarsConnectionManager.AddConnection("hoppies-ybbb", acarsConnection); var aircraftRepository = new TestAircraftRepository(); var acarsConnectedCallsignsRepository = new InMemoryAcarsStationRepository(); @@ -352,11 +350,11 @@ public async Task Handle_PublishesNotificationWhenCallsignRemoved() await acarsConnectedCallsignsRepository.Update(["UAL123", "QFA456"], CancellationToken.None); // Simulate one aircraft leaving the ACARS network - acarsClient.Connections.Add("UAL123"); + acarsConnection.Connections.Add("UAL123"); // QFA456 is no longer connected var handler = new RefreshAcarsCallsignsRequestHandler( - clientManager, + acarsConnectionManager, aircraftRepository, acarsConnectedCallsignsRepository, mediator, diff --git a/source/CPDLCServer.Tests/AcarsConnections/Traffic/AcarsTrafficLogTests.cs b/source/CPDLCServer.Tests/AcarsConnections/Traffic/AcarsTrafficLogTests.cs new file mode 100644 index 0000000..b52db51 --- /dev/null +++ b/source/CPDLCServer.Tests/AcarsConnections/Traffic/AcarsTrafficLogTests.cs @@ -0,0 +1,85 @@ +using CPDLCServer.AcarsConnections.Traffic; + +namespace CPDLCServer.Tests.AcarsConnections.Traffic; + +public class AcarsTrafficLogTests +{ + [Fact] + public void Get_ReturnsTheNewestEntriesFirst() + { + // Arrange + var trafficLog = new AcarsTrafficLog(); + + // Act + trafficLog.Add("Hoppies/YBBB", CreateEntry("first")); + trafficLog.Add("Hoppies/YBBB", CreateEntry("second")); + + // Assert + Assert.Equal(["second", "first"], trafficLog.Get("Hoppies/YBBB").Select(e => e.Response)); + } + + [Fact] + public void Add_KeepsOnlyTheMostRecentEntriesOfEachConnection() + { + // Arrange + var trafficLog = new AcarsTrafficLog(capacity: 2); + + // Act + trafficLog.Add("Hoppies/YBBB", CreateEntry("first")); + trafficLog.Add("Hoppies/YBBB", CreateEntry("second")); + trafficLog.Add("Hoppies/YBBB", CreateEntry("third")); + trafficLog.Add("Hoppies/YMMM", CreateEntry("other")); + + // Assert + Assert.Equal(["third", "second"], trafficLog.Get("Hoppies/YBBB").Select(e => e.Response)); + Assert.Equal(["other"], trafficLog.Get("Hoppies/YMMM").Select(e => e.Response)); + } + + [Fact] + public void Get_WhenNoTraffic_ReturnsNoEntries() + { + // Arrange + var trafficLog = new AcarsTrafficLog(); + + // Act & Assert + Assert.Empty(trafficLog.Get("Hoppies/YBBB")); + } + + [Fact] + public void FormatRequest_ReplacesTheAuthenticationCode() + { + // Arrange + var fields = new Dictionary + { + ["logon"] = "SECRET123", + ["from"] = "YBBB", + ["type"] = "poll" + }; + + // Act + var request = AcarsTrafficLog.FormatRequest(fields); + + // Assert + Assert.DoesNotContain("SECRET123", request); + Assert.Equal($"logon={AcarsTrafficLog.RedactedValue}\nfrom=YBBB\ntype=poll", request); + } + + [Theory] + [InlineData("poll", "ok", null, true)] + [InlineData("poll", "ok {UAL123 cpdlc {/data2/1//Y/REQUEST DESCENT}}", null, false)] + [InlineData("poll", null, "Timeout", false)] + [InlineData("cpdlc", "ok", null, false)] + public void IsEmptyPoll_IsTrueOnlyForAPollWithNoMessages(string type, string? response, string? error, bool expected) + { + // Arrange + var entry = new AcarsTrafficEntry(DateTimeOffset.UtcNow, type, "type=poll", 200, response, TimeSpan.Zero, error); + + // Act & Assert + Assert.Equal(expected, entry.IsEmptyPoll); + } + + static AcarsTrafficEntry CreateEntry(string response) + { + return new AcarsTrafficEntry(DateTimeOffset.UtcNow, "poll", "type=poll", 200, response, TimeSpan.Zero, null); + } +} diff --git a/source/CPDLCServer.Tests/AdscContracts/AdscContractRepositoryTests.cs b/source/CPDLCServer.Tests/AdscContracts/AdscContractRepositoryTests.cs new file mode 100644 index 0000000..ed4c8fd --- /dev/null +++ b/source/CPDLCServer.Tests/AdscContracts/AdscContractRepositoryTests.cs @@ -0,0 +1,71 @@ +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Tests.Mocks; + +namespace CPDLCServer.Tests.AdscContracts; + +public class AdscContractRepositoryTests +{ + static readonly DateTimeOffset Start = new(2026, 10, 13, 12, 0, 0, TimeSpan.Zero); + + [Fact] + public async Task Find_ReturnsSavedContract() + { + // Arrange + using var database = new TestDatabase(); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(15), Start.AddMinutes(-10)); + contract.RequestDefaultContract(TimeSpan.FromMinutes(10)); + contract.ReportReceived(new AdscReport(Start.AddMinutes(-5), -33.9461, 151.1772, 37000, AdscReportSource.VATSIM)); + contract.RequestSelectedContract(TimeSpan.FromMinutes(2)); + contract.RequestDemandReport(); + contract.LogActivity(Start); + + await using (var dbContext = database.CreateDbContext()) + { + await new AdscContractRepository(dbContext).Add(new("UAL123", "YBBB"), contract, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act + await using var readDbContext = database.CreateDbContext(); + var saved = await new AdscContractRepository(readDbContext).Find(new("UAL123", "YBBB"), CancellationToken.None); + + // Assert + Assert.NotNull(saved); + Assert.Equal(TimeSpan.FromMinutes(10), saved.DefaultReportingInterval); + Assert.Equal(TimeSpan.FromMinutes(2), saved.ReportingInterval); + Assert.Equal(AdscContractState.Accepted, saved.DefaultContractState); + Assert.Equal(TimeSpan.FromMinutes(2), saved.SelectedReportingInterval); + Assert.Equal(AdscContractState.Sent, saved.SelectedContractState); + Assert.Equal(AdscContractState.Sent, saved.DemandContractState); + Assert.Equal(Start.AddMinutes(-10), saved.Created); + Assert.Equal(Start, saved.LastActivity); + Assert.Equal(Start.AddMinutes(-5), saved.LastReportReceived); + Assert.Equal(AdscReportSource.VATSIM, saved.ReportingSource); + } + + [Fact] + public async Task Remove_DeletesContract() + { + // Arrange + using var database = new TestDatabase(); + await using (var dbContext = database.CreateDbContext()) + { + await new AdscContractRepository(dbContext).Add(new("UAL123", "YBBB"), new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue), CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act + bool removed; + await using (var dbContext = database.CreateDbContext()) + { + removed = await new AdscContractRepository(dbContext).Remove(new("UAL123", "YBBB"), CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Assert + Assert.True(removed); + await using var readDbContext = database.CreateDbContext(); + Assert.Empty(await new AdscContractRepository(readDbContext).All(CancellationToken.None)); + } +} diff --git a/source/CPDLCServer.Tests/Model/AdscContractTests.cs b/source/CPDLCServer.Tests/AdscContracts/AdscContractTests.cs similarity index 59% rename from source/CPDLCServer.Tests/Model/AdscContractTests.cs rename to source/CPDLCServer.Tests/AdscContracts/AdscContractTests.cs index c09483b..5ef1f50 100644 --- a/source/CPDLCServer.Tests/Model/AdscContractTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/AdscContractTests.cs @@ -1,18 +1,19 @@ -using CPDLCServer.Model; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; -namespace CPDLCServer.Tests.Model; +namespace CPDLCServer.Tests.AdscContracts; public class AdscContractTests { static readonly TimeSpan DefaultInterval = TimeSpan.FromMinutes(10); static readonly TimeSpan SelectedInterval = TimeSpan.FromMinutes(2); - static readonly DateTimeOffset Ends = new(2026, 1, 1, 1, 0, 0, TimeSpan.Zero); + static readonly AdscReport Report = new(new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero), -33.9461, 151.1772, 37000, AdscReportSource.Hoppie); [Fact] public void RequestDefaultContract_SendsDefaultContract() { // Arrange - var contract = new AdscContract("UAL123", "YBBB"); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); // Act contract.RequestDefaultContract(DefaultInterval); @@ -24,13 +25,26 @@ public void RequestDefaultContract_SendsDefaultContract() Assert.True(contract.IsActive); } + [Fact] + public void RequestDefaultContract_UpdatesDefaultReportingInterval() + { + // Arrange - the default reporting interval of the ATSU changed after the contract was made + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(15), DateTimeOffset.MinValue); + + // Act + contract.RequestDefaultContract(DefaultInterval); + + // Assert + Assert.Equal(DefaultInterval, contract.DefaultReportingInterval); + } + [Fact] public void RequestDefaultContract_WhenSelectedContractIsAccepted_EndsSelectedContract() { // Arrange - var contract = new AdscContract("UAL123", "YBBB"); - contract.RequestSelectedContract(SelectedInterval, Ends); - contract.ReportReceived(); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); + contract.RequestSelectedContract(SelectedInterval); + contract.ReportReceived(Report); // Act contract.RequestDefaultContract(DefaultInterval); @@ -40,15 +54,14 @@ public void RequestDefaultContract_WhenSelectedContractIsAccepted_EndsSelectedCo Assert.Equal(AdscContractState.Sent, contract.DefaultContractState); Assert.Null(contract.SelectedReportingInterval); Assert.Null(contract.SelectedContractState); - Assert.Null(contract.SelectedContractEnds); } [Fact] public void RequestDefaultContract_WhenSelectedContractIsRejected_KeepsRejection() { // Arrange - var contract = new AdscContract("UAL123", "YBBB"); - contract.RequestSelectedContract(SelectedInterval, Ends); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); + contract.RequestSelectedContract(SelectedInterval); contract.Reject(); // Act @@ -64,18 +77,17 @@ public void RequestDefaultContract_WhenSelectedContractIsRejected_KeepsRejection public void RequestSelectedContract_SendsSelectedContractAndKeepsDefaultContract() { // Arrange - var contract = new AdscContract("UAL123", "YBBB"); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(DefaultInterval); - contract.ReportReceived(); + contract.ReportReceived(Report); // Act - contract.RequestSelectedContract(SelectedInterval, Ends); + contract.RequestSelectedContract(SelectedInterval); // Assert Assert.Equal(SelectedInterval, contract.ReportingInterval); Assert.Equal(SelectedInterval, contract.SelectedReportingInterval); Assert.Equal(AdscContractState.Sent, contract.SelectedContractState); - Assert.Equal(Ends, contract.SelectedContractEnds); Assert.Equal(AdscContractState.Accepted, contract.DefaultContractState); } @@ -83,14 +95,13 @@ public void RequestSelectedContract_SendsSelectedContractAndKeepsDefaultContract public void ReportReceived_WhenDefaultContractIsSent_AcceptsDefaultContract() { // Arrange - var contract = new AdscContract("UAL123", "YBBB"); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(DefaultInterval); // Act - var changed = contract.ReportReceived(); + contract.ReportReceived(Report); // Assert - Assert.True(changed); Assert.Equal(AdscContractState.Accepted, contract.DefaultContractState); } @@ -98,15 +109,14 @@ public void ReportReceived_WhenDefaultContractIsSent_AcceptsDefaultContract() public void ReportReceived_WhenSelectedContractIsSent_AcceptsSelectedContractAndEndsDefaultContract() { // Arrange - var contract = new AdscContract("UAL123", "YBBB"); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(DefaultInterval); - contract.RequestSelectedContract(SelectedInterval, Ends); + contract.RequestSelectedContract(SelectedInterval); // Act - var changed = contract.ReportReceived(); + contract.ReportReceived(Report); // Assert - Assert.True(changed); Assert.Equal(AdscContractState.Accepted, contract.SelectedContractState); Assert.Null(contract.DefaultContractState); } @@ -115,32 +125,48 @@ public void ReportReceived_WhenSelectedContractIsSent_AcceptsSelectedContractAnd public void ReportReceived_WhenDemandReportIsSent_AcceptsDemandReport() { // Arrange - var contract = new AdscContract("UAL123", "YBBB"); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDemandReport(); // Act - var changed = contract.ReportReceived(); + contract.ReportReceived(Report); // Assert - Assert.True(changed); Assert.Equal(AdscContractState.Accepted, contract.DemandContractState); Assert.False(contract.HasPeriodicContract); Assert.True(contract.IsActive); } [Fact] - public void ReportReceived_WhenNothingIsSent_ReturnsFalse() + public void ReportReceived_RecordsTimestampAndSource() + { + // Arrange + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); + contract.RequestDefaultContract(DefaultInterval); + var report = Report with { Source = AdscReportSource.VATSIM }; + + // Act + contract.ReportReceived(report); + + // Assert + Assert.Equal(report.Timestamp, contract.LastReportReceived); + Assert.Equal(AdscReportSource.VATSIM, contract.ReportingSource); + } + + [Fact] + public void ReportTimedOut_RemovesSourceAndKeepsTimestamp() { // Arrange - var contract = new AdscContract("UAL123", "YBBB"); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(DefaultInterval); - contract.ReportReceived(); + contract.ReportReceived(Report); // Act - var changed = contract.ReportReceived(); + contract.ReportTimedOut(); // Assert - Assert.False(changed); + Assert.Null(contract.ReportingSource); + Assert.Equal(Report.Timestamp, contract.LastReportReceived); Assert.Equal(AdscContractState.Accepted, contract.DefaultContractState); } @@ -148,10 +174,10 @@ public void ReportReceived_WhenNothingIsSent_ReturnsFalse() public void Reject_WhenSelectedContractIsSent_RejectsSelectedContract() { // Arrange - var contract = new AdscContract("UAL123", "YBBB"); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(DefaultInterval); - contract.ReportReceived(); - contract.RequestSelectedContract(SelectedInterval, Ends); + contract.ReportReceived(Report); + contract.RequestSelectedContract(SelectedInterval); // Act var selectedContractRejected = contract.Reject(); @@ -159,7 +185,6 @@ public void Reject_WhenSelectedContractIsSent_RejectsSelectedContract() // Assert Assert.True(selectedContractRejected); Assert.Equal(AdscContractState.Rejected, contract.SelectedContractState); - Assert.Null(contract.SelectedContractEnds); Assert.Equal(AdscContractState.Accepted, contract.DefaultContractState); } @@ -167,9 +192,9 @@ public void Reject_WhenSelectedContractIsSent_RejectsSelectedContract() public void Reject_WhenSelectedContractIsAccepted_RejectsSelectedContract() { // Arrange - var contract = new AdscContract("UAL123", "YBBB"); - contract.RequestSelectedContract(SelectedInterval, Ends); - contract.ReportReceived(); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); + contract.RequestSelectedContract(SelectedInterval); + contract.ReportReceived(Report); // Act var selectedContractRejected = contract.Reject(); @@ -184,7 +209,7 @@ public void Reject_WhenSelectedContractIsAccepted_RejectsSelectedContract() public void Reject_WhenDefaultContractIsSent_RejectsDefaultContract() { // Arrange - var contract = new AdscContract("UAL123", "YBBB"); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(DefaultInterval); // Act @@ -200,9 +225,9 @@ public void Reject_WhenDefaultContractIsSent_RejectsDefaultContract() public void Reject_WhenDemandReportIsSent_RejectsDemandReport() { // Arrange - var contract = new AdscContract("UAL123", "YBBB"); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(DefaultInterval); - contract.ReportReceived(); + contract.ReportReceived(Report); contract.RequestDemandReport(); // Act @@ -217,9 +242,9 @@ public void Reject_WhenDemandReportIsSent_RejectsDemandReport() public void Reject_WhenDemandReportIsAccepted_KeepsDemandReport() { // Arrange - var contract = new AdscContract("UAL123", "YBBB"); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDemandReport(); - contract.ReportReceived(); + contract.ReportReceived(Report); contract.RequestDefaultContract(DefaultInterval); // Act diff --git a/source/CPDLCServer.Tests/Handlers/AdscMessageReceivedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/AdscMessageReceivedNotificationHandlerTests.cs similarity index 83% rename from source/CPDLCServer.Tests/Handlers/AdscMessageReceivedNotificationHandlerTests.cs rename to source/CPDLCServer.Tests/AdscContracts/AdscMessageReceivedNotificationHandlerTests.cs index ae7e833..81522ea 100644 --- a/source/CPDLCServer.Tests/Handlers/AdscMessageReceivedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/AdscMessageReceivedNotificationHandlerTests.cs @@ -1,16 +1,15 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.AdscContracts; public class AdscMessageReceivedNotificationHandlerTests { + static readonly AdscReport Report = new(DateTimeOffset.UtcNow, -33.9461, 151.1772, 37000, AdscReportSource.Hoppie); static readonly TimeSpan DefaultInterval = TimeSpan.FromMinutes(10); static readonly TimeSpan SelectedInterval = TimeSpan.FromMinutes(2); @@ -24,7 +23,7 @@ public async Task Handle_Report_PublishesReport() contract.RequestDefaultContract(DefaultInterval); var mediator = Substitute.For(); - var handler = new AdscMessageReceivedNotificationHandler(contractRepository, mediator, Logger.None); + var handler = new AdscMessageReceivedNotificationHandler(new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); var report = new AdscReport(clock.UtcNow(), -33.9461, 151.1772, 37000, AdscReportSource.Hoppie); var received = clock.UtcNow().AddSeconds(30); @@ -52,7 +51,7 @@ public async Task Handle_Report_WhenNoContract_IsIgnored() // Arrange var contractRepository = new TestAdscContractRepository(); var mediator = Substitute.For(); - var handler = new AdscMessageReceivedNotificationHandler(contractRepository, mediator, Logger.None); + var handler = new AdscMessageReceivedNotificationHandler(new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); // Act await handler.Handle(CreateReport("YBBB"), CancellationToken.None); @@ -71,7 +70,7 @@ public async Task Handle_Report_WhenContractIsWithOtherStation_IsIgnored() contract.RequestDefaultContract(DefaultInterval); var mediator = Substitute.For(); - var handler = new AdscMessageReceivedNotificationHandler(contractRepository, mediator, Logger.None); + var handler = new AdscMessageReceivedNotificationHandler(new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); // Act await handler.Handle(CreateReport("YBBB"), CancellationToken.None); @@ -89,7 +88,7 @@ public async Task Handle_Report_WhenContractIsSent_AcceptsContract() contract.RequestDefaultContract(DefaultInterval); var mediator = Substitute.For(); - var handler = new AdscMessageReceivedNotificationHandler(contractRepository, mediator, Logger.None); + var handler = new AdscMessageReceivedNotificationHandler(new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); // Act await handler.Handle(CreateReport("YBBB"), CancellationToken.None); @@ -103,23 +102,23 @@ await mediator.Received(1).Publish( } [Fact] - public async Task Handle_Report_WhenContractIsAccepted_DoesNotPublishContractChange() + public async Task Handle_Report_WhenContractIsAccepted_PublishesContractChange() { // Arrange var contractRepository = new TestAdscContractRepository(); var contract = await AddContract(contractRepository, "YBBB"); contract.RequestDefaultContract(DefaultInterval); - contract.ReportReceived(); + contract.ReportReceived(Report); var mediator = Substitute.For(); - var handler = new AdscMessageReceivedNotificationHandler(contractRepository, mediator, Logger.None); + var handler = new AdscMessageReceivedNotificationHandler(new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); // Act await handler.Handle(CreateReport("YBBB"), CancellationToken.None); // Assert - await mediator.DidNotReceive().Publish( - Arg.Any(), + await mediator.Received(1).Publish( + Arg.Is(n => n.Contract == contract), Arg.Any()); await mediator.Received(1).Publish( Arg.Any(), @@ -136,7 +135,7 @@ public async Task Handle_Report_WhenContractIsRejected_IsIgnored() contract.Reject(); var mediator = Substitute.For(); - var handler = new AdscMessageReceivedNotificationHandler(contractRepository, mediator, Logger.None); + var handler = new AdscMessageReceivedNotificationHandler(new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); // Act await handler.Handle(CreateReport("YBBB"), CancellationToken.None); @@ -152,10 +151,10 @@ public async Task Handle_Rejection_WhenSelectedContractIsInUse_RejectsSelectedCo // Arrange var contractRepository = new TestAdscContractRepository(); var contract = await AddContract(contractRepository, "YBBB"); - contract.RequestSelectedContract(SelectedInterval, DateTimeOffset.UtcNow.AddHours(1)); + contract.RequestSelectedContract(SelectedInterval); var mediator = Substitute.For(); - var handler = new AdscMessageReceivedNotificationHandler(contractRepository, mediator, Logger.None); + var handler = new AdscMessageReceivedNotificationHandler(new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); // Act await handler.Handle(CreateRejection("YBBB"), CancellationToken.None); @@ -168,7 +167,7 @@ await mediator.Received(1).Publish( Arg.Is(n => n.Contract == contract), Arg.Any()); await mediator.Received(1).Send( - Arg.Is(c => c.StationId == "YBBB" && c.Callsign == "UAL123"), + Arg.Is(c => c.StationId == "YBBB" && c.Callsign == "UAL123" && c.ReportingInterval == TimeSpan.FromMinutes(10)), Arg.Any()); } @@ -181,7 +180,7 @@ public async Task Handle_Rejection_WhenDefaultContractIsInUse_RejectsDefaultCont contract.RequestDefaultContract(DefaultInterval); var mediator = Substitute.For(); - var handler = new AdscMessageReceivedNotificationHandler(contractRepository, mediator, Logger.None); + var handler = new AdscMessageReceivedNotificationHandler(new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); // Act await handler.Handle(CreateRejection("YBBB"), CancellationToken.None); @@ -193,7 +192,7 @@ await mediator.Received(1).Publish( Arg.Is(n => n.Contract == contract), Arg.Any()); await mediator.DidNotReceive().Send( - Arg.Any(), + Arg.Any(), Arg.Any()); } @@ -203,7 +202,7 @@ public async Task Handle_Rejection_WhenNoContract_IsIgnored() // Arrange var mediator = Substitute.For(); var handler = new AdscMessageReceivedNotificationHandler( - new TestAdscContractRepository(), mediator, Logger.None); + new TestAcarsConnectionManager(), new TestAdscContractRepository(), mediator, Logger.None); // Act await handler.Handle(CreateRejection("YBBB"), CancellationToken.None); @@ -221,7 +220,7 @@ public async Task Handle_Report_LogsActivity() contract.RequestDefaultContract(DefaultInterval); var handler = new AdscMessageReceivedNotificationHandler( - contractRepository, Substitute.For(), Logger.None); + new TestAcarsConnectionManager(), contractRepository, Substitute.For(), Logger.None); var notification = CreateReport("YBBB"); // Act @@ -240,7 +239,7 @@ public async Task Handle_Rejection_LogsActivity() contract.RequestDefaultContract(DefaultInterval); var handler = new AdscMessageReceivedNotificationHandler( - contractRepository, Substitute.For(), Logger.None); + new TestAcarsConnectionManager(), contractRepository, Substitute.For(), Logger.None); var notification = CreateRejection("YBBB"); // Act @@ -252,7 +251,7 @@ public async Task Handle_Rejection_LogsActivity() static async Task AddContract(TestAdscContractRepository contractRepository, string stationId) { - var contract = new AdscContract("UAL123", stationId); + var contract = new AdscContract("UAL123", stationId, TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); await contractRepository.Add(new AdscContractKey("UAL123", stationId), contract, CancellationToken.None); return contract; } diff --git a/source/CPDLCServer.Tests/Handlers/CancelAdscContractCommandHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractCommandHandlerTests.cs similarity index 60% rename from source/CPDLCServer.Tests/Handlers/CancelAdscContractCommandHandlerTests.cs rename to source/CPDLCServer.Tests/AdscContracts/CancelAdscContractCommandHandlerTests.cs index 0be85e6..b35c5ec 100644 --- a/source/CPDLCServer.Tests/Handlers/CancelAdscContractCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractCommandHandlerTests.cs @@ -1,13 +1,10 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.AdscContracts; public class CancelAdscContractCommandHandlerTests { @@ -15,20 +12,20 @@ public class CancelAdscContractCommandHandlerTests public async Task Handle_WhenContractExists_SendsCancelAndRemovesContract() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB"); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); var mediator = Substitute.For(); - var handler = new CancelAdscContractCommandHandler(clientManager, contractRepository, mediator, Logger.None); + var handler = new CancelAdscContractCommandHandler(acarsConnectionManager, contractRepository, mediator, new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new CancelAdscContractCommand("YBBB", "UAL123"), CancellationToken.None); // Assert - var client = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Equal("UAL123", Assert.Single(client.CancelledAdscContracts)); + var acarsConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Equal("UAL123", Assert.Single(acarsConnection.CancelledAdscContracts)); Assert.Empty(await contractRepository.All(CancellationToken.None)); await mediator.Received(1).Publish( @@ -40,17 +37,17 @@ await mediator.Received(1).Publish( public async Task Handle_WhenContractNotFound_SendsNothing() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var mediator = Substitute.For(); var handler = new CancelAdscContractCommandHandler( - clientManager, new TestAdscContractRepository(), mediator, Logger.None); + acarsConnectionManager, new TestAdscContractRepository(), mediator, new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new CancelAdscContractCommand("YBBB", "UAL123"), CancellationToken.None); // Assert - var client = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Empty(client.CancelledAdscContracts); + var acarsConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Empty(acarsConnection.CancelledAdscContracts); await mediator.DidNotReceive().Publish( Arg.Any(), @@ -62,13 +59,13 @@ public async Task Handle_OnlyRemovesContractForStation() { // Arrange var contractRepository = new TestAdscContractRepository(); - var ybbbContract = new AdscContract("UAL123", "YBBB"); - var ymmmContract = new AdscContract("UAL123", "YMMM"); + var ybbbContract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); + var ymmmContract = new AdscContract("UAL123", "YMMM", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), ybbbContract, CancellationToken.None); await contractRepository.Add(new AdscContractKey("UAL123", "YMMM"), ymmmContract, CancellationToken.None); var handler = new CancelAdscContractCommandHandler( - new TestClientManager(), contractRepository, Substitute.For(), Logger.None); + new TestAcarsConnectionManager(), contractRepository, Substitute.For(), new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new CancelAdscContractCommand("YBBB", "UAL123"), CancellationToken.None); diff --git a/source/CPDLCServer.Tests/Handlers/CancelAdscContractOnConnectionEndedHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractOnConnectionEndedHandlerTests.cs similarity index 64% rename from source/CPDLCServer.Tests/Handlers/CancelAdscContractOnConnectionEndedHandlerTests.cs rename to source/CPDLCServer.Tests/AdscContracts/CancelAdscContractOnConnectionEndedHandlerTests.cs index ba35c58..bfe6513 100644 --- a/source/CPDLCServer.Tests/Handlers/CancelAdscContractOnConnectionEndedHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractOnConnectionEndedHandlerTests.cs @@ -1,13 +1,11 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts; +using CPDLCServer.Cpdlc.Connections; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.AdscContracts; public class CancelAdscContractOnConnectionEndedHandlerTests { @@ -16,12 +14,12 @@ public async Task Handle_ConnectionTerminated_CancelsContract() { // Arrange var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB"); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); var mediator = Substitute.For(); var handler = new CancelAdscContractOnConnectionEndedHandler( - new TestClientManager(), contractRepository, mediator, Logger.None); + new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); // Act await handler.Handle( @@ -35,16 +33,16 @@ await mediator.Received(1).Send( } [Fact] - public async Task Handle_ConnectionLost_CancelsContractForStationOfAcarsClient() + public async Task Handle_ConnectionLost_CancelsContractForStationOfAcarsConnection() { // Arrange var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YMMM"); + var contract = new AdscContract("UAL123", "YMMM", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); await contractRepository.Add(new AdscContractKey("UAL123", "YMMM"), contract, CancellationToken.None); var mediator = Substitute.For(); var handler = new CancelAdscContractOnConnectionEndedHandler( - new TestClientManager(), contractRepository, mediator, Logger.None); + new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); // Act await handler.Handle( @@ -63,7 +61,7 @@ public async Task Handle_WhenNoContract_DoesNotCancel() // Arrange var mediator = Substitute.For(); var handler = new CancelAdscContractOnConnectionEndedHandler( - new TestClientManager(), new TestAdscContractRepository(), mediator, Logger.None); + new TestAcarsConnectionManager(), new TestAdscContractRepository(), mediator, Logger.None); // Act await handler.Handle( @@ -79,12 +77,12 @@ public async Task Handle_WhenContractIsWithOtherStation_DoesNotCancel() { // Arrange var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YMMM"); + var contract = new AdscContract("UAL123", "YMMM", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); await contractRepository.Add(new AdscContractKey("UAL123", "YMMM"), contract, CancellationToken.None); var mediator = Substitute.For(); var handler = new CancelAdscContractOnConnectionEndedHandler( - new TestClientManager(), contractRepository, mediator, Logger.None); + new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); // Act await handler.Handle( @@ -100,7 +98,7 @@ public async Task Handle_WhenCancelFails_DoesNotThrow() { // Arrange var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB"); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); var mediator = Substitute.For(); @@ -109,11 +107,34 @@ public async Task Handle_WhenCancelFails_DoesNotThrow() .Returns(Task.FromException(new HttpRequestException("Hoppie is down"))); var handler = new CancelAdscContractOnConnectionEndedHandler( - new TestClientManager(), contractRepository, mediator, Logger.None); + new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); // Act & Assert - should not throw await handler.Handle( new AircraftConnectionTerminated("hoppies-ybbb", "YBBB", "UAL123"), CancellationToken.None); } + + [Fact] + public async Task Handle_ConnectionReset_CancelsContract() + { + // Arrange + var contractRepository = new TestAdscContractRepository(); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); + await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); + + var mediator = Substitute.For(); + var handler = new CancelAdscContractOnConnectionEndedHandler( + new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); + + // Act + await handler.Handle( + new AircraftConnectionReset("hoppies-ybbb", "YBBB", "UAL123"), + CancellationToken.None); + + // Assert + await mediator.Received(1).Send( + Arg.Is(c => c.StationId == "YBBB" && c.Callsign == "UAL123"), + Arg.Any()); + } } diff --git a/source/CPDLCServer.Tests/Handlers/EndExpiredAdscContractsRequestHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/EndExpiredAdscContractsRequestHandlerTests.cs similarity index 55% rename from source/CPDLCServer.Tests/Handlers/EndExpiredAdscContractsRequestHandlerTests.cs rename to source/CPDLCServer.Tests/AdscContracts/EndExpiredAdscContractsRequestHandlerTests.cs index 0c619cb..fbe50b2 100644 --- a/source/CPDLCServer.Tests/Handlers/EndExpiredAdscContractsRequestHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/EndExpiredAdscContractsRequestHandlerTests.cs @@ -1,164 +1,121 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts; +using CPDLCServer.Infrastructure; +using CPDLCServer.Settings; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.AdscContracts; public class EndExpiredAdscContractsRequestHandlerTests { static readonly TimeSpan ContractTimeout = TimeSpan.FromMinutes(120); + static readonly TestServerSettingsProvider Settings = new(new ServerSettings { AdscContractTimeoutMinutes = 120 }); - [Fact] - public async Task Handle_WhenSelectedContractHasEnded_RequestsDefaultContract() - { - // Arrange - var clock = new TestClock(); - var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB"); - contract.RequestSelectedContract(TimeSpan.FromMinutes(2), clock.UtcNow()); - contract.LogActivity(clock.UtcNow()); - await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); - - var mediator = Substitute.For(); - var handler = new EndExpiredAdscContractsRequestHandler( - new TestClientManager(), contractRepository, clock, mediator, Logger.None); - - // Act - await handler.Handle(new EndExpiredAdscContractsRequest(ContractTimeout), CancellationToken.None); - - // Assert - await mediator.Received(1).Send( - Arg.Is(c => c.StationId == "YBBB" && c.Callsign == "UAL123"), - Arg.Any()); - } + // The server has been online for longer than any timeout + static readonly ServerStartTime StartedLongAgo = new(DateTimeOffset.MinValue); [Fact] - public async Task Handle_WhenSelectedContractHasNotEnded_DoesNothing() + public async Task Handle_WhenSelectedContractIsActive_KeepsSelectedContract() { // Arrange var clock = new TestClock(); var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB"); - contract.RequestSelectedContract(TimeSpan.FromMinutes(2), clock.UtcNow().AddSeconds(1)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); + contract.RequestSelectedContract(TimeSpan.FromMinutes(2)); contract.LogActivity(clock.UtcNow()); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); var mediator = Substitute.For(); var handler = new EndExpiredAdscContractsRequestHandler( - new TestClientManager(), contractRepository, clock, mediator, Logger.None); + new TestAcarsConnectionManager(), contractRepository, Settings, clock, StartedLongAgo, mediator, new TestUnitOfWork(), Logger.None); // Act - await handler.Handle(new EndExpiredAdscContractsRequest(ContractTimeout), CancellationToken.None); + clock.SetUtcNow(clock.UtcNow() + ContractTimeout - TimeSpan.FromMinutes(1)); + await handler.Handle(new EndExpiredAdscContractsRequest(), CancellationToken.None); // Assert + Assert.Same(contract, Assert.Single(await contractRepository.All(CancellationToken.None))); + Assert.Equal(TimeSpan.FromMinutes(2), contract.SelectedReportingInterval); Assert.Empty(mediator.ReceivedCalls()); } [Fact] - public async Task Handle_WhenNoSelectedContract_DoesNothing() + public async Task Handle_WhenContractIsInactive_CancelsAndRemovesContract() { // Arrange var clock = new TestClock(); var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB"); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(TimeSpan.FromMinutes(10)); contract.LogActivity(clock.UtcNow()); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); + var acarsConnectionManager = new TestAcarsConnectionManager(); var mediator = Substitute.For(); var handler = new EndExpiredAdscContractsRequestHandler( - new TestClientManager(), contractRepository, clock, mediator, Logger.None); + acarsConnectionManager, contractRepository, Settings, clock, StartedLongAgo, mediator, new TestUnitOfWork(), Logger.None); // Act - await handler.Handle(new EndExpiredAdscContractsRequest(ContractTimeout), CancellationToken.None); - - // Assert - Assert.Empty(mediator.ReceivedCalls()); - } - - [Fact] - public async Task Handle_WhenRequestFails_ContinuesWithOtherContracts() - { - // Arrange - var clock = new TestClock(); - var contractRepository = new TestAdscContractRepository(); - foreach (var callsign in new[] { "UAL123", "QFA1" }) - { - var contract = new AdscContract(callsign, "YBBB"); - contract.RequestSelectedContract(TimeSpan.FromMinutes(2), clock.UtcNow()); - contract.LogActivity(clock.UtcNow()); - await contractRepository.Add(new AdscContractKey(callsign, "YBBB"), contract, CancellationToken.None); - } - - var mediator = Substitute.For(); - mediator - .Send(Arg.Is(c => c.Callsign == "UAL123"), Arg.Any()) - .Returns(Task.FromException(new HttpRequestException("Hoppie is down"))); - - var handler = new EndExpiredAdscContractsRequestHandler( - new TestClientManager(), contractRepository, clock, mediator, Logger.None); - - // Act - await handler.Handle(new EndExpiredAdscContractsRequest(ContractTimeout), CancellationToken.None); + clock.SetUtcNow(clock.UtcNow() + ContractTimeout + TimeSpan.FromMinutes(1)); + await handler.Handle(new EndExpiredAdscContractsRequest(), CancellationToken.None); // Assert - await mediator.Received(1).Send( - Arg.Is(c => c.Callsign == "QFA1"), + var acarsConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Equal(["UAL123"], acarsConnection.CancelledAdscContracts); + Assert.Empty(await contractRepository.All(CancellationToken.None)); + await mediator.Received(1).Publish( + Arg.Is(n => n.Callsign == "UAL123" && n.StationId == "YBBB"), Arg.Any()); } [Fact] - public async Task Handle_WhenContractIsInactive_CancelsAndRemovesContract() + public async Task Handle_WhenServerOnlineForLessThanTimeout_KeepsInactiveContract() { - // Arrange + // Arrange - the last activity was long before the server started var clock = new TestClock(); var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB"); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(TimeSpan.FromMinutes(10)); contract.LogActivity(clock.UtcNow()); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); - var clientManager = new TestClientManager(); + var serverStarted = clock.UtcNow() + ContractTimeout; + var acarsConnectionManager = new TestAcarsConnectionManager(); var mediator = Substitute.For(); var handler = new EndExpiredAdscContractsRequestHandler( - clientManager, contractRepository, clock, mediator, Logger.None); + acarsConnectionManager, contractRepository, Settings, clock, new ServerStartTime(serverStarted), mediator, new TestUnitOfWork(), Logger.None); // Act - clock.SetUtcNow(clock.UtcNow() + ContractTimeout + TimeSpan.FromMinutes(1)); - await handler.Handle(new EndExpiredAdscContractsRequest(ContractTimeout), CancellationToken.None); + clock.SetUtcNow(serverStarted + ContractTimeout); + await handler.Handle(new EndExpiredAdscContractsRequest(), CancellationToken.None); // Assert - var client = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Equal(["UAL123"], client.CancelledAdscContracts); - Assert.Empty(await contractRepository.All(CancellationToken.None)); - await mediator.Received(1).Publish( - Arg.Is(n => n.Callsign == "UAL123" && n.StationId == "YBBB"), - Arg.Any()); + var acarsConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Empty(acarsConnection.CancelledAdscContracts); + Assert.Equal([contract], await contractRepository.All(CancellationToken.None)); + Assert.Empty(mediator.ReceivedCalls()); } [Fact] public async Task Handle_WhenContractIsInactiveAndAcarsCancelFails_RemovesContract() { - // Arrange - TestClientManager has no ACARS client for YSSY, so the cancel fails + // Arrange - TestAcarsConnectionManager has no ACARS connection for YSSY, so the cancel fails var clock = new TestClock(); var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YSSY"); + var contract = new AdscContract("UAL123", "YSSY", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(TimeSpan.FromMinutes(10)); contract.LogActivity(clock.UtcNow()); await contractRepository.Add(new AdscContractKey("UAL123", "YSSY"), contract, CancellationToken.None); var mediator = Substitute.For(); var handler = new EndExpiredAdscContractsRequestHandler( - new TestClientManager(), contractRepository, clock, mediator, Logger.None); + new TestAcarsConnectionManager(), contractRepository, Settings, clock, StartedLongAgo, mediator, new TestUnitOfWork(), Logger.None); // Act clock.SetUtcNow(clock.UtcNow() + ContractTimeout + TimeSpan.FromMinutes(1)); - await handler.Handle(new EndExpiredAdscContractsRequest(ContractTimeout), CancellationToken.None); + await handler.Handle(new EndExpiredAdscContractsRequest(), CancellationToken.None); // Assert Assert.Empty(await contractRepository.All(CancellationToken.None)); @@ -173,18 +130,18 @@ public async Task Handle_WhenContractHasRecentActivity_KeepsContract() // Arrange var clock = new TestClock(); var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB"); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(TimeSpan.FromMinutes(10)); contract.LogActivity(clock.UtcNow()); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); var mediator = Substitute.For(); var handler = new EndExpiredAdscContractsRequestHandler( - new TestClientManager(), contractRepository, clock, mediator, Logger.None); + new TestAcarsConnectionManager(), contractRepository, Settings, clock, StartedLongAgo, mediator, new TestUnitOfWork(), Logger.None); // Act clock.SetUtcNow(clock.UtcNow() + ContractTimeout - TimeSpan.FromMinutes(1)); - await handler.Handle(new EndExpiredAdscContractsRequest(ContractTimeout), CancellationToken.None); + await handler.Handle(new EndExpiredAdscContractsRequest(), CancellationToken.None); // Assert Assert.Same(contract, Assert.Single(await contractRepository.All(CancellationToken.None))); @@ -192,28 +149,28 @@ public async Task Handle_WhenContractHasRecentActivity_KeepsContract() } [Fact] - public async Task Handle_WhenSelectedContractIsInactive_CancelsInsteadOfRequestingDefault() + public async Task Handle_WhenSelectedContractIsInactive_CancelsContract() { // Arrange var clock = new TestClock(); var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB"); - contract.RequestSelectedContract(TimeSpan.FromMinutes(2), clock.UtcNow().AddMinutes(60)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); + contract.RequestSelectedContract(TimeSpan.FromMinutes(2)); contract.LogActivity(clock.UtcNow()); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); var mediator = Substitute.For(); var handler = new EndExpiredAdscContractsRequestHandler( - new TestClientManager(), contractRepository, clock, mediator, Logger.None); + new TestAcarsConnectionManager(), contractRepository, Settings, clock, StartedLongAgo, mediator, new TestUnitOfWork(), Logger.None); // Act clock.SetUtcNow(clock.UtcNow() + ContractTimeout + TimeSpan.FromMinutes(1)); - await handler.Handle(new EndExpiredAdscContractsRequest(ContractTimeout), CancellationToken.None); + await handler.Handle(new EndExpiredAdscContractsRequest(), CancellationToken.None); // Assert Assert.Empty(await contractRepository.All(CancellationToken.None)); await mediator.DidNotReceive().Send( - Arg.Any(), + Arg.Any(), Arg.Any()); } } diff --git a/source/CPDLCServer.Tests/Persistence/InMemoryAdscMessageLogRepositoryTests.cs b/source/CPDLCServer.Tests/AdscContracts/MessageLog/InMemoryAdscMessageLogRepositoryTests.cs similarity index 95% rename from source/CPDLCServer.Tests/Persistence/InMemoryAdscMessageLogRepositoryTests.cs rename to source/CPDLCServer.Tests/AdscContracts/MessageLog/InMemoryAdscMessageLogRepositoryTests.cs index 0cf7622..7ec61ef 100644 --- a/source/CPDLCServer.Tests/Persistence/InMemoryAdscMessageLogRepositoryTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/MessageLog/InMemoryAdscMessageLogRepositoryTests.cs @@ -1,7 +1,6 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts.MessageLog; -namespace CPDLCServer.Tests.Persistence; +namespace CPDLCServer.Tests.AdscContracts.MessageLog; public class InMemoryAdscMessageLogRepositoryTests { diff --git a/source/CPDLCServer.Tests/AdscContracts/PurgeExpiredAdscDataRequestHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/PurgeExpiredAdscDataRequestHandlerTests.cs new file mode 100644 index 0000000..3899b55 --- /dev/null +++ b/source/CPDLCServer.Tests/AdscContracts/PurgeExpiredAdscDataRequestHandlerTests.cs @@ -0,0 +1,45 @@ +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.MessageLog; +using CPDLCServer.Tests.Mocks; + +namespace CPDLCServer.Tests.AdscContracts; + +public class PurgeExpiredAdscDataRequestHandlerTests +{ + [Fact] + public async Task Handle_RemovesAdscMessagesOlderThan24Hours() + { + // Arrange + var clock = new TestClock(); + var adscMessageLogRepository = new TestAdscMessageLogRepository(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + var oldEntry = new AdscMessageLogEntry( + startTime, + "Hoppies/YBBB", + "YBBB", + "UAL123", + AdscMessageDirection.Uplink, + "REQUEST PERIODIC 1"); + var newEntry = new AdscMessageLogEntry( + startTime.AddHours(2), + "Hoppies/YBBB", + "YBBB", + "UAL123", + AdscMessageDirection.Uplink, + "REQUEST PERIODIC 2"); + await adscMessageLogRepository.Add(oldEntry, CancellationToken.None); + await adscMessageLogRepository.Add(newEntry, CancellationToken.None); + + var handler = new PurgeExpiredAdscDataRequestHandler(adscMessageLogRepository, clock); + + // Act - advance time beyond the purge timeout (24 hours) for the old entry only + clock.SetUtcNow(startTime.AddHours(25)); + await handler.Handle(new PurgeExpiredAdscDataRequest(), CancellationToken.None); + + // Assert + Assert.Equal([newEntry], await adscMessageLogRepository.All(CancellationToken.None)); + } +} diff --git a/source/CPDLCServer.Tests/Handlers/AdscReportReceivedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportReceivedNotificationHandlerTests.cs similarity index 83% rename from source/CPDLCServer.Tests/Handlers/AdscReportReceivedNotificationHandlerTests.cs rename to source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportReceivedNotificationHandlerTests.cs index 5b1bcfb..b65e410 100644 --- a/source/CPDLCServer.Tests/Handlers/AdscReportReceivedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportReceivedNotificationHandlerTests.cs @@ -1,14 +1,13 @@ using CPDLCServer.Contracts; -using CPDLCServer.Handlers; -using CPDLCServer.Hubs; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Controllers; +using CPDLCServer.Web; using CPDLCServer.Tests.Mocks; using Microsoft.AspNetCore.SignalR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.AdscContracts.Reports; public class AdscReportReceivedNotificationHandlerTests { @@ -18,10 +17,10 @@ public async Task Handle_NotifiesAllConnectedControllers() // Arrange var controllerRepository = new TestControllerRepository(); await controllerRepository.Add( - new ControllerInfo(Guid.NewGuid(), "ConnectionId-1", "YBBB", "BN-TSN_FSS", "1234567"), + new ControllerInfo(Guid.NewGuid(), "ConnectionId-1", "YBBB", "BN-TSN_FSS", "1234567", "Test Controller"), CancellationToken.None); await controllerRepository.Add( - new ControllerInfo(Guid.NewGuid(), "ConnectionId-2", "YMMM", "ML-ASP_CTR", "7654321"), + new ControllerInfo(Guid.NewGuid(), "ConnectionId-2", "YMMM", "ML-ASP_CTR", "1234567", "Test Controller"), CancellationToken.None); var hubContext = Substitute.For>(); @@ -29,14 +28,14 @@ await controllerRepository.Add( hubContext.Clients.Clients(Arg.Any>()).Returns(clientProxy); var handler = new AdscReportReceivedNotificationHandler( - new TestAdscReportRepository(), controllerRepository, hubContext, Logger.None); + new TestAdscReportRepository(), controllerRepository, hubContext, new TestUnitOfWork(), Logger.None); var timestamp = new DateTimeOffset(2026, 10, 13, 11, 55, 0, TimeSpan.Zero); var received = timestamp.AddSeconds(40); var notification = new AdscReportReceivedNotification( "UAL123", "YBBB", - new AdscReport(timestamp, -33.9461, 151.1772, 37000, CPDLCServer.Model.AdscReportSource.Hoppie), + new AdscReport(timestamp, -33.9461, 151.1772, 37000, CPDLCServer.AdscContracts.Reports.AdscReportSource.Hoppie), received); // Act @@ -62,12 +61,12 @@ public async Task Handle_DoesNotNotifyWhenNoControllersConnected() // Arrange var hubContext = Substitute.For>(); var handler = new AdscReportReceivedNotificationHandler( - new TestAdscReportRepository(), new TestControllerRepository(), hubContext, Logger.None); + new TestAdscReportRepository(), new TestControllerRepository(), hubContext, new TestUnitOfWork(), Logger.None); var notification = new AdscReportReceivedNotification( "UAL123", "YBBB", - new AdscReport(DateTimeOffset.UtcNow, -33.9461, 151.1772, 37000, CPDLCServer.Model.AdscReportSource.Hoppie), + new AdscReport(DateTimeOffset.UtcNow, -33.9461, 151.1772, 37000, CPDLCServer.AdscContracts.Reports.AdscReportSource.Hoppie), DateTimeOffset.UtcNow); // Act @@ -83,10 +82,10 @@ public async Task Handle_StoresReportWhenNoControllersConnected() // Arrange var reportRepository = new TestAdscReportRepository(); var handler = new AdscReportReceivedNotificationHandler( - reportRepository, new TestControllerRepository(), Substitute.For>(), Logger.None); + reportRepository, new TestControllerRepository(), Substitute.For>(), new TestUnitOfWork(), Logger.None); var timestamp = new DateTimeOffset(2026, 10, 13, 11, 55, 0, TimeSpan.Zero); - var report = new AdscReport(timestamp, -33.9461, 151.1772, 37000, CPDLCServer.Model.AdscReportSource.Hoppie); + var report = new AdscReport(timestamp, -33.9461, 151.1772, 37000, CPDLCServer.AdscContracts.Reports.AdscReportSource.Hoppie); var received = timestamp.AddSeconds(40); var notification = new AdscReportReceivedNotification("UAL123", "YBBB", report, received); @@ -96,6 +95,6 @@ public async Task Handle_StoresReportWhenNoControllersConnected() // Assert Assert.Equal( [new AircraftAdscReport("UAL123", "YBBB", report, received)], - await reportRepository.All(CancellationToken.None)); + await reportRepository.AllLatest(CancellationToken.None)); } } diff --git a/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportRepositoryTests.cs b/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportRepositoryTests.cs new file mode 100644 index 0000000..09c4e0c --- /dev/null +++ b/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportRepositoryTests.cs @@ -0,0 +1,165 @@ +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Tests.Mocks; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Tests.AdscContracts.Reports; + +public class AdscReportRepositoryTests +{ + static readonly DateTimeOffset Start = new(2026, 10, 13, 12, 0, 0, TimeSpan.Zero); + + [Fact] + public async Task Add_KeepsOneReportForEachContract() + { + // Arrange + using var database = new TestDatabase(); + var first = CreateReport("UAL123", "YBBB", 0); + var second = CreateReport("UAL123", "YBBB", 5); + var otherStation = CreateReport("UAL123", "YMMM", 0); + var otherAircraft = CreateReport("QFA1", "YBBB", 0); + + // Act + await AddAndSave(database, first, otherStation, otherAircraft); + await AddAndSave(database, second); + + // Assert + await using var dbContext = database.CreateDbContext(); + var reports = await dbContext.AdscReports.ToArrayAsync(); + Assert.Equal(3, reports.Length); + Assert.Contains(second, reports); + Assert.Contains(otherStation, reports); + Assert.Contains(otherAircraft, reports); + } + + [Fact] + public async Task Add_InSameUnitOfWork_KeepsOneReportForEachContract() + { + // Arrange + using var database = new TestDatabase(); + var first = CreateReport("UAL123", "YBBB", 0); + var second = CreateReport("UAL123", "YBBB", 5); + + // Act + await AddAndSave(database, first, second); + + // Assert + await using var dbContext = database.CreateDbContext(); + Assert.Equal([second], await dbContext.AdscReports.ToArrayAsync()); + } + + [Fact] + public async Task AllLatest_ReturnsLatestReportForEachAircraft() + { + // Arrange + using var database = new TestDatabase(); + var older = CreateReport("UAL123", "YBBB", 0); + var newer = CreateReport("UAL123", "YMMM", 5); + var other = CreateReport("QFA1", "YBBB", 0); + await AddAndSave(database, older, newer, other); + + // Act + var reports = await AllLatest(database); + + // Assert + Assert.Equal(2, reports.Length); + Assert.Contains(newer, reports); + Assert.Contains(other, reports); + } + + [Fact] + public async Task AllLatest_WhenVatsimReportIsNewerThanHoppieReport_ReturnsHoppieReport() + { + // Arrange + using var database = new TestDatabase(); + var hoppieReport = CreateReport("UAL123", "YBBB", 0); + var vatsimReport = CreateReport("UAL123", "YMMM", 5, AdscReportSource.VATSIM); + await AddAndSave(database, hoppieReport, vatsimReport); + + // Act & Assert + Assert.Equal([hoppieReport], await AllLatest(database)); + } + + [Fact] + public async Task FindLatest_ReturnsLatestReportForAircraft() + { + // Arrange + using var database = new TestDatabase(); + var report = CreateReport("UAL123", "YBBB", 0); + await AddAndSave(database, report); + + // Act & Assert + await using var dbContext = database.CreateDbContext(); + var repository = new AdscReportRepository(dbContext); + Assert.Equal(report, await repository.FindLatest("UAL123", CancellationToken.None)); + Assert.Null(await repository.FindLatest("QFA1", CancellationToken.None)); + } + + [Fact] + public async Task Find_ReturnsReportForContract() + { + // Arrange + using var database = new TestDatabase(); + var report = CreateReport("UAL123", "YBBB", 0); + await AddAndSave(database, report); + + // Act & Assert + await using var dbContext = database.CreateDbContext(); + var repository = new AdscReportRepository(dbContext); + Assert.Equal(report, await repository.Find("UAL123", "YBBB", CancellationToken.None)); + Assert.Null(await repository.Find("UAL123", "YMMM", CancellationToken.None)); + } + + [Fact] + public async Task Remove_RemovesReport() + { + // Arrange + using var database = new TestDatabase(); + var removed = CreateReport("UAL123", "YBBB", 0); + var kept = CreateReport("QFA1", "YBBB", 0); + await AddAndSave(database, removed, kept); + + // Act + await using (var dbContext = database.CreateDbContext()) + { + var repository = new AdscReportRepository(dbContext); + var report = await repository.Find("UAL123", "YBBB", CancellationToken.None); + await repository.Remove(report!, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Assert + Assert.Equal([kept], await AllLatest(database)); + } + + static async Task AddAndSave(TestDatabase database, params AircraftAdscReport[] reports) + { + await using var dbContext = database.CreateDbContext(); + var repository = new AdscReportRepository(dbContext); + + foreach (var report in reports) + await repository.Add(report, CancellationToken.None); + + await dbContext.SaveChangesAsync(); + } + + static async Task AllLatest(TestDatabase database) + { + await using var dbContext = database.CreateDbContext(); + var repository = new AdscReportRepository(dbContext); + return await repository.AllLatest(CancellationToken.None); + } + + static AircraftAdscReport CreateReport( + string callsign, + string stationId, + int minutes, + AdscReportSource source = AdscReportSource.Hoppie) + { + var timestamp = Start.AddMinutes(minutes); + return new AircraftAdscReport( + callsign, + stationId, + new AdscReport(timestamp, -33.9461, 151.1772, 37000, source), + timestamp.AddSeconds(30)); + } +} diff --git a/source/CPDLCServer.Tests/AdscContracts/Reports/ExpireAdscReportsRequestHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/Reports/ExpireAdscReportsRequestHandlerTests.cs new file mode 100644 index 0000000..d181d0b --- /dev/null +++ b/source/CPDLCServer.Tests/AdscContracts/Reports/ExpireAdscReportsRequestHandlerTests.cs @@ -0,0 +1,202 @@ +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Tests.Mocks; +using MediatR; +using NSubstitute; +using Serilog.Core; + +namespace CPDLCServer.Tests.AdscContracts.Reports; + +public class ExpireAdscReportsRequestHandlerTests +{ + static readonly TimeSpan ReportingInterval = TimeSpan.FromMinutes(10); + + // Two reporting intervals and the delivery tolerance + static readonly TimeSpan ReportExpiry = TimeSpan.FromMinutes(23); + + [Fact] + public async Task Handle_WhenLastReportIsOlderThanReportExpiry_RemovesReportAndPublishesNotification() + { + // Arrange + var clock = new TestClock(); + var contractRepository = new TestAdscContractRepository(); + var contract = await AddContract(contractRepository); + contract.RequestDefaultContract(ReportingInterval); + + var reportRepository = new TestAdscReportRepository(); + await ReceiveReport(reportRepository, contract, clock.UtcNow() - ReportExpiry - TimeSpan.FromSeconds(1)); + + var mediator = Substitute.For(); + var handler = new ExpireAdscReportsRequestHandler(reportRepository, contractRepository, clock, mediator, Logger.None); + + // Act + await handler.Handle(new ExpireAdscReportsRequest(), CancellationToken.None); + + // Assert + Assert.Empty(await reportRepository.All(CancellationToken.None)); + await mediator.Received(1).Publish( + Arg.Is(n => n.Callsign == "UAL123" && n.StationId == "YBBB"), + Arg.Any()); + } + + [Fact] + public async Task Handle_WhenLastReportIsOlderThanReportExpiry_TimesOutContractReport() + { + // Arrange + var clock = new TestClock(); + var contractRepository = new TestAdscContractRepository(); + var contract = await AddContract(contractRepository); + contract.RequestDefaultContract(ReportingInterval); + + var reportRepository = new TestAdscReportRepository(); + var report = await ReceiveReport(reportRepository, contract, clock.UtcNow() - ReportExpiry - TimeSpan.FromSeconds(1)); + + var handler = new ExpireAdscReportsRequestHandler(reportRepository, contractRepository, clock, Substitute.For(), Logger.None); + + // Act + await handler.Handle(new ExpireAdscReportsRequest(), CancellationToken.None); + + // Assert + Assert.Null(contract.ReportingSource); + Assert.Equal(report.Report.Timestamp, contract.LastReportReceived); + } + + [Fact] + public async Task Handle_WhenLastReportIsNotOlderThanReportExpiry_KeepsReport() + { + // Arrange + var clock = new TestClock(); + var contractRepository = new TestAdscContractRepository(); + var contract = await AddContract(contractRepository); + contract.RequestDefaultContract(ReportingInterval); + + var reportRepository = new TestAdscReportRepository(); + var report = await ReceiveReport(reportRepository, contract, clock.UtcNow() - ReportExpiry); + + var mediator = Substitute.For(); + var handler = new ExpireAdscReportsRequestHandler(reportRepository, contractRepository, clock, mediator, Logger.None); + + // Act + await handler.Handle(new ExpireAdscReportsRequest(), CancellationToken.None); + + // Assert + Assert.Equal([report], await reportRepository.All(CancellationToken.None)); + await mediator.DidNotReceive().Publish(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task Handle_WhenSelectedContractHasShorterInterval_UsesSelectedInterval() + { + // Arrange + var clock = new TestClock(); + var contractRepository = new TestAdscContractRepository(); + var contract = await AddContract(contractRepository); + contract.RequestDefaultContract(ReportingInterval); + contract.RequestSelectedContract(TimeSpan.FromMinutes(2)); + + // Two selected intervals and the delivery tolerance is 7 minutes + var reportRepository = new TestAdscReportRepository(); + await ReceiveReport(reportRepository, contract, clock.UtcNow() - TimeSpan.FromMinutes(7) - TimeSpan.FromSeconds(1)); + + var handler = new ExpireAdscReportsRequestHandler(reportRepository, contractRepository, clock, Substitute.For(), Logger.None); + + // Act + await handler.Handle(new ExpireAdscReportsRequest(), CancellationToken.None); + + // Assert + Assert.Empty(await reportRepository.All(CancellationToken.None)); + } + + [Fact] + public async Task Handle_WhenContractHasOnlyDemandRequest_UsesDefaultInterval() + { + // Arrange + var clock = new TestClock(); + var contractRepository = new TestAdscContractRepository(); + var contract = await AddContract(contractRepository); + contract.RequestDemandReport(); + + var reportRepository = new TestAdscReportRepository(); + var report = await ReceiveReport(reportRepository, contract, clock.UtcNow() - ReportExpiry); + + var handler = new ExpireAdscReportsRequestHandler(reportRepository, contractRepository, clock, Substitute.For(), Logger.None); + + // Act + await handler.Handle(new ExpireAdscReportsRequest(), CancellationToken.None); + + // Assert + Assert.Equal([report], await reportRepository.All(CancellationToken.None)); + } + + [Fact] + public async Task Handle_WhenContractHasNoLastReport_RemovesReport() + { + // Arrange + var clock = new TestClock(); + var contractRepository = new TestAdscContractRepository(); + var contract = await AddContract(contractRepository); + contract.RequestDefaultContract(ReportingInterval); + + var reportRepository = new TestAdscReportRepository(); + await AddReport(reportRepository, clock.UtcNow()); + + var handler = new ExpireAdscReportsRequestHandler(reportRepository, contractRepository, clock, Substitute.For(), Logger.None); + + // Act + await handler.Handle(new ExpireAdscReportsRequest(), CancellationToken.None); + + // Assert + Assert.Empty(await reportRepository.All(CancellationToken.None)); + } + + [Fact] + public async Task Handle_WhenReportHasNoContract_RemovesReportAndPublishesNotification() + { + // Arrange + var clock = new TestClock(); + var reportRepository = new TestAdscReportRepository(); + await AddReport(reportRepository, clock.UtcNow()); + + var mediator = Substitute.For(); + var handler = new ExpireAdscReportsRequestHandler( + reportRepository, new TestAdscContractRepository(), clock, mediator, Logger.None); + + // Act + await handler.Handle(new ExpireAdscReportsRequest(), CancellationToken.None); + + // Assert + Assert.Empty(await reportRepository.All(CancellationToken.None)); + await mediator.Received(1).Publish( + Arg.Is(n => n.Callsign == "UAL123" && n.StationId == "YBBB"), + Arg.Any()); + } + + static async Task AddContract(TestAdscContractRepository contractRepository) + { + var contract = new AdscContract("UAL123", "YBBB", ReportingInterval, DateTimeOffset.MinValue); + await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); + return contract; + } + + // Adds the report to the repository and gives it to the contract, as the server does when a report arrives + static async Task ReceiveReport( + TestAdscReportRepository reportRepository, + AdscContract contract, + DateTimeOffset timestamp) + { + var report = await AddReport(reportRepository, timestamp); + contract.ReportReceived(report.Report); + return report; + } + + static async Task AddReport(TestAdscReportRepository reportRepository, DateTimeOffset timestamp) + { + var report = new AircraftAdscReport( + "UAL123", + "YBBB", + new AdscReport(timestamp, -33.9461, 151.1772, 37000, AdscReportSource.Hoppie), + timestamp); + await reportRepository.Add(report, CancellationToken.None); + return report; + } +} diff --git a/source/CPDLCServer.Tests/Handlers/RequestAdscDemandReportCommandHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/Reports/RequestAdscDemandReportCommandHandlerTests.cs similarity index 69% rename from source/CPDLCServer.Tests/Handlers/RequestAdscDemandReportCommandHandlerTests.cs rename to source/CPDLCServer.Tests/AdscContracts/Reports/RequestAdscDemandReportCommandHandlerTests.cs index 42b02c8..a0c131a 100644 --- a/source/CPDLCServer.Tests/Handlers/RequestAdscDemandReportCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/Reports/RequestAdscDemandReportCommandHandlerTests.cs @@ -1,31 +1,31 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.AdscContracts.Reports; public class RequestAdscDemandReportCommandHandlerTests { + static readonly AdscReport Report = new(DateTimeOffset.UtcNow, -33.9461, 151.1772, 37000, AdscReportSource.Hoppie); + [Fact] - public async Task Handle_SendsRequestViaAcarsClientForStation() + public async Task Handle_SendsRequestViaAcarsConnectionForStation() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var handler = new RequestAdscDemandReportCommandHandler( - clientManager, new TestAdscContractRepository(), Substitute.For(), new TestClock(), Logger.None); + acarsConnectionManager, new TestAdscContractRepository(), Substitute.For(), new TestClock(), new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new RequestAdscDemandReportCommand("YBBB", "UAL123"), CancellationToken.None); // Assert - var client = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Equal("UAL123", Assert.Single(client.RequestedAdscDemandReports)); - Assert.Empty(client.RequestedAdscContracts); + var acarsConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Equal("UAL123", Assert.Single(acarsConnection.RequestedAdscDemandReports)); + Assert.Empty(acarsConnection.RequestedAdscContracts); } [Fact] @@ -35,7 +35,7 @@ public async Task Handle_WhenNoContractExists_AddsContractWithOnlyDemandReport() var contractRepository = new TestAdscContractRepository(); var mediator = Substitute.For(); var handler = new RequestAdscDemandReportCommandHandler( - new TestClientManager(), contractRepository, mediator, new TestClock(), Logger.None); + new TestAcarsConnectionManager(), contractRepository, mediator, new TestClock(), new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new RequestAdscDemandReportCommand("YBBB", "UAL123"), CancellationToken.None); @@ -58,14 +58,14 @@ public async Task Handle_WhenPeriodicContractExists_KeepsPeriodicContractAndSend { // Arrange var contractRepository = new TestAdscContractRepository(); - var existingContract = new AdscContract("UAL123", "YBBB"); + var existingContract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); existingContract.RequestDefaultContract(TimeSpan.FromMinutes(10)); - existingContract.ReportReceived(); + existingContract.ReportReceived(Report); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), existingContract, CancellationToken.None); var mediator = Substitute.For(); var handler = new RequestAdscDemandReportCommandHandler( - new TestClientManager(), contractRepository, mediator, new TestClock(), Logger.None); + new TestAcarsConnectionManager(), contractRepository, mediator, new TestClock(), new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new RequestAdscDemandReportCommand("YBBB", "UAL123"), CancellationToken.None); diff --git a/source/CPDLCServer.Tests/Handlers/RequestAdscContractOnConnectionEstablishedHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/RequestAdscContractOnConnectionEstablishedHandlerTests.cs similarity index 71% rename from source/CPDLCServer.Tests/Handlers/RequestAdscContractOnConnectionEstablishedHandlerTests.cs rename to source/CPDLCServer.Tests/AdscContracts/RequestAdscContractOnConnectionEstablishedHandlerTests.cs index 11faa3c..5d11bdd 100644 --- a/source/CPDLCServer.Tests/Handlers/RequestAdscContractOnConnectionEstablishedHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/RequestAdscContractOnConnectionEstablishedHandlerTests.cs @@ -1,13 +1,11 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts; +using CPDLCServer.Cpdlc.Connections; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.AdscContracts; public class RequestAdscContractOnConnectionEstablishedHandlerTests { @@ -17,7 +15,7 @@ public async Task Handle_RequestsDefaultContract() // Arrange var mediator = Substitute.For(); var handler = new RequestAdscContractOnConnectionEstablishedHandler( - new TestAdscContractRepository(), mediator, Logger.None); + new TestAcarsConnectionManager(), new TestAdscContractRepository(), mediator, Logger.None); var notification = new AircraftConnectionEstablished( "hoppies-ymmm", "YMMM", "UAL123", DataAuthorityState.NextDataAuthority); @@ -27,7 +25,7 @@ public async Task Handle_RequestsDefaultContract() // Assert await mediator.Received(1).Send( - Arg.Is(c => c.StationId == "YMMM" && c.Callsign == "UAL123"), + Arg.Is(c => c.StationId == "YMMM" && c.Callsign == "UAL123" && c.ReportingInterval == TimeSpan.FromMinutes(20)), Arg.Any()); } @@ -36,12 +34,12 @@ public async Task Handle_WhenSelectedContractExists_DoesNotRequestContract() { // Arrange var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB"); - contract.RequestSelectedContract(TimeSpan.FromMinutes(5), DateTimeOffset.UtcNow.AddHours(1)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); + contract.RequestSelectedContract(TimeSpan.FromMinutes(5)); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); var mediator = Substitute.For(); - var handler = new RequestAdscContractOnConnectionEstablishedHandler(contractRepository, mediator, Logger.None); + var handler = new RequestAdscContractOnConnectionEstablishedHandler(new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); var notification = new AircraftConnectionEstablished( "hoppies-ybbb", "YBBB", "UAL123", DataAuthorityState.NextDataAuthority); @@ -58,12 +56,12 @@ public async Task Handle_WhenOnlyDemandReportExists_RequestsDefaultContract() { // Arrange var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB"); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDemandReport(); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); var mediator = Substitute.For(); - var handler = new RequestAdscContractOnConnectionEstablishedHandler(contractRepository, mediator, Logger.None); + var handler = new RequestAdscContractOnConnectionEstablishedHandler(new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); var notification = new AircraftConnectionEstablished( "hoppies-ybbb", "YBBB", "UAL123", DataAuthorityState.NextDataAuthority); @@ -73,7 +71,7 @@ public async Task Handle_WhenOnlyDemandReportExists_RequestsDefaultContract() // Assert await mediator.Received(1).Send( - Arg.Is(c => c.StationId == "YBBB" && c.Callsign == "UAL123"), + Arg.Is(c => c.StationId == "YBBB" && c.Callsign == "UAL123" && c.ReportingInterval == TimeSpan.FromMinutes(10)), Arg.Any()); } @@ -82,13 +80,13 @@ public async Task Handle_WhenDefaultContractIsRejected_RequestsDefaultContract() { // Arrange var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB"); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(TimeSpan.FromMinutes(10)); contract.Reject(); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); var mediator = Substitute.For(); - var handler = new RequestAdscContractOnConnectionEstablishedHandler(contractRepository, mediator, Logger.None); + var handler = new RequestAdscContractOnConnectionEstablishedHandler(new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); var notification = new AircraftConnectionEstablished( "hoppies-ybbb", "YBBB", "UAL123", DataAuthorityState.NextDataAuthority); @@ -98,7 +96,7 @@ public async Task Handle_WhenDefaultContractIsRejected_RequestsDefaultContract() // Assert await mediator.Received(1).Send( - Arg.Is(c => c.StationId == "YBBB" && c.Callsign == "UAL123"), + Arg.Is(c => c.StationId == "YBBB" && c.Callsign == "UAL123" && c.ReportingInterval == TimeSpan.FromMinutes(10)), Arg.Any()); } @@ -108,11 +106,11 @@ public async Task Handle_WhenRequestFails_DoesNotThrow() // Arrange var mediator = Substitute.For(); mediator - .Send(Arg.Any(), Arg.Any()) + .Send(Arg.Any(), Arg.Any()) .Returns(Task.FromException(new HttpRequestException("Hoppie is down"))); var handler = new RequestAdscContractOnConnectionEstablishedHandler( - new TestAdscContractRepository(), mediator, Logger.None); + new TestAcarsConnectionManager(), new TestAdscContractRepository(), mediator, Logger.None); var notification = new AircraftConnectionEstablished( "hoppies-ybbb", "YBBB", "UAL123", DataAuthorityState.NextDataAuthority); diff --git a/source/CPDLCServer.Tests/AdscContracts/RequestPeriodicAdscContractCommandHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/RequestPeriodicAdscContractCommandHandlerTests.cs new file mode 100644 index 0000000..041fd29 --- /dev/null +++ b/source/CPDLCServer.Tests/AdscContracts/RequestPeriodicAdscContractCommandHandlerTests.cs @@ -0,0 +1,212 @@ +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Tests.Mocks; +using MediatR; +using NSubstitute; +using Serilog.Core; + +namespace CPDLCServer.Tests.AdscContracts; + +public class RequestPeriodicAdscContractCommandHandlerTests +{ + static readonly AdscReport Report = new(DateTimeOffset.UtcNow, -33.9461, 151.1772, 37000, AdscReportSource.Hoppie); + + [Fact] + public async Task Handle_SendsDefaultIntervalViaAcarsConnectionForStation() + { + // Arrange + var acarsConnectionManager = new TestAcarsConnectionManager(); + var handler = new RequestPeriodicAdscContractCommandHandler( + acarsConnectionManager, new TestAdscContractRepository(), Substitute.For(), new TestClock(), new TestUnitOfWork(), Logger.None); + + // Act + await handler.Handle(new RequestPeriodicAdscContractCommand("YMMM", "UAL123", TimeSpan.FromMinutes(20)), CancellationToken.None); + + // Assert - TestAcarsConnectionManager sets the YMMM default to 20 minutes + var ybbbConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + var ymmmConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ymmm", CancellationToken.None); + Assert.Equal(TimeSpan.FromMinutes(20), ymmmConnection.RequestedAdscContracts["UAL123"]); + Assert.Empty(ybbbConnection.RequestedAdscContracts); + } + + [Fact] + public async Task Handle_WithDefaultInterval_WhenNoContractExists_AddsDefaultContract() + { + // Arrange + var contractRepository = new TestAdscContractRepository(); + var mediator = Substitute.For(); + var handler = new RequestPeriodicAdscContractCommandHandler( + new TestAcarsConnectionManager(), contractRepository, mediator, new TestClock(), new TestUnitOfWork(), Logger.None); + + // Act + await handler.Handle(new RequestPeriodicAdscContractCommand("YBBB", "UAL123", TimeSpan.FromMinutes(10)), CancellationToken.None); + + // Assert - TestAcarsConnectionManager sets the YBBB default to 10 minutes + var contract = await contractRepository.Find(new AdscContractKey("UAL123", "YBBB"), CancellationToken.None); + Assert.NotNull(contract); + Assert.Equal(TimeSpan.FromMinutes(10), contract.ReportingInterval); + Assert.Equal(AdscContractState.Sent, contract.DefaultContractState); + Assert.Null(contract.SelectedContractState); + + await mediator.Received(1).Publish( + Arg.Is(n => n.Contract == contract), + Arg.Any()); + } + + [Fact] + public async Task Handle_LogsActivity() + { + // Arrange + var clock = new TestClock(); + var contractRepository = new TestAdscContractRepository(); + var handler = new RequestPeriodicAdscContractCommandHandler( + new TestAcarsConnectionManager(), contractRepository, Substitute.For(), clock, new TestUnitOfWork(), Logger.None); + + // Act + await handler.Handle(new RequestPeriodicAdscContractCommand("YBBB", "UAL123", TimeSpan.FromMinutes(10)), CancellationToken.None); + + // Assert + var contract = await contractRepository.Find(new AdscContractKey("UAL123", "YBBB"), CancellationToken.None); + Assert.NotNull(contract); + Assert.Equal(clock.UtcNow(), contract.LastActivity); + } + + [Fact] + public async Task Handle_WithDefaultInterval_WhenSelectedContractIsInUse_EndsSelectedContract() + { + // Arrange + var contractRepository = new TestAdscContractRepository(); + var existingContract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); + existingContract.RequestSelectedContract(TimeSpan.FromMinutes(2)); + existingContract.ReportReceived(Report); + await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), existingContract, CancellationToken.None); + + var handler = new RequestPeriodicAdscContractCommandHandler( + new TestAcarsConnectionManager(), contractRepository, Substitute.For(), new TestClock(), new TestUnitOfWork(), Logger.None); + + // Act + await handler.Handle(new RequestPeriodicAdscContractCommand("YBBB", "UAL123", TimeSpan.FromMinutes(10)), CancellationToken.None); + + // Assert + var contract = Assert.Single(await contractRepository.All(CancellationToken.None)); + Assert.Same(existingContract, contract); + Assert.Equal(TimeSpan.FromMinutes(10), contract.ReportingInterval); + Assert.Equal(AdscContractState.Sent, contract.DefaultContractState); + Assert.Null(contract.SelectedContractState); + } + + [Fact] + public async Task Handle_WithOtherInterval_SendsRequestViaAcarsConnectionForStation() + { + // Arrange + var acarsConnectionManager = new TestAcarsConnectionManager(); + var handler = new RequestPeriodicAdscContractCommandHandler( + acarsConnectionManager, new TestAdscContractRepository(), Substitute.For(), new TestClock(), new TestUnitOfWork(), Logger.None); + + var command = new RequestPeriodicAdscContractCommand("YBBB", "UAL123", TimeSpan.FromMinutes(5)); + + // Act + await handler.Handle(command, CancellationToken.None); + + // Assert + var ybbbConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + var ymmmConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ymmm", CancellationToken.None); + Assert.Equal(TimeSpan.FromMinutes(5), ybbbConnection.RequestedAdscContracts["UAL123"]); + Assert.Empty(ymmmConnection.RequestedAdscContracts); + } + + [Fact] + public async Task Handle_WithOtherInterval_WhenNoContractExists_AddsSelectedContract() + { + // Arrange + var clock = new TestClock(); + var contractRepository = new TestAdscContractRepository(); + var mediator = Substitute.For(); + var handler = new RequestPeriodicAdscContractCommandHandler( + new TestAcarsConnectionManager(), contractRepository, mediator, clock, new TestUnitOfWork(), Logger.None); + + var command = new RequestPeriodicAdscContractCommand("YBBB", "UAL123", TimeSpan.FromMinutes(5)); + + // Act + await handler.Handle(command, CancellationToken.None); + + // Assert + var contract = await contractRepository.Find(new AdscContractKey("UAL123", "YBBB"), CancellationToken.None); + Assert.NotNull(contract); + Assert.Equal(TimeSpan.FromMinutes(5), contract.ReportingInterval); + Assert.Equal(TimeSpan.FromMinutes(5), contract.SelectedReportingInterval); + Assert.Equal(AdscContractState.Sent, contract.SelectedContractState); + Assert.Null(contract.DefaultContractState); + Assert.Equal(TimeSpan.FromMinutes(10), contract.DefaultReportingInterval); + + await mediator.Received(1).Publish( + Arg.Is(n => n.Contract == contract), + Arg.Any()); + } + + [Fact] + public async Task Handle_WhenDefaultContractExists_KeepsDefaultContractUntilAccepted() + { + // Arrange + var contractRepository = new TestAdscContractRepository(); + var existingContract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); + existingContract.RequestDefaultContract(TimeSpan.FromMinutes(10)); + existingContract.ReportReceived(Report); + await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), existingContract, CancellationToken.None); + + var handler = new RequestPeriodicAdscContractCommandHandler( + new TestAcarsConnectionManager(), contractRepository, Substitute.For(), new TestClock(), new TestUnitOfWork(), Logger.None); + + var command = new RequestPeriodicAdscContractCommand("YBBB", "UAL123", TimeSpan.FromMinutes(2)); + + // Act + await handler.Handle(command, CancellationToken.None); + + // Assert + var contract = Assert.Single(await contractRepository.All(CancellationToken.None)); + Assert.Same(existingContract, contract); + Assert.Equal(TimeSpan.FromMinutes(2), contract.ReportingInterval); + Assert.Equal(AdscContractState.Sent, contract.SelectedContractState); + Assert.Equal(AdscContractState.Accepted, contract.DefaultContractState); + } + + [Fact] + public async Task Handle_WhenIntervalIsLessThanMinimum_ThrowsAndSendsNothing() + { + // Arrange + var acarsConnectionManager = new TestAcarsConnectionManager(); + var contractRepository = new TestAdscContractRepository(); + var handler = new RequestPeriodicAdscContractCommandHandler( + acarsConnectionManager, contractRepository, Substitute.For(), new TestClock(), new TestUnitOfWork(), Logger.None); + + var command = new RequestPeriodicAdscContractCommand("YBBB", "UAL123", TimeSpan.FromSeconds(59)); + + // Act & Assert + await Assert.ThrowsAsync(() => handler.Handle(command, CancellationToken.None)); + + var acarsConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Empty(acarsConnection.RequestedAdscContracts); + Assert.Empty(await contractRepository.All(CancellationToken.None)); + } + + [Fact] + public async Task Handle_WhenIntervalIsMinimum_SendsRequest() + { + // Arrange + var acarsConnectionManager = new TestAcarsConnectionManager(); + var handler = new RequestPeriodicAdscContractCommandHandler( + acarsConnectionManager, new TestAdscContractRepository(), Substitute.For(), new TestClock(), new TestUnitOfWork(), Logger.None); + + var command = new RequestPeriodicAdscContractCommand( + "YBBB", + "UAL123", + AdscContract.MinimumReportingInterval); + + // Act + await handler.Handle(command, CancellationToken.None); + + // Assert + var acarsConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Single(acarsConnection.RequestedAdscContracts); + } +} diff --git a/source/CPDLCServer.Tests/Auth/Administrators/AdministratorCommandHandlerTests.cs b/source/CPDLCServer.Tests/Auth/Administrators/AdministratorCommandHandlerTests.cs new file mode 100644 index 0000000..7a1b42b --- /dev/null +++ b/source/CPDLCServer.Tests/Auth/Administrators/AdministratorCommandHandlerTests.cs @@ -0,0 +1,95 @@ +using CPDLCServer.Auth.Administrators; +using CPDLCServer.Tests.Mocks; +using Serilog.Core; + +namespace CPDLCServer.Tests.Auth.Administrators; + +public class AdministratorCommandHandlerTests +{ + readonly TestAdministratorRepository _administratorRepository = new(); + readonly TestClock _clock = new(); + + [Fact] + public async Task Add_AddsTheAdministrator() + { + // Arrange + var handler = new AddAdministratorCommandHandler(_administratorRepository, _clock, new TestUnitOfWork(), Logger.None); + + // Act + await handler.Handle(new AddAdministratorCommand("1234567"), CancellationToken.None); + + // Assert + var administrator = await _administratorRepository.FindByCid("1234567", CancellationToken.None); + Assert.NotNull(administrator); + Assert.Null(administrator.Name); + Assert.Equal(_clock.UtcNow(), administrator.Added); + } + + [Fact] + public async Task Add_WhenAlreadyAdministrator_Throws() + { + // Arrange + await _administratorRepository.Add(new Administrator { Cid = "1234567" }, CancellationToken.None); + var handler = new AddAdministratorCommandHandler(_administratorRepository, _clock, new TestUnitOfWork(), Logger.None); + + // Act & Assert + await Assert.ThrowsAsync(() => + handler.Handle(new AddAdministratorCommand("1234567"), CancellationToken.None)); + } + + [Fact] + public async Task Remove_RemovesTheAdministrator() + { + // Arrange + await _administratorRepository.Add(new Administrator { Cid = "1111111" }, CancellationToken.None); + await _administratorRepository.Add(new Administrator { Cid = "2222222" }, CancellationToken.None); + var handler = new RemoveAdministratorCommandHandler(_administratorRepository, new TestUnitOfWork(), Logger.None); + + // Act + await handler.Handle(new RemoveAdministratorCommand("2222222", CurrentUserCid: "1111111"), CancellationToken.None); + + // Assert + Assert.Null(await _administratorRepository.FindByCid("2222222", CancellationToken.None)); + } + + [Fact] + public async Task Remove_Yourself_Throws() + { + // Arrange + await _administratorRepository.Add(new Administrator { Cid = "1111111" }, CancellationToken.None); + await _administratorRepository.Add(new Administrator { Cid = "2222222" }, CancellationToken.None); + var handler = new RemoveAdministratorCommandHandler(_administratorRepository, new TestUnitOfWork(), Logger.None); + + // Act & Assert + await Assert.ThrowsAsync(() => + handler.Handle(new RemoveAdministratorCommand("1111111", CurrentUserCid: "1111111"), CancellationToken.None)); + Assert.NotNull(await _administratorRepository.FindByCid("1111111", CancellationToken.None)); + } + + [Fact] + public async Task Remove_LastAdministrator_Throws() + { + // Arrange + await _administratorRepository.Add(new Administrator { Cid = "1111111" }, CancellationToken.None); + var handler = new RemoveAdministratorCommandHandler(_administratorRepository, new TestUnitOfWork(), Logger.None); + + // Act & Assert + await Assert.ThrowsAsync(() => + handler.Handle(new RemoveAdministratorCommand("1111111", CurrentUserCid: "9999999"), CancellationToken.None)); + } + + [Fact] + public async Task UpdateName_ChangesTheNameOfAnAdministrator() + { + // Arrange + await _administratorRepository.Add(new Administrator { Cid = "1234567" }, CancellationToken.None); + var handler = new UpdateAdministratorNameCommandHandler(_administratorRepository); + + // Act + await handler.Handle(new UpdateAdministratorNameCommand("1234567", "Test Controller"), CancellationToken.None); + + // Assert + var administrator = await _administratorRepository.FindByCid("1234567", CancellationToken.None); + Assert.Equal("Test Controller", administrator!.Name); + } +} diff --git a/source/CPDLCServer.Tests/Auth/PluginTokens/PluginAuthorizationCodesTests.cs b/source/CPDLCServer.Tests/Auth/PluginTokens/PluginAuthorizationCodesTests.cs new file mode 100644 index 0000000..0337d4b --- /dev/null +++ b/source/CPDLCServer.Tests/Auth/PluginTokens/PluginAuthorizationCodesTests.cs @@ -0,0 +1,109 @@ +using CPDLCServer.Auth.PluginTokens; +using CPDLCServer.Tests.Mocks; + +namespace CPDLCServer.Tests.Auth.PluginTokens; + +public class PluginAuthorizationCodesTests +{ + const string RedirectUri = "http://127.0.0.1:50000/callback"; + const string CodeVerifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; + + readonly TestClock _clock = new(); + + [Fact] + public void ComputeChallenge_MatchesTheExampleOfRfc7636() + { + // Act + var challenge = PluginAuthorizationCodes.ComputeChallenge(CodeVerifier); + + // Assert + Assert.Equal("E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", challenge); + } + + [Fact] + public void Redeem_WithTheVerifier_ReturnsTheUser() + { + // Arrange + var codes = new PluginAuthorizationCodes(_clock); + var code = codes.Create("1234567", "Test Controller", RedirectUri, PluginAuthorizationCodes.ComputeChallenge(CodeVerifier)); + + // Act + var user = codes.Redeem(code, RedirectUri, CodeVerifier); + + // Assert + Assert.Equal(new PluginUser("1234567", "Test Controller"), user); + } + + [Fact] + public void Redeem_WithAWrongVerifier_ReturnsNull() + { + // Arrange + var codes = new PluginAuthorizationCodes(_clock); + var code = codes.Create("1234567", "Test Controller", RedirectUri, PluginAuthorizationCodes.ComputeChallenge(CodeVerifier)); + + // Act + var user = codes.Redeem(code, RedirectUri, "wrong-verifier"); + + // Assert + Assert.Null(user); + } + + [Fact] + public void Redeem_WithADifferentRedirectUri_ReturnsNull() + { + // Arrange + var codes = new PluginAuthorizationCodes(_clock); + var code = codes.Create("1234567", "Test Controller", RedirectUri, PluginAuthorizationCodes.ComputeChallenge(CodeVerifier)); + + // Act + var user = codes.Redeem(code, "http://127.0.0.1:50001/callback", CodeVerifier); + + // Assert + Assert.Null(user); + } + + [Fact] + public void Redeem_AfterTheCodeExpires_ReturnsNull() + { + // Arrange + var codes = new PluginAuthorizationCodes(_clock); + var code = codes.Create("1234567", "Test Controller", RedirectUri, PluginAuthorizationCodes.ComputeChallenge(CodeVerifier)); + _clock.SetUtcNow(_clock.UtcNow() + PluginAuthorizationCodes.CodeLifetime); + + // Act + var user = codes.Redeem(code, RedirectUri, CodeVerifier); + + // Assert + Assert.Null(user); + } + + [Fact] + public void Redeem_TwoTimes_ReturnsNullTheSecondTime() + { + // Arrange + var codes = new PluginAuthorizationCodes(_clock); + var code = codes.Create("1234567", "Test Controller", RedirectUri, PluginAuthorizationCodes.ComputeChallenge(CodeVerifier)); + codes.Redeem(code, RedirectUri, CodeVerifier); + + // Act + var user = codes.Redeem(code, RedirectUri, CodeVerifier); + + // Assert + Assert.Null(user); + } + + [Fact] + public void Redeem_AfterAFailedCheck_ReturnsNull() + { + // Arrange + var codes = new PluginAuthorizationCodes(_clock); + var code = codes.Create("1234567", "Test Controller", RedirectUri, PluginAuthorizationCodes.ComputeChallenge(CodeVerifier)); + codes.Redeem(code, RedirectUri, "wrong-verifier"); + + // Act + var user = codes.Redeem(code, RedirectUri, CodeVerifier); + + // Assert + Assert.Null(user); + } +} diff --git a/source/CPDLCServer.Tests/Auth/PluginTokens/PluginRedirectUriTests.cs b/source/CPDLCServer.Tests/Auth/PluginTokens/PluginRedirectUriTests.cs new file mode 100644 index 0000000..34378e8 --- /dev/null +++ b/source/CPDLCServer.Tests/Auth/PluginTokens/PluginRedirectUriTests.cs @@ -0,0 +1,23 @@ +using CPDLCServer.Auth.PluginTokens; + +namespace CPDLCServer.Tests.Auth.PluginTokens; + +public class PluginRedirectUriTests +{ + [Theory] + [InlineData("http://127.0.0.1:50000/callback", true)] + [InlineData("http://localhost:50000/callback", true)] + [InlineData("https://127.0.0.1:50000/callback", false)] + [InlineData("http://127.0.0.1/callback", false)] + [InlineData("http://example.com:50000/callback", false)] + [InlineData("http://127.0.0.1.example.com:50000/callback", false)] + [InlineData("http://127.0.0.1:50000/callback?next=http://example.com", false)] + [InlineData("http://user@127.0.0.1:50000/callback", false)] + [InlineData("not a URL", false)] + [InlineData(null, false)] + public void IsValid_AcceptsOnlyAPortOnThisComputer(string? redirectUri, bool expected) + { + // Act & Assert + Assert.Equal(expected, PluginRedirectUri.IsValid(redirectUri)); + } +} diff --git a/source/CPDLCServer.Tests/Handlers/AircraftConnectionEstablishedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandlerTests.cs similarity index 86% rename from source/CPDLCServer.Tests/Handlers/AircraftConnectionEstablishedNotificationHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandlerTests.cs index 6031413..974a8d8 100644 --- a/source/CPDLCServer.Tests/Handlers/AircraftConnectionEstablishedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandlerTests.cs @@ -1,14 +1,13 @@ using CPDLCServer.Contracts; -using CPDLCServer.Handlers; -using CPDLCServer.Hubs; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Web; using CPDLCServer.Tests.Mocks; using Microsoft.AspNetCore.SignalR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class AircraftConnectionEstablishedNotificationHandlerTests { @@ -22,13 +21,15 @@ public async Task Handle_NotifiesAllConnectedControllers() "ConnectionId-1", "YBBB", "BN-TSN_FSS", - "1234567"); + "1234567", + "Test Controller"); var controller2 = new ControllerInfo( Guid.NewGuid(), "ConnectionId-2", "YBBB", "BN-OCN_CTR", - "7654321"); + "1234567", + "Test Controller"); await controllerManager.Add(controller1, CancellationToken.None); await controllerManager.Add(controller2, CancellationToken.None); @@ -39,13 +40,13 @@ public async Task Handle_NotifiesAllConnectedControllers() var handler = new AircraftConnectionEstablishedNotificationHandler( controllerManager, hubContext, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionEstablished( "hoppies-ybbb", "YBBB", "UAL123", - CPDLCServer.Model.DataAuthorityState.NextDataAuthority); + CPDLCServer.Cpdlc.Connections.DataAuthorityState.NextDataAuthority); // Act await handler.Handle(notification, CancellationToken.None); @@ -78,13 +79,13 @@ public async Task Handle_DoesNotNotifyWhenNoControllersConnected() var handler = new AircraftConnectionEstablishedNotificationHandler( controllerManager, hubContext, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionEstablished( "hoppies-ybbb", "YBBB", "UAL123", - CPDLCServer.Model.DataAuthorityState.NextDataAuthority); + CPDLCServer.Cpdlc.Connections.DataAuthorityState.NextDataAuthority); // Act await handler.Handle(notification, CancellationToken.None); diff --git a/source/CPDLCServer.Tests/Handlers/AircraftConnectionLostNotificationHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionLostNotificationHandlerTests.cs similarity index 81% rename from source/CPDLCServer.Tests/Handlers/AircraftConnectionLostNotificationHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionLostNotificationHandlerTests.cs index d17bc96..30df636 100644 --- a/source/CPDLCServer.Tests/Handlers/AircraftConnectionLostNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionLostNotificationHandlerTests.cs @@ -1,13 +1,15 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Hubs; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Web; using CPDLCServer.Tests.Mocks; using Microsoft.AspNetCore.SignalR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class AircraftConnectionLostNotificationHandlerTests { @@ -19,7 +21,7 @@ public async Task Handle_RemovesAircraftFromTracking() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(DateTimeOffset.UtcNow); aircraft.AcceptLogon(DateTimeOffset.UtcNow); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -38,7 +40,7 @@ public async Task Handle_RemovesAircraftFromTracking() messageIdProvider, publisher, clock, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionLost("hoppies-ybbb", "UAL123"); @@ -60,7 +62,7 @@ public async Task Handle_CreatesDialogueWithErrorMessageAndNotifiesControllers() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(DateTimeOffset.UtcNow); aircraft.AcceptLogon(DateTimeOffset.UtcNow); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var controller1 = new ControllerInfo( @@ -68,13 +70,15 @@ public async Task Handle_CreatesDialogueWithErrorMessageAndNotifiesControllers() "ConnectionId-1", "YBBB", "BN-TSN_FSS", - "1234567"); + "1234567", + "Test Controller"); var controller2 = new ControllerInfo( Guid.NewGuid(), "ConnectionId-2", "YBBB", "BN-OCN_CTR", - "7654321"); + "1234567", + "Test Controller"); await controllerManager.Add(controller1, CancellationToken.None); await controllerManager.Add(controller2, CancellationToken.None); @@ -94,7 +98,7 @@ public async Task Handle_CreatesDialogueWithErrorMessageAndNotifiesControllers() messageIdProvider, publisher, clock, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionLost("hoppies-ybbb", "UAL123"); @@ -147,7 +151,7 @@ public async Task Handle_DoesNotThrowWhenAircraftNotFound() messageIdProvider, publisher, clock, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionLost("hoppies-ybbb", "UAL123"); @@ -166,7 +170,7 @@ public async Task Handle_DoesNotNotifyWhenNoControllersConnected() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(DateTimeOffset.UtcNow); aircraft.AcceptLogon(DateTimeOffset.UtcNow); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -185,7 +189,7 @@ public async Task Handle_DoesNotNotifyWhenNoControllersConnected() messageIdProvider, publisher, clock, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionLost("hoppies-ybbb", "UAL123"); @@ -203,6 +207,42 @@ await clientProxy.DidNotReceive().SendCoreAsync( Arg.Any()); } + [Fact] + public async Task Handle_ClosesOpenDialoguesWhenNoControllersConnected() + { + // Arrange + var aircraftManager = new TestAircraftRepository(); + var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); + aircraft.RequestLogon(DateTimeOffset.UtcNow); + aircraft.AcceptLogon(DateTimeOffset.UtcNow); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); + + var clock = new TestClock(); + var dialogueRepository = new TestDialogueRepository(); + var openDialogue = new Dialogue("UAL123", "YBBB"); + openDialogue.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", clock.UtcNow()); + await dialogueRepository.Add(openDialogue, CancellationToken.None); + + var messageIdProvider = new TestMessageIdProvider(); + var handler = new AircraftConnectionLostNotificationHandler( + aircraftManager, + new TestControllerRepository(), + dialogueRepository, + Substitute.For>(), + messageIdProvider, + new TestPublisher(), + clock, + new TestUnitOfWork(), Logger.None); + + // Act + await handler.Handle(new AircraftConnectionLost("hoppies-ybbb", "UAL123"), CancellationToken.None); + + // Assert - the dialogue is closed with the error message, and the message IDs are removed + Assert.True(openDialogue.IsClosed); + Assert.Equal("ERROR CONNECTION TIMED OUT", Assert.IsType(openDialogue.Messages.Last()).Content); + Assert.Equal([("hoppies-ybbb", "UAL123")], messageIdProvider.Removed); + } + [Fact] public async Task Handle_AddsErrorMessageToExistingOpenDialogue() { @@ -211,7 +251,7 @@ public async Task Handle_AddsErrorMessageToExistingOpenDialogue() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(DateTimeOffset.UtcNow); aircraft.AcceptLogon(DateTimeOffset.UtcNow); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var controller = new ControllerInfo( @@ -219,14 +259,15 @@ public async Task Handle_AddsErrorMessageToExistingOpenDialogue() "ConnectionId-1", "YBBB", "BN-TSN_FSS", - "1234567"); + "1234567", + "Test Controller"); await controllerManager.Add(controller, CancellationToken.None); var dialogueRepository = new TestDialogueRepository(); var clock = new TestClock(); // Create an existing dialogue with an open downlink message - var existingDialogue = new Dialogue("UAL123"); + var existingDialogue = new Dialogue("UAL123", "YBBB"); existingDialogue.AddDownlink( 1, null, @@ -252,7 +293,7 @@ public async Task Handle_AddsErrorMessageToExistingOpenDialogue() messageIdProvider, publisher, clock, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionLost("hoppies-ybbb", "UAL123"); @@ -270,6 +311,9 @@ public async Task Handle_AddsErrorMessageToExistingOpenDialogue() Assert.Equal("ERROR CONNECTION TIMED OUT", errorMessage.Content); Assert.Equal(AlertType.Medium, errorMessage.AlertType); Assert.Equal(1, errorMessage.MessageReference); // References the open downlink + + // Assert - the message IDs of the connection are removed after the error message + Assert.Equal([("hoppies-ybbb", "UAL123")], messageIdProvider.Removed); } [Fact] @@ -280,7 +324,7 @@ public async Task Handle_ClosesOpenDialogue_SoItCanBeArchived() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(DateTimeOffset.UtcNow); aircraft.AcceptLogon(DateTimeOffset.UtcNow); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var controller = new ControllerInfo( @@ -288,14 +332,15 @@ public async Task Handle_ClosesOpenDialogue_SoItCanBeArchived() "ConnectionId-1", "YBBB", "BN-TSN_FSS", - "1234567"); + "1234567", + "Test Controller"); await controllerManager.Add(controller, CancellationToken.None); var dialogueRepository = new TestDialogueRepository(); var clock = new TestClock(); // Create an existing dialogue with an open downlink message - var existingDialogue = new Dialogue("UAL123"); + var existingDialogue = new Dialogue("UAL123", "YBBB"); var openDownlink = existingDialogue.AddDownlink( 1, null, @@ -321,7 +366,7 @@ public async Task Handle_ClosesOpenDialogue_SoItCanBeArchived() messageIdProvider, publisher, clock, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionLost("hoppies-ybbb", "UAL123"); diff --git a/source/CPDLCServer.Tests/Handlers/AircraftConnectionTerminatedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandlerTests.cs similarity index 89% rename from source/CPDLCServer.Tests/Handlers/AircraftConnectionTerminatedNotificationHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandlerTests.cs index 921b33a..8165f4f 100644 --- a/source/CPDLCServer.Tests/Handlers/AircraftConnectionTerminatedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandlerTests.cs @@ -1,13 +1,12 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Hubs; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Web; using CPDLCServer.Tests.Mocks; using Microsoft.AspNetCore.SignalR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class AircraftConnectionTerminatedNotificationHandlerTests { @@ -21,13 +20,15 @@ public async Task Handle_NotifiesAllConnectedControllers() "ConnectionId-1", "YBBB", "BN-TSN_FSS", - "1234567"); + "1234567", + "Test Controller"); var controller2 = new ControllerInfo( Guid.NewGuid(), "ConnectionId-2", "YBBB", "BN-OCN_CTR", - "7654321"); + "1234567", + "Test Controller"); await controllerManager.Add(controller1, CancellationToken.None); await controllerManager.Add(controller2, CancellationToken.None); @@ -38,7 +39,7 @@ public async Task Handle_NotifiesAllConnectedControllers() var handler = new AircraftConnectionTerminatedNotificationHandler( controllerManager, hubContext, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionTerminated("hoppies-ybbb", "YBBB", "UAL123"); @@ -70,7 +71,7 @@ public async Task Handle_DoesNotNotifyWhenNoControllersConnected() var handler = new AircraftConnectionTerminatedNotificationHandler( controllerManager, hubContext, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionTerminated("hoppies-ybbb", "YBBB", "UAL123"); diff --git a/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftRepositoryTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftRepositoryTests.cs new file mode 100644 index 0000000..a4831fe --- /dev/null +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftRepositoryTests.cs @@ -0,0 +1,95 @@ +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Tests.Mocks; + +namespace CPDLCServer.Tests.Cpdlc.Connections; + +public class AircraftRepositoryTests +{ + static readonly DateTimeOffset Start = new(2026, 10, 13, 12, 0, 0, TimeSpan.Zero); + + [Fact] + public async Task Find_ReturnsSavedConnection() + { + // Arrange + using var database = new TestDatabase(); + var connection = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.NextDataAuthority); + connection.RequestLogon(Start); + connection.AcceptLogon(Start.AddSeconds(5)); + connection.PromoteToCurrentDataAuthority(); + connection.SetNextDataAuthority("YMMM", Start.AddHours(1)); + connection.SentNextDataAuthorityMessage(); + + await using (var dbContext = database.CreateDbContext()) + { + await new AircraftRepository(dbContext).Add(new("UAL123", "hoppies-ybbb"), connection, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act + await using var readDbContext = database.CreateDbContext(); + var saved = await new AircraftRepository(readDbContext).Find(new("UAL123", "hoppies-ybbb"), CancellationToken.None); + + // Assert + Assert.NotNull(saved); + Assert.Equal("YBBB", saved.StationId); + Assert.Equal(DataAuthorityState.CurrentDataAuthority, saved.DataAuthorityState); + Assert.Equal(ConnectionState.Connected, saved.ConnectionState); + Assert.Equal(Start, saved.LogonRequested); + Assert.Equal(Start.AddSeconds(5), saved.LogonAccepted); + Assert.Equal(Start.AddSeconds(5), saved.LastSeen); + Assert.Equal("YMMM", saved.NextDataAuthority); + Assert.Equal(Start.AddHours(1), saved.ExpectedTransferTime); + Assert.True(saved.DidSentNextDataAuthorityMessage); + } + + [Fact] + public async Task Add_WhenConnectionExists_ReplacesConnection() + { + // Arrange + using var database = new TestDatabase(); + var first = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.NextDataAuthority); + var second = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); + + await using (var dbContext = database.CreateDbContext()) + { + await new AircraftRepository(dbContext).Add(new("UAL123", "hoppies-ybbb"), first, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act + await using (var dbContext = database.CreateDbContext()) + { + await new AircraftRepository(dbContext).Add(new("UAL123", "hoppies-ybbb"), second, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Assert + await using var readDbContext = database.CreateDbContext(); + var connections = await new AircraftRepository(readDbContext).All(CancellationToken.None); + var connection = Assert.Single(connections); + Assert.Equal(DataAuthorityState.CurrentDataAuthority, connection.DataAuthorityState); + } + + [Fact] + public async Task Remove_InSameUnitOfWorkAsAdd_DoesNotSaveConnection() + { + // Arrange + using var database = new TestDatabase(); + var connection = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.NextDataAuthority); + + // Act + bool removed; + await using (var dbContext = database.CreateDbContext()) + { + var repository = new AircraftRepository(dbContext); + await repository.Add(new("UAL123", "hoppies-ybbb"), connection, CancellationToken.None); + removed = await repository.Remove(new("UAL123", "hoppies-ybbb"), CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Assert + Assert.True(removed); + await using var readDbContext = database.CreateDbContext(); + Assert.Empty(await new AircraftRepository(readDbContext).All(CancellationToken.None)); + } +} diff --git a/source/CPDLCServer.Tests/Handlers/CheckLostAircraftConnectionsRequestHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/CheckLostAircraftConnectionsRequestHandlerTests.cs similarity index 56% rename from source/CPDLCServer.Tests/Handlers/CheckLostAircraftConnectionsRequestHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/CheckLostAircraftConnectionsRequestHandlerTests.cs index ca2f385..000e371 100644 --- a/source/CPDLCServer.Tests/Handlers/CheckLostAircraftConnectionsRequestHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/CheckLostAircraftConnectionsRequestHandlerTests.cs @@ -1,16 +1,92 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Infrastructure; +using CPDLCServer.Settings; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class CheckLostAircraftConnectionsRequestHandlerTests { + static readonly TestServerSettingsProvider Settings = new(new ServerSettings { AircraftConnectionTimeoutMinutes = 15 }); + + // The server has been online for longer than any timeout + static readonly ServerStartTime StartedLongAgo = new(DateTimeOffset.MinValue); + + [Fact] + public async Task Handle_WhenServerOnlineForLessThanTimeout_DoesNotPublishAircraftLost() + { + // Arrange - the aircraft was last seen long before the server started + var aircraftRepository = new TestAircraftRepository(); + var clock = new TestClock(); + var mediator = Substitute.For(); + + var lastSeen = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + clock.SetUtcNow(lastSeen); + + var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); + aircraft.RequestLogon(lastSeen); + aircraft.AcceptLogon(lastSeen); + await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); + + var timeout = TimeSpan.FromMinutes(15); + var serverStarted = lastSeen.AddHours(2); + var handler = new CheckLostAircraftConnectionsRequestHandler( + aircraftRepository, + Settings, + clock, + new ServerStartTime(serverStarted), + mediator, + Logger.None); + + clock.SetUtcNow(serverStarted + timeout); + + // Act + await handler.Handle(new CheckLostAircraftConnectionsRequest(), CancellationToken.None); + + // Assert + Assert.Empty(mediator.ReceivedCalls()); + } + + [Fact] + public async Task Handle_WhenServerOnlineForLongerThanTimeout_PublishesAircraftLost() + { + // Arrange - the aircraft was last seen long before the server started + var aircraftRepository = new TestAircraftRepository(); + var clock = new TestClock(); + var mediator = Substitute.For(); + + var lastSeen = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + clock.SetUtcNow(lastSeen); + + var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); + aircraft.RequestLogon(lastSeen); + aircraft.AcceptLogon(lastSeen); + await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); + + var timeout = TimeSpan.FromMinutes(15); + var serverStarted = lastSeen.AddHours(2); + var handler = new CheckLostAircraftConnectionsRequestHandler( + aircraftRepository, + Settings, + clock, + new ServerStartTime(serverStarted), + mediator, + Logger.None); + + clock.SetUtcNow(serverStarted + timeout + TimeSpan.FromMinutes(1)); + + // Act + await handler.Handle(new CheckLostAircraftConnectionsRequest(), CancellationToken.None); + + // Assert + await mediator.Received(1).Publish( + Arg.Is(n => n.AcarsConnectionId == "hoppies-ybbb" && n.Callsign == "UAL123"), + Arg.Any()); + } + [Fact] public async Task Handle_PublishesAircraftLostWhenConnectionTimedOut() { @@ -25,11 +101,13 @@ public async Task Handle_PublishesAircraftLostWhenConnectionTimedOut() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(initialTime); aircraft.AcceptLogon(initialTime); - await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new CheckLostAircraftConnectionsRequestHandler( aircraftRepository, + Settings, clock, + StartedLongAgo, mediator, Logger.None); @@ -38,14 +116,14 @@ public async Task Handle_PublishesAircraftLostWhenConnectionTimedOut() var now = initialTime.Add(timeout).AddMinutes(1); clock.SetUtcNow(now); - var request = new CheckLostAircraftConnectionsRequest(timeout); + var request = new CheckLostAircraftConnectionsRequest(); // Act await handler.Handle(request, CancellationToken.None); // Assert await mediator.Received(1).Publish( - Arg.Is(n => n.AcarsClientId == "hoppies-ybbb" && n.Callsign == "UAL123"), + Arg.Is(n => n.AcarsConnectionId == "hoppies-ybbb" && n.Callsign == "UAL123"), Arg.Any()); } @@ -63,11 +141,13 @@ public async Task Handle_DoesNotPublishAircraftLostWhenConnectionNotTimedOut() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(initialTime); aircraft.AcceptLogon(initialTime); - await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new CheckLostAircraftConnectionsRequestHandler( aircraftRepository, + Settings, clock, + StartedLongAgo, mediator, Logger.None); @@ -76,7 +156,7 @@ public async Task Handle_DoesNotPublishAircraftLostWhenConnectionNotTimedOut() var now = initialTime.AddMinutes(15); clock.SetUtcNow(now); - var request = new CheckLostAircraftConnectionsRequest(timeout); + var request = new CheckLostAircraftConnectionsRequest(); // Act await handler.Handle(request, CancellationToken.None); @@ -101,16 +181,18 @@ public async Task Handle_PublishesAircraftLostForEachTimedOutAircraft() var aircraft1 = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft1.RequestLogon(initialTime); aircraft1.AcceptLogon(initialTime); - await aircraftRepository.Add(new AircraftKey(aircraft1.Callsign, aircraft1.AcarsClientId), aircraft1, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(aircraft1.Callsign, aircraft1.AcarsConnectionId), aircraft1, CancellationToken.None); var aircraft2 = new AircraftConnection("QFA456", "hoppies-ymmm", "YMMM", DataAuthorityState.CurrentDataAuthority); aircraft2.RequestLogon(initialTime); aircraft2.AcceptLogon(initialTime); - await aircraftRepository.Add(new AircraftKey(aircraft2.Callsign, aircraft2.AcarsClientId), aircraft2, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(aircraft2.Callsign, aircraft2.AcarsConnectionId), aircraft2, CancellationToken.None); var handler = new CheckLostAircraftConnectionsRequestHandler( aircraftRepository, + Settings, clock, + StartedLongAgo, mediator, Logger.None); @@ -119,18 +201,18 @@ public async Task Handle_PublishesAircraftLostForEachTimedOutAircraft() var now = initialTime.Add(timeout).AddMinutes(1); clock.SetUtcNow(now); - var request = new CheckLostAircraftConnectionsRequest(timeout); + var request = new CheckLostAircraftConnectionsRequest(); // Act await handler.Handle(request, CancellationToken.None); // Assert await mediator.Received(1).Publish( - Arg.Is(n => n.AcarsClientId == "hoppies-ybbb" && n.Callsign == "UAL123"), + Arg.Is(n => n.AcarsConnectionId == "hoppies-ybbb" && n.Callsign == "UAL123"), Arg.Any()); await mediator.Received(1).Publish( - Arg.Is(n => n.AcarsClientId == "hoppies-ymmm" && n.Callsign == "QFA456"), + Arg.Is(n => n.AcarsConnectionId == "hoppies-ymmm" && n.Callsign == "QFA456"), Arg.Any()); } @@ -149,7 +231,7 @@ public async Task Handle_OnlyPublishesForTimedOutAircraft() var oldAircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); oldAircraft.RequestLogon(initialTime); oldAircraft.AcceptLogon(initialTime); - await aircraftRepository.Add(new AircraftKey(oldAircraft.Callsign, oldAircraft.AcarsClientId), oldAircraft, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(oldAircraft.Callsign, oldAircraft.AcarsConnectionId), oldAircraft, CancellationToken.None); // Advance time past the timeout var timeout = TimeSpan.FromMinutes(15); @@ -160,15 +242,17 @@ public async Task Handle_OnlyPublishesForTimedOutAircraft() var newAircraft = new AircraftConnection("QFA456", "hoppies-ymmm", "YMMM", DataAuthorityState.CurrentDataAuthority); newAircraft.RequestLogon(now); newAircraft.AcceptLogon(now); - await aircraftRepository.Add(new AircraftKey(newAircraft.Callsign, newAircraft.AcarsClientId), newAircraft, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(newAircraft.Callsign, newAircraft.AcarsConnectionId), newAircraft, CancellationToken.None); var handler = new CheckLostAircraftConnectionsRequestHandler( aircraftRepository, + Settings, clock, + StartedLongAgo, mediator, Logger.None); - var request = new CheckLostAircraftConnectionsRequest(timeout); + var request = new CheckLostAircraftConnectionsRequest(); // Act await handler.Handle(request, CancellationToken.None); diff --git a/source/CPDLCServer.Tests/Handlers/GetConnectedAircraftRequestHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/GetConnectedAircraftRequestHandlerTests.cs similarity index 87% rename from source/CPDLCServer.Tests/Handlers/GetConnectedAircraftRequestHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/GetConnectedAircraftRequestHandlerTests.cs index 48e0a8b..132156a 100644 --- a/source/CPDLCServer.Tests/Handlers/GetConnectedAircraftRequestHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/GetConnectedAircraftRequestHandlerTests.cs @@ -1,9 +1,7 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Connections; using CPDLCServer.Tests.Mocks; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class GetConnectedAircraftRequestHandlerTests { @@ -22,7 +20,7 @@ public async Task Handle_ReturnsAllConnectedAircraft() DataAuthorityState.CurrentDataAuthority); aircraft1.RequestLogon(DateTimeOffset.UtcNow); aircraft1.AcceptLogon(DateTimeOffset.UtcNow); - await aircraftManager.Add(new(aircraft1.Callsign, aircraft1.AcarsClientId), aircraft1, CancellationToken.None); + await aircraftManager.Add(new(aircraft1.Callsign, aircraft1.AcarsConnectionId), aircraft1, CancellationToken.None); var aircraft2 = new AircraftConnection( "QFA456", @@ -30,23 +28,23 @@ public async Task Handle_ReturnsAllConnectedAircraft() "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft2.RequestLogon(DateTimeOffset.UtcNow); - await aircraftManager.Add(new(aircraft2.Callsign, aircraft2.AcarsClientId), aircraft2, CancellationToken.None); + await aircraftManager.Add(new(aircraft2.Callsign, aircraft2.AcarsConnectionId), aircraft2, CancellationToken.None); - // Aircraft on different ACARS client - should also be returned + // Aircraft on different ACARS connection - should also be returned var aircraft3 = new AircraftConnection( "AAL789", "hoppies-ymmm", "YMMM", DataAuthorityState.CurrentDataAuthority); aircraft3.RequestLogon(DateTimeOffset.UtcNow); - await aircraftManager.Add(new(aircraft3.Callsign, aircraft3.AcarsClientId), aircraft3, CancellationToken.None); + await aircraftManager.Add(new(aircraft3.Callsign, aircraft3.AcarsConnectionId), aircraft3, CancellationToken.None); var query = new GetConnectedAircraftRequest(); // Act var result = await handler.Handle(query, CancellationToken.None); - // Assert - returns ALL aircraft regardless of ACARS client + // Assert - returns ALL aircraft regardless of ACARS connection Assert.NotNull(result); Assert.Equal(3, result.Aircraft.Length); Assert.Contains(result.Aircraft, a => a.Callsign == "UAL123"); @@ -85,7 +83,7 @@ public async Task Handle_IncludesAllConnectionState() DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(DateTimeOffset.UtcNow); aircraft.AcceptLogon(DateTimeOffset.UtcNow); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var query = new GetConnectedAircraftRequest(); diff --git a/source/CPDLCServer.Tests/Handlers/LogonCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/LogonCommandHandlerTests.cs similarity index 50% rename from source/CPDLCServer.Tests/Handlers/LogonCommandHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/LogonCommandHandlerTests.cs index 3eb5c33..8788aac 100644 --- a/source/CPDLCServer.Tests/Handlers/LogonCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/LogonCommandHandlerTests.cs @@ -1,12 +1,14 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class LogonCommandHandlerTests { @@ -18,10 +20,10 @@ public class LogonCommandHandlerTests DownlinkAlertType: AlertType.None, DownlinkContent: "REQUEST LOGON", DownlinkReceived: clock.UtcNow(), - AcarsClientId: "hoppies-ybbb"); + AcarsConnectionId: "hoppies-ybbb"); static LogonCommandHandler BuildHandler( - TestClientManager clientManager, + TestAcarsConnectionManager acarsConnectionManager, TestAircraftRepository aircraftRepository, TestControllerRepository controllerRepository, TestDialogueRepository dialogueRepository, @@ -29,13 +31,14 @@ static LogonCommandHandler BuildHandler( TestClock clock, IMediator mediator) => new( - clientManager, + acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator, + new TestUplinkTransmitter(), Logger.None); [Fact] @@ -43,7 +46,7 @@ public async Task Handle_NoATC_RejectsLogon() { // Arrange var clock = new TestClock(); - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var aircraftRepository = new TestAircraftRepository(); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -51,17 +54,17 @@ public async Task Handle_NoATC_RejectsLogon() var mediator = Substitute.For(); var command = BuildLogonCommand(clock); - var handler = BuildHandler(clientManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); + var handler = BuildHandler(acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); // Act await handler.Handle(command, CancellationToken.None); - // Assert - rejection uplink transmitted via the ACARS client - var client = (TestAcarsClient)await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Single(client.SentMessages); - Assert.Equal("LOGON REJECTED. NO ATS AVBL.", client.SentMessages[0].Content); - Assert.Equal("QFA1", client.SentMessages[0].Recipient); - Assert.Equal(1, client.SentMessages[0].MessageReference); + // Assert - rejection uplink transmitted via the ACARS connection + var acarsConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Single(acarsConnection.SentMessages); + Assert.Equal("LOGON REJECTED. NO ATS AVBL.", acarsConnection.SentMessages[0].Content); + Assert.Equal("QFA1", acarsConnection.SentMessages[0].Recipient); + Assert.Equal(1, acarsConnection.SentMessages[0].MessageReference); } [Fact] @@ -69,7 +72,7 @@ public async Task Handle_NoATC_DoesNotTrackAircraft() { // Arrange var clock = new TestClock(); - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var aircraftRepository = new TestAircraftRepository(); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -77,7 +80,7 @@ public async Task Handle_NoATC_DoesNotTrackAircraft() var mediator = Substitute.For(); var command = BuildLogonCommand(clock); - var handler = BuildHandler(clientManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); + var handler = BuildHandler(acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); // Act await handler.Handle(command, CancellationToken.None); @@ -92,7 +95,7 @@ public async Task Handle_NewConnection_AcceptsLogon() { // Arrange var clock = new TestClock(); - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var aircraftRepository = new TestAircraftRepository(); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -104,21 +107,22 @@ public async Task Handle_NewConnection_AcceptsLogon() "Connection-1", "YBBB", "BN-TSN_FSS", - "1234567"); + "1234567", + "Test Controller"); await controllerRepository.Add(controller, CancellationToken.None); var command = BuildLogonCommand(clock); - var handler = BuildHandler(clientManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); + var handler = BuildHandler(acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); // Act await handler.Handle(command, CancellationToken.None); // Assert - acceptance uplink transmitted - var client = (TestAcarsClient)await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Single(client.SentMessages); - Assert.Equal("LOGON ACCEPTED", client.SentMessages[0].Content); - Assert.Equal("QFA1", client.SentMessages[0].Recipient); - Assert.Equal(1, client.SentMessages[0].MessageReference); + var acarsConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Single(acarsConnection.SentMessages); + Assert.Equal("LOGON ACCEPTED", acarsConnection.SentMessages[0].Content); + Assert.Equal("QFA1", acarsConnection.SentMessages[0].Recipient); + Assert.Equal(1, acarsConnection.SentMessages[0].MessageReference); } [Fact] @@ -126,7 +130,7 @@ public async Task Handle_NewConnection_TracksConnection() { // Arrange var clock = new TestClock(); - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var aircraftRepository = new TestAircraftRepository(); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -138,11 +142,12 @@ public async Task Handle_NewConnection_TracksConnection() "Connection-1", "YBBB", "BN-TSN_FSS", - "1234567"); + "1234567", + "Test Controller"); await controllerRepository.Add(controller, CancellationToken.None); var command = BuildLogonCommand(clock); - var handler = BuildHandler(clientManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); + var handler = BuildHandler(acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); // Act await handler.Handle(command, CancellationToken.None); @@ -161,7 +166,7 @@ public async Task Handle_NewConnection_PersistsDialogueWithDownlinkAndUplink() { // Arrange var clock = new TestClock(); - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var aircraftRepository = new TestAircraftRepository(); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -173,11 +178,12 @@ public async Task Handle_NewConnection_PersistsDialogueWithDownlinkAndUplink() "Connection-1", "YBBB", "BN-TSN_FSS", - "1234567"); + "1234567", + "Test Controller"); await controllerRepository.Add(controller, CancellationToken.None); var command = BuildLogonCommand(clock); - var handler = BuildHandler(clientManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); + var handler = BuildHandler(acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); // Act await handler.Handle(command, CancellationToken.None); @@ -199,45 +205,133 @@ public async Task Handle_NewConnection_PersistsDialogueWithDownlinkAndUplink() await mediator.Received(1).Publish(Arg.Any(), Arg.Any()); } + static async Task AddExistingConnection(TestAircraftRepository aircraftRepository, TestClock clock) + { + var existing = new AircraftConnection("QFA1", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); + existing.RequestLogon(clock.UtcNow()); + existing.AcceptLogon(clock.UtcNow()); + existing.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(30)); + await aircraftRepository.Add(new("QFA1", "hoppies-ybbb"), existing, CancellationToken.None); + return existing; + } + + static async Task AddController(TestControllerRepository controllerRepository) + { + var controller = new ControllerInfo( + Guid.NewGuid(), + "Connection-1", + "YBBB", + "BN-TSN_FSS", + "1234567", + "Test Controller"); + await controllerRepository.Add(controller, CancellationToken.None); + } + [Fact] - public async Task Handle_ExistingConnection_AcceptsLogon_AndDoesNotDuplicateConnection() + public async Task Handle_ExistingConnection_ReplacesConnection() { // Arrange var clock = new TestClock(); - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var aircraftRepository = new TestAircraftRepository(); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); var messageIdProvider = new TestMessageIdProvider(); var mediator = Substitute.For(); - var controller = new ControllerInfo( - Guid.NewGuid(), - "Connection-1", - "YBBB", - "BN-TSN_FSS", - "1234567"); - await controllerRepository.Add(controller, CancellationToken.None); + await AddController(controllerRepository); + var existing = await AddExistingConnection(aircraftRepository, clock); - var existing = new AircraftConnection("QFA1", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); - existing.RequestLogon(clock.UtcNow()); - existing.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new("QFA1", "hoppies-ybbb"), existing, CancellationToken.None); + var command = BuildLogonCommand(clock); + var handler = BuildHandler(acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); + + // Act + await handler.Handle(command, CancellationToken.None); + + // Assert - the logon is accepted + var acarsConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Equal("LOGON ACCEPTED", Assert.Single(acarsConnection.SentMessages).Content); + + // Assert - a new connection replaces the existing connection, and does not keep its state + var connection = Assert.Single(await aircraftRepository.All(CancellationToken.None)); + Assert.NotSame(existing, connection); + Assert.Equal(DataAuthorityState.NextDataAuthority, connection.DataAuthorityState); + Assert.False(connection.HasNextDataAuthority); + + // Assert - the new connection is established, so that a new ADS-C contract is requested + await mediator.Received(1).Publish( + new AircraftConnectionEstablished("hoppies-ybbb", "YBBB", "QFA1", DataAuthorityState.NextDataAuthority), + Arg.Any()); + } + + [Fact] + public async Task Handle_ExistingConnection_PublishesReset() + { + // Arrange + var clock = new TestClock(); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var aircraftRepository = new TestAircraftRepository(); + var controllerRepository = new TestControllerRepository(); + var dialogueRepository = new TestDialogueRepository(); + var messageIdProvider = new TestMessageIdProvider(); + var mediator = Substitute.For(); + + await AddController(controllerRepository); + await AddExistingConnection(aircraftRepository, clock); var command = BuildLogonCommand(clock); - var handler = BuildHandler(clientManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); + var handler = BuildHandler(acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); // Act await handler.Handle(command, CancellationToken.None); // Assert - var client = (TestAcarsClient)await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Single(client.SentMessages); - Assert.Equal("LOGON ACCEPTED", client.SentMessages[0].Content); + await mediator.Received(1).Publish( + new AircraftConnectionReset("hoppies-ybbb", "YBBB", "QFA1"), + Arg.Any()); + } + + [Fact] + public async Task Handle_ExistingConnection_ClosesOpenDialoguesWithResetMessage() + { + // Arrange + var clock = new TestClock(); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var aircraftRepository = new TestAircraftRepository(); + var controllerRepository = new TestControllerRepository(); + var dialogueRepository = new TestDialogueRepository(); + var messageIdProvider = new TestMessageIdProvider(); + messageIdProvider.SetNextId(10); + var mediator = Substitute.For(); + + await AddController(controllerRepository); + await AddExistingConnection(aircraftRepository, clock); + + var openDialogue = new Dialogue("QFA1", "YBBB"); + openDialogue.AddUplink(5, null, "QFA1", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", clock.UtcNow()); + await dialogueRepository.Add(openDialogue, CancellationToken.None); + + // A dialogue with a different ATSU is not part of the connection + var otherStationDialogue = new Dialogue("QFA1", "YMMM"); + otherStationDialogue.AddUplink(6, null, "QFA1", "ML-IND_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL390", clock.UtcNow()); + await dialogueRepository.Add(otherStationDialogue, CancellationToken.None); + + var command = BuildLogonCommand(clock); + var handler = BuildHandler(acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); + + // Act + await handler.Handle(command, CancellationToken.None); + + // Assert - the open dialogue is closed with the reset message + Assert.True(openDialogue.IsClosed); + var resetMessage = Assert.IsType(openDialogue.Messages.Last()); + Assert.Equal("CPDLC CONNECTION RESET", resetMessage.Content); + Assert.Equal(10, resetMessage.MessageId); + Assert.Equal(5, resetMessage.MessageReference); - var allTrackedAircraft = await aircraftRepository.All(CancellationToken.None); - Assert.Single(allTrackedAircraft); - Assert.Equal("QFA1", allTrackedAircraft.Single().Callsign); + // Assert - the dialogue with the other ATSU does not change + Assert.False(otherStationDialogue.IsClosed); + Assert.Single(otherStationDialogue.Messages); } [Fact] @@ -245,7 +339,7 @@ public async Task Handle_NotifiesATC() { // Arrange var clock = new TestClock(); - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var aircraftRepository = new TestAircraftRepository(); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -257,11 +351,12 @@ public async Task Handle_NotifiesATC() "Connection-1", "YBBB", "BN-TSN_FSS", - "1234567"); + "1234567", + "Test Controller"); await controllerRepository.Add(controller, CancellationToken.None); var command = BuildLogonCommand(clock); - var handler = BuildHandler(clientManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); + var handler = BuildHandler(acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); // Act await handler.Handle(command, CancellationToken.None); diff --git a/source/CPDLCServer.Tests/Cpdlc/Connections/SendConnectionRequestCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/SendConnectionRequestCommandHandlerTests.cs new file mode 100644 index 0000000..cb5092d --- /dev/null +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/SendConnectionRequestCommandHandlerTests.cs @@ -0,0 +1,102 @@ +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Tests.Mocks; +using Serilog.Core; + +namespace CPDLCServer.Tests.Cpdlc.Connections; + +public class SendConnectionRequestCommandHandlerTests +{ + [Fact] + public async Task Handle_SendsConnectionRequestUplink() + { + // Arrange + var acarsConnectionManager = new TestAcarsConnectionManager(); + var messageIdProvider = new TestMessageIdProvider(); + messageIdProvider.SetNextId(5); + var clock = new TestClock(); + + var handler = new SendConnectionRequestCommandHandler(acarsConnectionManager, messageIdProvider, clock, new TestUnitOfWork(), Logger.None); + + var command = new SendConnectionRequestCommand("UAL123", "YBBB"); + + // Act + await handler.Handle(command, CancellationToken.None); + + // Assert + var acarsConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + var uplink = Assert.Single(acarsConnection.SentMessages); + Assert.Equal("UAL123", uplink.Recipient); + Assert.Equal("CONNECTION REQUESTED @YBBB@", uplink.Content); + Assert.Equal(5, uplink.MessageId); + Assert.Null(uplink.MessageReference); + Assert.Equal(CpdlcUplinkResponseType.NoResponse, uplink.ResponseType); + Assert.Equal(clock.UtcNow(), uplink.Sent); + } + + [Fact] + public async Task Handle_SendsUplinkViaConnectionForSelectedStation() + { + // The uplink must go through the ACARS connection of the selected ATSU, not another acarsConnection. + // Arrange + var acarsConnectionManager = new TestAcarsConnectionManager(); + var messageIdProvider = new TestMessageIdProvider(); + var clock = new TestClock(); + + var handler = new SendConnectionRequestCommandHandler(acarsConnectionManager, messageIdProvider, clock, new TestUnitOfWork(), Logger.None); + + var command = new SendConnectionRequestCommand("UAL123", "YMMM"); + + // Act + await handler.Handle(command, CancellationToken.None); + + // Assert + var ymmmConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ymmm", CancellationToken.None); + var ybbbConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + + var uplink = Assert.Single(ymmmConnection.SentMessages); + Assert.Equal("CONNECTION REQUESTED @YMMM@", uplink.Content); + Assert.Empty(ybbbConnection.SentMessages); + } + + [Fact] + public async Task Handle_MatchesStationIdIgnoringCase() + { + // Arrange + var acarsConnectionManager = new TestAcarsConnectionManager(); + var messageIdProvider = new TestMessageIdProvider(); + var clock = new TestClock(); + + var handler = new SendConnectionRequestCommandHandler(acarsConnectionManager, messageIdProvider, clock, new TestUnitOfWork(), Logger.None); + + var command = new SendConnectionRequestCommand("UAL123", "ybbb"); + + // Act + await handler.Handle(command, CancellationToken.None); + + // Assert + var acarsConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Single(acarsConnection.SentMessages); + } + + [Fact] + public async Task Handle_ThrowsWhenNoConnectionForStation() + { + // Arrange + var acarsConnectionManager = new TestAcarsConnectionManager(); + var messageIdProvider = new TestMessageIdProvider(); + var clock = new TestClock(); + + var handler = new SendConnectionRequestCommandHandler(acarsConnectionManager, messageIdProvider, clock, new TestUnitOfWork(), Logger.None); + + var command = new SendConnectionRequestCommand("UAL123", "YPPP"); + + // Act & Assert + await Assert.ThrowsAnyAsync(() => handler.Handle(command, CancellationToken.None)); + + var ybbbConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + var ymmmConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ymmm", CancellationToken.None); + Assert.Empty(ybbbConnection.SentMessages); + Assert.Empty(ymmmConnection.SentMessages); + } +} diff --git a/source/CPDLCServer.Tests/Handlers/TerminateConnectionHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionHandlerTests.cs similarity index 83% rename from source/CPDLCServer.Tests/Handlers/TerminateConnectionHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionHandlerTests.cs index b4bbba7..209fdc1 100644 --- a/source/CPDLCServer.Tests/Handlers/TerminateConnectionHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionHandlerTests.cs @@ -1,12 +1,12 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class TerminateConnectionHandlerTests { @@ -14,10 +14,12 @@ static TerminateConnectionHandler BuildHandler( TestAircraftRepository aircraftRepository, TestDialogueRepository dialogueRepository, TestClock clock, - IMediator mediator) => + IMediator mediator, + TestMessageIdProvider? messageIdProvider = null) => new( aircraftRepository, dialogueRepository, + messageIdProvider ?? new TestMessageIdProvider(), clock, mediator, Logger.None); @@ -27,13 +29,13 @@ static async Task AddConnectedAircraft(TestAircraftRepositor var aircraft = new AircraftConnection(callsign, "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); return aircraft; } static async Task AddOpenDialogue(TestDialogueRepository dialogueRepository, TestClock clock, string callsign) { - var dialogue = new Dialogue(callsign); + var dialogue = new Dialogue(callsign, "YBBB"); dialogue.AddDownlink( 1, null, @@ -67,7 +69,7 @@ public async Task Handle_RemovesConnectionAndPublishesTerminatedNotification() await mediator.Received(1).Publish( Arg.Is(n => - n.AcarsClientId == "hoppies-ybbb" && + n.AcarsConnectionId == "hoppies-ybbb" && n.StationId == "YBBB" && n.Callsign == "UAL123"), Arg.Any()); @@ -108,7 +110,7 @@ public async Task Handle_DoesNotChangeClosedOrArchivedDialogues() var mediator = Substitute.For(); await AddConnectedAircraft(aircraftRepository, clock, "UAL123"); - var closedDialogue = new Dialogue("UAL123"); + var closedDialogue = new Dialogue("UAL123", "YBBB"); closedDialogue.AddDownlink( 1, null, @@ -177,4 +179,24 @@ public async Task Handle_UnknownAircraft_DoesNothing() await mediator.DidNotReceive().Publish(Arg.Any(), Arg.Any()); await mediator.DidNotReceive().Publish(Arg.Any(), Arg.Any()); } + + [Fact] + public async Task Handle_RemovesMessageIdSequence() + { + // Arrange + var clock = new TestClock(); + var aircraftRepository = new TestAircraftRepository(); + var dialogueRepository = new TestDialogueRepository(); + var messageIdProvider = new TestMessageIdProvider(); + var mediator = Substitute.For(); + await AddConnectedAircraft(aircraftRepository, clock, "UAL123"); + + var handler = BuildHandler(aircraftRepository, dialogueRepository, clock, mediator, messageIdProvider); + + // Act + await handler.Handle(new TerminateConnectionRequest("UAL123", "hoppies-ybbb"), CancellationToken.None); + + // Assert + Assert.Equal([("hoppies-ybbb", "UAL123")], messageIdProvider.Removed); + } } diff --git a/source/CPDLCServer.Tests/Handlers/TerminateConnectionOnDialogueClosedHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandlerTests.cs similarity index 90% rename from source/CPDLCServer.Tests/Handlers/TerminateConnectionOnDialogueClosedHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandlerTests.cs index aafa77e..d81d89c 100644 --- a/source/CPDLCServer.Tests/Handlers/TerminateConnectionOnDialogueClosedHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandlerTests.cs @@ -1,12 +1,13 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class TerminateConnectionOnDialogueClosedHandlerTests { @@ -22,7 +23,7 @@ public async Task Handle_ClosedDialogueWithEndService_TerminatesConnection() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TerminateConnectionOnDialogueClosedHandler( aircraftRepository, @@ -30,7 +31,7 @@ public async Task Handle_ClosedDialogueWithEndService_TerminatesConnection() Logger.None); // Create a closed dialogue with END SERVICE - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, @@ -51,7 +52,7 @@ await mediator.Received(1) .Send( Arg.Is(req => req.Callsign == "UAL123" && - req.AcarsClientId == "hoppies-ybbb"), + req.AcarsConnectionId == "hoppies-ybbb"), Arg.Any()); } @@ -67,7 +68,7 @@ public async Task Handle_OpenDialogueWithEndService_DoesNotTerminateConnection() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TerminateConnectionOnDialogueClosedHandler( aircraftRepository, @@ -75,7 +76,7 @@ public async Task Handle_OpenDialogueWithEndService_DoesNotTerminateConnection() Logger.None); // Create an open dialogue with END SERVICE (requires response) - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, @@ -110,7 +111,7 @@ public async Task Handle_ClosedDialogueWithoutEndService_DoesNotTerminateConnect var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TerminateConnectionOnDialogueClosedHandler( aircraftRepository, @@ -118,7 +119,7 @@ public async Task Handle_ClosedDialogueWithoutEndService_DoesNotTerminateConnect Logger.None); // Create a closed dialogue WITHOUT END SERVICE - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, @@ -153,7 +154,7 @@ public async Task Handle_ClosedDialogueWithMultipleMessages_TerminatesWhenEndSer var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TerminateConnectionOnDialogueClosedHandler( aircraftRepository, @@ -161,7 +162,7 @@ public async Task Handle_ClosedDialogueWithMultipleMessages_TerminatesWhenEndSer Logger.None); // Create a dialogue with multiple messages including END SERVICE - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); // Pilot request dialogue.AddDownlink( @@ -204,7 +205,7 @@ await mediator.Received(1) .Send( Arg.Is(req => req.Callsign == "UAL123" && - req.AcarsClientId == "hoppies-ybbb"), + req.AcarsConnectionId == "hoppies-ybbb"), Arg.Any()); } @@ -224,7 +225,7 @@ public async Task Handle_AircraftConnectionNotFound_LogsWarningAndDoesNotCrash() Logger.None); // Create a closed dialogue with END SERVICE - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, @@ -259,7 +260,7 @@ public async Task Handle_AircraftConnectionNotCDA_DoesNotTerminate() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.NextDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TerminateConnectionOnDialogueClosedHandler( aircraftRepository, @@ -267,7 +268,7 @@ public async Task Handle_AircraftConnectionNotCDA_DoesNotTerminate() Logger.None); // Create a closed dialogue with END SERVICE - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, diff --git a/source/CPDLCServer.Tests/Handlers/TransmitPendingNdaUplinksCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/TransmitPendingNdaUplinksCommandHandlerTests.cs similarity index 88% rename from source/CPDLCServer.Tests/Handlers/TransmitPendingNdaUplinksCommandHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/TransmitPendingNdaUplinksCommandHandlerTests.cs index 5b94a78..8ad99b0 100644 --- a/source/CPDLCServer.Tests/Handlers/TransmitPendingNdaUplinksCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/TransmitPendingNdaUplinksCommandHandlerTests.cs @@ -1,21 +1,18 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AcarsConnections.Stations; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Settings; using CPDLCServer.Tests.Mocks; using MediatR; -using Microsoft.Extensions.Configuration; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class TransmitPendingNdaUplinksCommandHandlerTests { - static IConfiguration DefaultConfiguration() => - new ConfigurationBuilder() - .AddInMemoryCollection(new Dictionary { ["Handoff:NotificationLeadTime"] = "10" }) - .Build(); + static TestServerSettingsProvider DefaultSettings() => + new(new ServerSettings { HandoffNotificationLeadTimeMinutes = 10 }); static IAcarsStationRepository OnlineCallsigns(params string[] callsigns) { @@ -35,7 +32,7 @@ public async Task Handle_WhenNoNextDataAuthority_DoesNotSendMessage() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TransmitPendingNdaUplinksCommandHandler( aircraftRepository, @@ -43,7 +40,7 @@ public async Task Handle_WhenNoNextDataAuthority_DoesNotSendMessage() mediator, clock, Logger.None, - DefaultConfiguration()); + DefaultSettings()); // Act await handler.Handle(new TransmitPendingNdaUplinksCommand(), CancellationToken.None); @@ -65,7 +62,7 @@ public async Task Handle_WhenHandoffMessageAlreadySent_DoesNotSendMessage() aircraft.AcceptLogon(clock.UtcNow()); aircraft.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(5)); aircraft.SentNextDataAuthorityMessage(); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TransmitPendingNdaUplinksCommandHandler( aircraftRepository, @@ -73,7 +70,7 @@ public async Task Handle_WhenHandoffMessageAlreadySent_DoesNotSendMessage() mediator, clock, Logger.None, - DefaultConfiguration()); + DefaultSettings()); // Act await handler.Handle(new TransmitPendingNdaUplinksCommand(), CancellationToken.None); @@ -96,7 +93,7 @@ public async Task Handle_WhenOutsideNotificationWindow_DoesNotSendMessage() // Transfer is 20 minutes away, notification window is 10 minutes, too early to send aircraft.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(20)); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TransmitPendingNdaUplinksCommandHandler( aircraftRepository, @@ -104,7 +101,7 @@ public async Task Handle_WhenOutsideNotificationWindow_DoesNotSendMessage() mediator, clock, Logger.None, - DefaultConfiguration()); + DefaultSettings()); // Act await handler.Handle(new TransmitPendingNdaUplinksCommand(), CancellationToken.None); @@ -127,7 +124,7 @@ public async Task Handle_WhenNdaAtsuIsOffline_DoesNotSendMessage() // Transfer is 5 minutes away, within the notification window aircraft.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(5)); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TransmitPendingNdaUplinksCommandHandler( aircraftRepository, @@ -135,7 +132,7 @@ public async Task Handle_WhenNdaAtsuIsOffline_DoesNotSendMessage() mediator, clock, Logger.None, - DefaultConfiguration()); + DefaultSettings()); // Act await handler.Handle(new TransmitPendingNdaUplinksCommand(), CancellationToken.None); @@ -158,7 +155,7 @@ public async Task Handle_WhenWithinNotificationWindow_SendsNextDataAuthorityMess // Transfer is 5 minutes away, notification window is 10 minutes, within the window aircraft.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(5)); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TransmitPendingNdaUplinksCommandHandler( aircraftRepository, @@ -166,7 +163,7 @@ public async Task Handle_WhenWithinNotificationWindow_SendsNextDataAuthorityMess mediator, clock, Logger.None, - DefaultConfiguration()); + DefaultSettings()); // Act await handler.Handle(new TransmitPendingNdaUplinksCommand(), CancellationToken.None); @@ -195,7 +192,7 @@ public async Task Handle_WhenMessageSent_UpdatesAircraftConnection() // Transfer is 5 minutes away; notification window is 10 minutes → within window aircraft.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(5)); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TransmitPendingNdaUplinksCommandHandler( aircraftRepository, @@ -203,7 +200,7 @@ public async Task Handle_WhenMessageSent_UpdatesAircraftConnection() mediator, clock, Logger.None, - DefaultConfiguration()); + DefaultSettings()); // Act await handler.Handle(new TransmitPendingNdaUplinksCommand(), CancellationToken.None); diff --git a/source/CPDLCServer.Tests/Handlers/UpdateNextDataAuthorityCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/UpdateNextDataAuthorityCommandHandlerTests.cs similarity index 94% rename from source/CPDLCServer.Tests/Handlers/UpdateNextDataAuthorityCommandHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/UpdateNextDataAuthorityCommandHandlerTests.cs index b987942..9a7fbf8 100644 --- a/source/CPDLCServer.Tests/Handlers/UpdateNextDataAuthorityCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/UpdateNextDataAuthorityCommandHandlerTests.cs @@ -1,10 +1,8 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Connections; using CPDLCServer.Tests.Mocks; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class UpdateNextDataAuthorityCommandHandlerTests { @@ -37,7 +35,7 @@ public async Task Handle_WhenSettingNextDataAuthority_UpdatesAircraftConnection( var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new UpdateNextDataAuthorityCommandHandler( aircraftRepository, @@ -72,7 +70,7 @@ public async Task Handle_WhenClearingNextDataAuthority_ClearsAircraftConnection( aircraft.AcceptLogon(clock.UtcNow()); aircraft.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(30)); aircraft.SentNextDataAuthorityMessage(); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new UpdateNextDataAuthorityCommandHandler( aircraftRepository, @@ -105,11 +103,11 @@ public async Task Handle_WhenMultipleAircraftWithSameCallsign_UpdatesCorrectOne( var aircraftYBBB = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraftYBBB.RequestLogon(clock.UtcNow()); aircraftYBBB.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraftYBBB.Callsign, aircraftYBBB.AcarsClientId), aircraftYBBB, CancellationToken.None); + await aircraftRepository.Add(new(aircraftYBBB.Callsign, aircraftYBBB.AcarsConnectionId), aircraftYBBB, CancellationToken.None); var aircraftYMMM = new AircraftConnection("UAL123", "hoppies-ymmm", "YMMM", DataAuthorityState.NextDataAuthority); aircraftYMMM.RequestLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraftYMMM.Callsign, aircraftYMMM.AcarsClientId), aircraftYMMM, CancellationToken.None); + await aircraftRepository.Add(new(aircraftYMMM.Callsign, aircraftYMMM.AcarsConnectionId), aircraftYMMM, CancellationToken.None); var handler = new UpdateNextDataAuthorityCommandHandler( aircraftRepository, @@ -145,7 +143,7 @@ public async Task Handle_WhenUpdatingExistingNextDataAuthority_ReplacesValues() aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); aircraft.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(30)); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new UpdateNextDataAuthorityCommandHandler( aircraftRepository, @@ -179,7 +177,7 @@ public async Task Handle_WhenUpdatingAfterMessageSent_ClearsFlagToAllowNewMessag aircraft.AcceptLogon(clock.UtcNow()); aircraft.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(30)); aircraft.SentNextDataAuthorityMessage(); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new UpdateNextDataAuthorityCommandHandler( aircraftRepository, @@ -214,7 +212,7 @@ public async Task Handle_WhenOnlyTransferTimeChangesAfterMessageSent_KeepsFlag() aircraft.AcceptLogon(clock.UtcNow()); aircraft.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(30)); aircraft.SentNextDataAuthorityMessage(); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new UpdateNextDataAuthorityCommandHandler( aircraftRepository, diff --git a/source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequestHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequestHandlerTests.cs new file mode 100644 index 0000000..f3e44b5 --- /dev/null +++ b/source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequestHandlerTests.cs @@ -0,0 +1,152 @@ +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Tests.Mocks; +using Serilog.Core; + +namespace CPDLCServer.Tests.Cpdlc.Dialogues; + +public class ArchiveCompletedDialoguesRequestHandlerTests +{ + [Fact] + public async Task Handle_ArchivesDialogue_WhenAllMessagesAcknowledgedAndDelayPassed() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + // Create a closed dialogue with acknowledged message + var dialogue = new Dialogue("UAL123", "YBBB"); + dialogue.AddUplink( + 1, + null, + "UAL123", + "BN-TSN_FSS", + CpdlcUplinkResponseType.NoResponse, + AlertType.None, + "ROGER", + startTime); // NoResponse uplinks are self-closing and auto-acknowledged + await repository.Add(dialogue, CancellationToken.None); + + var handler = new ArchiveCompletedDialoguesRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time beyond archive delay (10 seconds) + clock.SetUtcNow(startTime.AddSeconds(15)); + await handler.Handle(new ArchiveCompletedDialoguesRequest(), CancellationToken.None); + + // Assert + Assert.True(dialogue.IsArchived); + Assert.Single(publisher.PublishedNotifications); + var notification = Assert.IsType(publisher.PublishedNotifications[0]); + Assert.Equal(dialogue, notification.Dialogue); + } + + [Fact] + public async Task Handle_DoesNotArchive_WhenDelayNotPassed() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + var dialogue = new Dialogue("UAL123", "YBBB"); + dialogue.AddUplink( + 1, + null, + "UAL123", + "BN-TSN_FSS", + CpdlcUplinkResponseType.NoResponse, + AlertType.None, + "ROGER", + startTime); + await repository.Add(dialogue, CancellationToken.None); + + var handler = new ArchiveCompletedDialoguesRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time but not enough (5 seconds < 10 second delay) + clock.SetUtcNow(startTime.AddSeconds(5)); + await handler.Handle(new ArchiveCompletedDialoguesRequest(), CancellationToken.None); + + // Assert + Assert.False(dialogue.IsArchived); + Assert.Empty(publisher.PublishedNotifications); + } + + [Fact] + public async Task Handle_IgnoresOpenDialogues() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + // Create an open dialogue (requires response) + var dialogue = new Dialogue("UAL123", "YBBB"); + dialogue.AddUplink( + 1, + null, + "UAL123", + "BN-TSN_FSS", + CpdlcUplinkResponseType.WilcoUnable, + AlertType.None, + "CLIMB TO FL410", + startTime); + await repository.Add(dialogue, CancellationToken.None); + + var handler = new ArchiveCompletedDialoguesRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time beyond archive delay + clock.SetUtcNow(startTime.AddSeconds(15)); + await handler.Handle(new ArchiveCompletedDialoguesRequest(), CancellationToken.None); + + // Assert - open dialogues should not be archived + Assert.False(dialogue.IsClosed); + Assert.False(dialogue.IsArchived); + Assert.Empty(publisher.PublishedNotifications); + } + + [Fact] + public async Task Handle_IgnoresDialoguesWithoutAcknowledgements() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + // Create a downlink that's closed but not acknowledged + var dialogue = new Dialogue("UAL123", "YBBB"); + dialogue.AddDownlink( + 1, + null, + "UAL123", + CpdlcDownlinkResponseType.NoResponse, + AlertType.None, + "WILCO", + startTime); + await repository.Add(dialogue, CancellationToken.None); + + var handler = new ArchiveCompletedDialoguesRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time beyond archive delay + clock.SetUtcNow(startTime.AddSeconds(15)); + await handler.Handle(new ArchiveCompletedDialoguesRequest(), CancellationToken.None); + + // Assert - unacknowledged dialogues should not be archived + Assert.True(dialogue.IsClosed); + Assert.False(dialogue.IsArchived); + Assert.Empty(publisher.PublishedNotifications); + } +} diff --git a/source/CPDLCServer.Tests/Handlers/ArchiveDialogueCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveDialogueCommandHandlerTests.cs similarity index 92% rename from source/CPDLCServer.Tests/Handlers/ArchiveDialogueCommandHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveDialogueCommandHandlerTests.cs index a2ab340..ec5ea10 100644 --- a/source/CPDLCServer.Tests/Handlers/ArchiveDialogueCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveDialogueCommandHandlerTests.cs @@ -1,10 +1,10 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Tests.Mocks; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Dialogues; public class ArchiveDialogueCommandHandlerTests { @@ -16,7 +16,7 @@ public async Task Handle_ArchivesClosedDialogue() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.NoResponse, @@ -43,7 +43,7 @@ public async Task Handle_AcknowledgesUnacknowledgedDownlinks_WhenArchiving() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, @@ -78,7 +78,7 @@ public async Task Handle_DoesNotArchive_WhenDialogueIsOpen() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, @@ -107,7 +107,7 @@ public async Task Handle_IsIdempotent_WhenAlreadyArchived() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.NoResponse, diff --git a/source/CPDLCServer.Tests/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandlerTests.cs new file mode 100644 index 0000000..fc20f17 --- /dev/null +++ b/source/CPDLCServer.Tests/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandlerTests.cs @@ -0,0 +1,258 @@ +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Tests.Mocks; +using Serilog.Core; + +namespace CPDLCServer.Tests.Cpdlc.Dialogues; + +public class CheckMessageTimeoutsRequestHandlerTests +{ + [Fact] + public async Task Handle_MarksPilotLate_WhenUplinkTimesOut() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + // Create an uplink that requires a response + var dialogue = new Dialogue("UAL123", "YBBB"); + var uplink = dialogue.AddUplink( + 1, + null, + "UAL123", + "BN-TSN_FSS", + CpdlcUplinkResponseType.WilcoUnable, + AlertType.None, + "CLIMB TO FL410", + startTime); + await repository.Add(dialogue, CancellationToken.None); + + var handler = new CheckMessageTimeoutsRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time beyond pilot late timeout (2 minutes) + clock.SetUtcNow(startTime.AddMinutes(3)); + await handler.Handle(new CheckMessageTimeoutsRequest(), CancellationToken.None); + + // Assert + Assert.True(uplink.IsPilotLate); + Assert.Single(publisher.PublishedNotifications); + var notification = Assert.IsType(publisher.PublishedNotifications[0]); + Assert.Equal(dialogue, notification.Dialogue); + } + + [Fact] + public async Task Handle_DoesNotMarkPilotLate_WhenTimeoutNotReached() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + var dialogue = new Dialogue("UAL123", "YBBB"); + var uplink = dialogue.AddUplink( + 1, + null, + "UAL123", + "BN-TSN_FSS", + CpdlcUplinkResponseType.WilcoUnable, + AlertType.None, + "CLIMB TO FL410", + startTime); + await repository.Add(dialogue, CancellationToken.None); + + var handler = new CheckMessageTimeoutsRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time but not beyond timeout (1 minute < 2 minute timeout) + clock.SetUtcNow(startTime.AddMinutes(1)); + await handler.Handle(new CheckMessageTimeoutsRequest(), CancellationToken.None); + + // Assert + Assert.False(uplink.IsPilotLate); + Assert.Empty(publisher.PublishedNotifications); + } + + [Fact] + public async Task Handle_IgnoresNoResponseUplinks() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + // Create an uplink that doesn't require a response + var dialogue = new Dialogue("UAL123", "YBBB"); + var uplink = dialogue.AddUplink( + 1, + null, + "UAL123", + "BN-TSN_FSS", + CpdlcUplinkResponseType.NoResponse, + AlertType.None, + "ROGER", + startTime); + await repository.Add(dialogue, CancellationToken.None); + + var handler = new CheckMessageTimeoutsRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time beyond timeout + clock.SetUtcNow(startTime.AddMinutes(3)); + await handler.Handle(new CheckMessageTimeoutsRequest(), CancellationToken.None); + + // Assert - should not be marked late since no response is needed + Assert.False(uplink.IsPilotLate); + Assert.Empty(publisher.PublishedNotifications); + } + + [Fact] + public async Task Handle_MarksControllerLate_WhenDownlinkTimesOut() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + // Create a downlink that requires a response + var dialogue = new Dialogue("UAL123", "YBBB"); + var downlink = dialogue.AddDownlink( + 1, + null, + "UAL123", + CpdlcDownlinkResponseType.ResponseRequired, + AlertType.None, + "REQUEST CLIMB FL410", + startTime); + await repository.Add(dialogue, CancellationToken.None); + + var handler = new CheckMessageTimeoutsRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time beyond controller late timeout (2 minutes) + clock.SetUtcNow(startTime.AddMinutes(3)); + await handler.Handle(new CheckMessageTimeoutsRequest(), CancellationToken.None); + + // Assert + Assert.True(downlink.IsControllerLate); + Assert.Single(publisher.PublishedNotifications); + var notification = Assert.IsType(publisher.PublishedNotifications[0]); + Assert.Equal(dialogue, notification.Dialogue); + } + + [Fact] + public async Task Handle_IgnoresClosedMessages() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + var dialogue = new Dialogue("UAL123", "YBBB"); + var uplink = dialogue.AddUplink( + 1, + null, + "UAL123", + "BN-TSN_FSS", + CpdlcUplinkResponseType.WilcoUnable, + AlertType.None, + "CLIMB TO FL410", + startTime); + + // Close the message + uplink.Close(startTime); + + await repository.Add(dialogue, CancellationToken.None); + + var handler = new CheckMessageTimeoutsRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time beyond timeout + clock.SetUtcNow(startTime.AddMinutes(3)); + await handler.Handle(new CheckMessageTimeoutsRequest(), CancellationToken.None); + + // Assert - closed messages should not be marked late + Assert.False(uplink.IsPilotLate); + Assert.Empty(publisher.PublishedNotifications); + } + + [Fact] + public async Task Handle_IgnoresClosedDialogues() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + // Create a self-closing uplink (NoResponse) + var dialogue = new Dialogue("UAL123", "YBBB"); + dialogue.AddUplink( + 1, + null, + "UAL123", + "BN-TSN_FSS", + CpdlcUplinkResponseType.NoResponse, + AlertType.None, + "ROGER", + startTime); + await repository.Add(dialogue, CancellationToken.None); + + var handler = new CheckMessageTimeoutsRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time beyond timeout + clock.SetUtcNow(startTime.AddMinutes(3)); + await handler.Handle(new CheckMessageTimeoutsRequest(), CancellationToken.None); + + // Assert - closed dialogues should be skipped + Assert.True(dialogue.IsClosed); + Assert.Empty(publisher.PublishedNotifications); + } + + [Fact] + public async Task Handle_HandlesMultipleDialogues() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + // Create multiple dialogues with different aircraft + var dialogue1 = new Dialogue("UAL123", "YBBB"); + var uplink1 = dialogue1.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB", startTime); + + var dialogue2 = new Dialogue("DAL456", "YBBB"); + var uplink2 = dialogue2.AddUplink(2, null, "DAL456", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "DESCEND", startTime); + + await repository.Add(dialogue1, CancellationToken.None); + await repository.Add(dialogue2, CancellationToken.None); + + var handler = new CheckMessageTimeoutsRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time beyond timeout + clock.SetUtcNow(startTime.AddMinutes(3)); + await handler.Handle(new CheckMessageTimeoutsRequest(), CancellationToken.None); + + // Assert - both should be marked late + Assert.True(uplink1.IsPilotLate); + Assert.True(uplink2.IsPilotLate); + Assert.Equal(2, publisher.PublishedNotifications.Count); + } +} diff --git a/source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueRepositoryTests.cs b/source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueRepositoryTests.cs new file mode 100644 index 0000000..154f961 --- /dev/null +++ b/source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueRepositoryTests.cs @@ -0,0 +1,254 @@ +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Tests.Mocks; + +namespace CPDLCServer.Tests.Cpdlc.Dialogues; + +public class DialogueRepositoryTests +{ + static readonly DateTimeOffset Start = new(2026, 10, 13, 12, 0, 0, TimeSpan.Zero); + + [Fact] + public async Task FindById_ReturnsSavedDialogueWithMessagesInOrder() + { + // Arrange + using var database = new TestDatabase(); + var dialogue = new Dialogue("UAL123", "YBBB"); + dialogue.AddDownlink(7, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST DESCENT FL350", Start); + dialogue.AddUplink(1, 7, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "DESCEND TO FL350", Start.AddMinutes(1)); + dialogue.AddDownlink(8, 1, "UAL123", CpdlcDownlinkResponseType.NoResponse, AlertType.None, "WILCO", Start.AddMinutes(2)); + + await using (var dbContext = database.CreateDbContext()) + { + await new DialogueRepository(dbContext).Add(dialogue, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act + await using var readDbContext = database.CreateDbContext(); + var saved = await new DialogueRepository(readDbContext).FindById(dialogue.Id, CancellationToken.None); + + // Assert + Assert.NotNull(saved); + Assert.Equal("UAL123", saved.AircraftCallsign); + Assert.Equal(dialogue.Opened, saved.Opened); + Assert.Equal(dialogue.Closed, saved.Closed); + Assert.True(saved.IsClosed); + Assert.Equal([7, 1, 8], saved.Messages.Select(m => m.MessageId)); + + var request = Assert.IsType(saved.Messages[0]); + Assert.Equal("REQUEST DESCENT FL350", request.Content); + Assert.Equal(CpdlcDownlinkResponseType.ResponseRequired, request.ResponseType); + Assert.True(request.IsAcknowledged); + + var clearance = Assert.IsType(saved.Messages[1]); + Assert.Equal("DESCEND TO FL350", clearance.Content); + Assert.Equal("BN-TSN_FSS", clearance.SenderCallsign); + Assert.Equal(CpdlcUplinkResponseType.WilcoUnable, clearance.ResponseType); + Assert.Equal(7, clearance.MessageReference); + Assert.Equal(Start.AddMinutes(2), clearance.Closed); + } + + [Fact] + public async Task Add_MessageToSavedDialogue_SavesMessage() + { + // Arrange + using var database = new TestDatabase(); + var dialogue = new Dialogue("UAL123", "YBBB"); + dialogue.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", Start); + + await using (var dbContext = database.CreateDbContext()) + { + await new DialogueRepository(dbContext).Add(dialogue, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act + await using (var dbContext = database.CreateDbContext()) + { + var saved = await new DialogueRepository(dbContext).FindById(dialogue.Id, CancellationToken.None); + saved!.AddDownlink(5, 1, "UAL123", CpdlcDownlinkResponseType.NoResponse, AlertType.None, "WILCO", Start.AddMinutes(1)); + await dbContext.SaveChangesAsync(); + } + + // Assert + await using var readDbContext = database.CreateDbContext(); + var result = await new DialogueRepository(readDbContext).FindById(dialogue.Id, CancellationToken.None); + Assert.NotNull(result); + Assert.Equal(2, result.Messages.Count); + Assert.True(result.IsClosed); + } + + [Fact] + public async Task FindOpenDialogueByUplink_FindsDialogueAddedInSameUnitOfWork() + { + // Arrange + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var repository = new DialogueRepository(dbContext); + + var dialogue = new Dialogue("UAL123", "YBBB"); + dialogue.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", Start); + await repository.Add(dialogue, CancellationToken.None); + + // Act + var result = await repository.FindOpenDialogueByUplink("UAL123", "YBBB", 1, CancellationToken.None); + + // Assert + Assert.Same(dialogue, result); + } + + [Fact] + public async Task FindOpen_ReturnsOnlyOpenDialogues() + { + // Arrange + using var database = new TestDatabase(); + var open = CreateOpenDialogue("UAL123", Start); + var closed = CreateClosedDialogue("QFA1", Start); + await AddAndSave(database, open, closed); + + // Act + await using var dbContext = database.CreateDbContext(); + var result = await new DialogueRepository(dbContext).FindOpen(CancellationToken.None); + + // Assert + Assert.Equal([open.Id], result.Select(d => d.Id)); + } + + [Fact] + public async Task FindClosedAndNotArchived_ReturnsOnlyClosedDialoguesThatAreNotArchived() + { + // Arrange + using var database = new TestDatabase(); + var open = CreateOpenDialogue("UAL123", Start); + var closed = CreateClosedDialogue("QFA1", Start); + var archived = CreateClosedDialogue("VOZ1", Start); + archived.Archive(Start.AddMinutes(1)); + await AddAndSave(database, open, closed, archived); + + // Act + await using var dbContext = database.CreateDbContext(); + var result = await new DialogueRepository(dbContext).FindClosedAndNotArchived(CancellationToken.None); + + // Assert + Assert.Equal([closed.Id], result.Select(d => d.Id)); + } + + [Fact] + public async Task FindOpenDialogueByUplink_DoesNotFindDialogueWithDifferentStation() + { + // Arrange + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var repository = new DialogueRepository(dbContext); + + var dialogue = new Dialogue("UAL123", "YMMM"); + dialogue.AddUplink(1, null, "UAL123", "ML-IND_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", Start); + await repository.Add(dialogue, CancellationToken.None); + + // Act + var result = await repository.FindOpenDialogueByUplink("UAL123", "YBBB", 1, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task FindOpenForAircraft_ReturnsOnlyOpenDialoguesOfAircraftAndStation() + { + // Arrange + using var database = new TestDatabase(); + var open = CreateOpenDialogue("UAL123", Start); + var closed = CreateClosedDialogue("UAL123", Start); + var otherAircraft = CreateOpenDialogue("QFA1", Start); + var otherStation = new Dialogue("UAL123", "YMMM"); + otherStation.AddUplink(1, null, "UAL123", "ML-IND_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", Start); + await AddAndSave(database, open, closed, otherAircraft, otherStation); + + // Act + await using var dbContext = database.CreateDbContext(); + var result = await new DialogueRepository(dbContext).FindOpenForAircraft("UAL123", "YBBB", CancellationToken.None); + + // Assert + Assert.Equal([open.Id], result.Select(d => d.Id)); + } + + [Fact] + public async Task RemoveOpenedBefore_DeletesOnlyOlderDialoguesAndTheirMessages() + { + // Arrange + using var database = new TestDatabase(); + var older = CreateOpenDialogue("UAL123", Start); + var newer = CreateOpenDialogue("QFA1", Start.AddHours(2)); + await AddAndSave(database, older, newer); + + // Act + int removedCount; + await using (var dbContext = database.CreateDbContext()) + { + removedCount = await new DialogueRepository(dbContext).RemoveOpenedBefore(Start.AddHours(1), CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Assert - the messages of the removed dialogue are deleted by the database + Assert.Equal(1, removedCount); + await using var readDbContext = database.CreateDbContext(); + Assert.Equal([newer.Id], (await new DialogueRepository(readDbContext).All(CancellationToken.None)).Select(d => d.Id)); + Assert.All(readDbContext.Set(), m => Assert.Equal(newer.Id, m.DialogueId)); + } + + [Fact] + public async Task Remove_DeletesDialogueAndMessages() + { + // Arrange + using var database = new TestDatabase(); + var dialogue = new Dialogue("UAL123", "YBBB"); + dialogue.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", Start); + + await using (var dbContext = database.CreateDbContext()) + { + await new DialogueRepository(dbContext).Add(dialogue, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act + await using (var dbContext = database.CreateDbContext()) + { + var repository = new DialogueRepository(dbContext); + var saved = await repository.FindById(dialogue.Id, CancellationToken.None); + await repository.Remove(saved!, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Assert + await using var readDbContext = database.CreateDbContext(); + Assert.Empty(await new DialogueRepository(readDbContext).All(CancellationToken.None)); + Assert.Empty(readDbContext.Set()); + } + + static async Task AddAndSave(TestDatabase database, params Dialogue[] dialogues) + { + await using var dbContext = database.CreateDbContext(); + var repository = new DialogueRepository(dbContext); + + foreach (var dialogue in dialogues) + await repository.Add(dialogue, CancellationToken.None); + + await dbContext.SaveChangesAsync(); + } + + static Dialogue CreateOpenDialogue(string callsign, DateTimeOffset time) + { + var dialogue = new Dialogue(callsign, "YBBB"); + dialogue.AddUplink(1, null, callsign, "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", time); + return dialogue; + } + + static Dialogue CreateClosedDialogue(string callsign, DateTimeOffset time) + { + var dialogue = new Dialogue(callsign, "YBBB"); + dialogue.AddUplink(1, null, callsign, "BN-TSN_FSS", CpdlcUplinkResponseType.NoResponse, AlertType.None, "MONITOR BRISBANE CENTRE 128.6", time); + return dialogue; + } +} diff --git a/source/CPDLCServer.Tests/Model/DialogueTests.cs b/source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueTests.cs similarity index 81% rename from source/CPDLCServer.Tests/Model/DialogueTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueTests.cs index 5fc2035..2f0da2c 100644 --- a/source/CPDLCServer.Tests/Model/DialogueTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueTests.cs @@ -1,6 +1,8 @@ -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; -namespace CPDLCServer.Tests.Model; +namespace CPDLCServer.Tests.Cpdlc.Dialogues; public class DialogueTests { @@ -9,7 +11,7 @@ public void Constructor_AddsFirstMessage() { // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); // Act var downlink = dialogue.AddDownlink( @@ -31,7 +33,7 @@ public void Constructor_SetsOpenedTimeToFirstMessageTime() { // Arrange var time = new DateTimeOffset(2025, 1, 15, 10, 30, 0, TimeSpan.Zero); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); // Act dialogue.AddDownlink( @@ -51,7 +53,7 @@ public void Constructor_SetsOpenedTimeToFirstMessageTime() public void Constructor_SetsCallsignFromParameter() { // Arrange - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); // Act dialogue.AddDownlink( @@ -72,7 +74,7 @@ public void AddMessage_UplinkResponseClosesReferencedDownlink() { // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var downlink = dialogue.AddDownlink( 1, null, @@ -103,7 +105,7 @@ public void AddMessage_DownlinkResponseClosesReferencedUplink() { // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var uplink = dialogue.AddUplink( 1, null, @@ -134,7 +136,7 @@ public void AddMessage_StandbyDownlinkDoesNotCloseUplink() { // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var uplink = dialogue.AddUplink( 1, null, @@ -164,7 +166,7 @@ public void AddMessage_StandbyUplinkDoesNotCloseDownlink() { // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var downlink = dialogue.AddDownlink( 1, null, @@ -195,7 +197,7 @@ public void AddMessage_RequestDeferredUplinkDoesNotCloseDownlink() { // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var downlink = dialogue.AddDownlink( 1, null, @@ -226,7 +228,7 @@ public void Dialogue_ClosesWhenAllMessagesAreClosed() { // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink( 1, null, @@ -257,7 +259,7 @@ public void Dialogue_RemainsOpenWhenSomeMessagesAreOpen() { // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var downlink = dialogue.AddDownlink( 1, null, @@ -289,7 +291,7 @@ public void Dialogue_MessageRequiringNoResponseIsSelfClosing() { // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); // Act var downlink = dialogue.AddDownlink( @@ -313,7 +315,7 @@ public void Dialogue_MultipleMessagesAndResponses() // Arrange - Simulate a realistic CPDLC exchange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); // Pilot requests climb var downlink1 = dialogue.AddDownlink( @@ -378,7 +380,7 @@ public void Dialogue_LogonRequestAndAcceptanceClosesImmediately() // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); // Pilot sends logon request var logonRequest = dialogue.AddDownlink( @@ -412,4 +414,37 @@ public void Dialogue_LogonRequestAndAcceptanceClosesImmediately() Assert.True(dialogue.IsArchived); // Dialogue is auto-archived with LOGON ACCEPTED Assert.Equal(logonAccepted.Sent, dialogue.Archived); } + + [Fact] + public void AddMessage_WithEarlierTime_IsPlacedByTime() + { + // Arrange + var time = new DateTimeOffset(2025, 1, 15, 10, 30, 0, TimeSpan.Zero); + var dialogue = new Dialogue("UAL123", "YBBB"); + dialogue.AddDownlink(1, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST CLIMB FL410", time); + dialogue.AddDownlink(3, null, "UAL123", CpdlcDownlinkResponseType.NoResponse, AlertType.None, "FREE TEXT", time.AddMinutes(2)); + + // Act + dialogue.AddDownlink(2, null, "UAL123", CpdlcDownlinkResponseType.NoResponse, AlertType.None, "FREE TEXT", time.AddMinutes(1)); + + // Assert + Assert.Equal([1, 2, 3], dialogue.Messages.Select(m => m.MessageId)); + Assert.Equal([0, 1, 2], dialogue.Messages.Select(m => m.Position)); + } + + [Fact] + public void AddMessage_WithEarlierTimeThanReferencedMessage_IsPlacedAfterReferencedMessage() + { + // Arrange - the reply has an earlier time than the request, for example because of a clock difference + var time = new DateTimeOffset(2025, 1, 15, 10, 30, 0, TimeSpan.Zero); + var dialogue = new Dialogue("UAL123", "YBBB"); + dialogue.AddDownlink(7, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST CLIMB FL410", time); + + // Act + dialogue.AddUplink(1, 7, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", time.AddSeconds(-5)); + + // Assert + Assert.Equal([7, 1], dialogue.Messages.Select(m => m.MessageId)); + Assert.Equal([0, 1], dialogue.Messages.Select(m => m.Position)); + } } diff --git a/source/CPDLCServer.Tests/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandlerTests.cs new file mode 100644 index 0000000..ff9d242 --- /dev/null +++ b/source/CPDLCServer.Tests/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandlerTests.cs @@ -0,0 +1,63 @@ +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Settings; +using CPDLCServer.Tests.Mocks; +using Serilog.Core; + +namespace CPDLCServer.Tests.Cpdlc.Dialogues; + +public class PurgeExpiredCpdlcDataRequestHandlerTests +{ + [Fact] + public async Task Handle_RemovesDialoguesOpenedMoreThan24HoursAgo() + { + // Arrange + var clock = new TestClock(); + var dialogueRepository = new TestDialogueRepository(); + var settingsProvider = new TestServerSettingsProvider(new ServerSettings { DialogueRetentionHours = 24 }); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + var oldDialogue = new Dialogue("UAL123", "YBBB"); + oldDialogue.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", startTime); + var newDialogue = new Dialogue("QFA1", "YBBB"); + newDialogue.AddUplink(1, null, "QFA1", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", startTime.AddHours(2)); + await dialogueRepository.Add(oldDialogue, CancellationToken.None); + await dialogueRepository.Add(newDialogue, CancellationToken.None); + + var handler = new PurgeExpiredCpdlcDataRequestHandler(dialogueRepository, settingsProvider, clock, Logger.None); + + // Act - advance time beyond the purge timeout (24 hours) for the old dialogue only + clock.SetUtcNow(startTime.AddHours(25)); + await handler.Handle(new PurgeExpiredCpdlcDataRequest(), CancellationToken.None); + + // Assert + Assert.Equal([newDialogue], await dialogueRepository.All(CancellationToken.None)); + } + + [Fact] + public async Task Handle_UsesDialogueRetentionSetting() + { + // Arrange + var clock = new TestClock(); + var dialogueRepository = new TestDialogueRepository(); + var settingsProvider = new TestServerSettingsProvider(new ServerSettings { DialogueRetentionHours = 2 }); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + var dialogue = new Dialogue("UAL123", "YBBB"); + dialogue.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", startTime); + await dialogueRepository.Add(dialogue, CancellationToken.None); + + var handler = new PurgeExpiredCpdlcDataRequestHandler(dialogueRepository, settingsProvider, clock, Logger.None); + + // Act - advance time beyond the configured retention (2 hours) + clock.SetUtcNow(startTime.AddHours(3)); + await handler.Handle(new PurgeExpiredCpdlcDataRequest(), CancellationToken.None); + + // Assert + Assert.Empty(await dialogueRepository.All(CancellationToken.None)); + } +} diff --git a/source/CPDLCServer.Tests/Handlers/AcknowledgeDownlinkCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandlerTests.cs similarity index 94% rename from source/CPDLCServer.Tests/Handlers/AcknowledgeDownlinkCommandHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandlerTests.cs index 108b715..7b14b50 100644 --- a/source/CPDLCServer.Tests/Handlers/AcknowledgeDownlinkCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandlerTests.cs @@ -1,10 +1,9 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; using CPDLCServer.Tests.Mocks; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Downlinks; public class AcknowledgeDownlinkCommandHandlerTests { @@ -16,7 +15,7 @@ public async Task Handle_AcknowledgesDownlinkMessage() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var downlink = dialogue.AddDownlink( 1, null, @@ -54,7 +53,7 @@ public async Task Handle_PublishesDialogueChangedNotification() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink( 1, null, @@ -91,7 +90,7 @@ public async Task Handle_DoesNotCloseDialogueWhenMessagesAreStillOpen() var publisher = new TestPublisher(); // Create a downlink that requires a response - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var downlink = dialogue.AddDownlink( 1, null, @@ -152,7 +151,7 @@ public async Task Handle_ThrowsWhenDownlinkMessageNotFoundInDialogue() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink( 1, null, diff --git a/source/CPDLCServer.Tests/Handlers/DownlinkReceivedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Downlinks/DownlinkReceivedNotificationHandlerTests.cs similarity index 94% rename from source/CPDLCServer.Tests/Handlers/DownlinkReceivedNotificationHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Downlinks/DownlinkReceivedNotificationHandlerTests.cs index 13708df..b0914c5 100644 --- a/source/CPDLCServer.Tests/Handlers/DownlinkReceivedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Downlinks/DownlinkReceivedNotificationHandlerTests.cs @@ -1,14 +1,16 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Hubs; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Web; using CPDLCServer.Tests.Mocks; using MediatR; using Microsoft.AspNetCore.SignalR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Downlinks; public class DownlinkReceivedNotificationHandlerTests { @@ -26,6 +28,7 @@ static DownlinkReceivedNotificationHandler BuildHandler( controllerRepository, dialogueRepository, hubContext, + new TestUnitOfWork(), Logger.None); [Fact] @@ -37,7 +40,7 @@ public async Task Handle_PublishesDialogueChangedNotification() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var controller1 = new ControllerInfo( @@ -45,13 +48,15 @@ public async Task Handle_PublishesDialogueChangedNotification() "ConnectionId-1", "YBBB", "BN-TSN_FSS", - "1234567"); + "1234567", + "Test Controller"); var controller2 = new ControllerInfo( Guid.NewGuid(), "ConnectionId-2", "YBBB", "BN-OCN_CTR", - "7654321"); + "1234567", + "Test Controller"); await controllerManager.Add(controller1, CancellationToken.None); await controllerManager.Add(controller2, CancellationToken.None); @@ -101,7 +106,7 @@ public async Task Handle_StillCreatesDialogueWhenNoControllersMatch() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var controller = new ControllerInfo( @@ -109,7 +114,8 @@ public async Task Handle_StillCreatesDialogueWhenNoControllersMatch() "ConnectionId-1", "YMMM", "ML-IND_FSS", - "1234567"); + "1234567", + "Test Controller"); await controllerManager.Add(controller, CancellationToken.None); var mediator = Substitute.For(); @@ -154,7 +160,7 @@ public async Task Handle_PromotesAircraftToCurrentDataAuthorityOnFirstDownlink() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.NextDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var controller = new ControllerInfo( @@ -162,7 +168,8 @@ public async Task Handle_PromotesAircraftToCurrentDataAuthorityOnFirstDownlink() "ConnectionId-1", "YBBB", "BN-TSN_FSS", - "1234567"); + "1234567", + "Test Controller"); await controllerManager.Add(controller, CancellationToken.None); var mediator = Substitute.For(); @@ -226,7 +233,7 @@ public async Task Handle_DoesNotPromoteToCurrentDataAuthority_WhenNotCurrentData var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.NextDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var controller = new ControllerInfo( @@ -234,7 +241,8 @@ public async Task Handle_DoesNotPromoteToCurrentDataAuthority_WhenNotCurrentData "ConnectionId-1", "YBBB", "BN-TSN_FSS", - "1234567"); + "1234567", + "Test Controller"); await controllerManager.Add(controller, CancellationToken.None); var mediator = Substitute.For(); @@ -289,7 +297,7 @@ public async Task Handle_UpdatesLastSeen() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.NextDataAuthority); aircraft.RequestLogon(logonTime); aircraft.AcceptLogon(logonTime); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var controller = new ControllerInfo( @@ -297,7 +305,8 @@ public async Task Handle_UpdatesLastSeen() "ConnectionId-1", "YBBB", "BN-TSN_FSS", - "1234567"); + "1234567", + "Test Controller"); await controllerManager.Add(controller, CancellationToken.None); var mediator = Substitute.For(); @@ -345,7 +354,7 @@ public async Task Handle_CreatesNewDialogue_ForDownlinkWithNoReference() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -387,7 +396,7 @@ public async Task Handle_AppendsToExistingDialogue_ForDownlinkWithReference() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -395,7 +404,7 @@ public async Task Handle_AppendsToExistingDialogue_ForDownlinkWithReference() var hubContext = Substitute.For>(); // Create existing dialogue with an uplink - var existingDialogue = new Dialogue("UAL123"); + var existingDialogue = new Dialogue("UAL123", "YBBB"); existingDialogue.AddUplink( 5, null, @@ -444,7 +453,7 @@ public async Task Handle_FallsBackToNewDialogue_WhenNoOpenDialogueMatchesReferen var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -492,7 +501,7 @@ public async Task Handle_DoesNotAppendToClosedDialogue_WhenAircraftReusesMessage var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -500,7 +509,7 @@ public async Task Handle_DoesNotAppendToClosedDialogue_WhenAircraftReusesMessage var hubContext = Substitute.For>(); // Prior session: uplink ID=5 was sent and fully replied to (dialogue is now closed) - var priorDialogue = new Dialogue("UAL123"); + var priorDialogue = new Dialogue("UAL123", "YBBB"); priorDialogue.AddUplink( 5, null, "UAL123", "YBBB", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB FL410", @@ -550,7 +559,7 @@ public async Task Handle_LogoffMessage_TerminatesConnectionAndCreatesDialogue() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -572,7 +581,7 @@ public async Task Handle_LogoffMessage_TerminatesConnectionAndCreatesDialogue() // Assert - connection termination was requested await mediator.Received(1).Send( - Arg.Is(r => r.Callsign == "UAL123" && r.AcarsClientId == "hoppies-ybbb"), + Arg.Is(r => r.Callsign == "UAL123" && r.AcarsConnectionId == "hoppies-ybbb"), Arg.Any()); // Assert - logoff message still created a dialogue for the controller to see @@ -595,7 +604,7 @@ public async Task Handle_LogoffMessage_FromNextDataAuthority_DoesNotPromoteOrNot var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.NextDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerRepository = new TestControllerRepository(); var controller = new ControllerInfo( @@ -603,7 +612,8 @@ public async Task Handle_LogoffMessage_FromNextDataAuthority_DoesNotPromoteOrNot "ConnectionId-1", "YBBB", "BN-TSN_FSS", - "1234567"); + "1234567", + "Test Controller"); await controllerRepository.Add(controller, CancellationToken.None); var dialogueRepository = new TestDialogueRepository(); @@ -636,7 +646,7 @@ await clientProxy.DidNotReceive().SendCoreAsync( // Assert - connection termination was requested await mediator.Received(1).Send( - Arg.Is(r => r.Callsign == "UAL123" && r.AcarsClientId == "hoppies-ybbb"), + Arg.Is(r => r.Callsign == "UAL123" && r.AcarsConnectionId == "hoppies-ybbb"), Arg.Any()); } @@ -651,7 +661,7 @@ public async Task Handle_LogoffMessage_PublishesDialogueBeforeTerminatingConnect var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -708,14 +718,14 @@ public async Task Handle_LogonRequest_DispatchesLogonCommand() // Act await handler.Handle(notification, CancellationToken.None); - // Assert - LogonCommand dispatched with downlink primitives + AcarsClientId + // Assert - LogonCommand dispatched with downlink primitives + AcarsConnectionId await mediator.Received(1).Send( Arg.Is(c => c.DownlinkId == 1 && c.DownlinkMessageReference == null && c.Callsign == "QFA1" && c.DownlinkContent == "REQUEST LOGON" && - c.AcarsClientId == "hoppies-ybbb"), + c.AcarsConnectionId == "hoppies-ybbb"), Arg.Any()); // Notification handler must not have created a dialogue itself - LogonCommandHandler owns it. diff --git a/source/CPDLCServer.Tests/Cpdlc/Motd/SendMotdCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Motd/SendMotdCommandHandlerTests.cs new file mode 100644 index 0000000..10bcc75 --- /dev/null +++ b/source/CPDLCServer.Tests/Cpdlc/Motd/SendMotdCommandHandlerTests.cs @@ -0,0 +1,83 @@ +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Motd; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Tests.Mocks; +using MediatR; +using NSubstitute; +using Serilog.Core; + +namespace CPDLCServer.Tests.Cpdlc.Motd; + +public class SendMotdCommandHandlerTests +{ + readonly TestAircraftRepository _aircraftRepository = new(); + readonly TestAcarsConnectionManager _acarsConnectionManager = new(); + readonly IMediator _mediator = Substitute.For(); + readonly TestClock _clock = new(); + + SendMotdCommandHandler CreateHandler() => new(_aircraftRepository, _acarsConnectionManager, _mediator, Logger.None); + + async Task AddAircraft(string callsign, DataAuthorityState dataAuthorityState) + { + var aircraft = new AircraftConnection(callsign, "hoppies-ybbb", "YBBB", dataAuthorityState); + aircraft.RequestLogon(_clock.UtcNow()); + aircraft.AcceptLogon(_clock.UtcNow()); + await _aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); + } + + [Fact] + public async Task Handle_SendsTheMessageAsFreeTextWithNoResponse() + { + // Arrange + _acarsConnectionManager.AddConfiguration(TestAcarsConnectionManager.CreateConfiguration("YBBB", 10, motd: "WELCOME TO BRISBANE")); + await AddAircraft("UAL123", DataAuthorityState.CurrentDataAuthority); + + // Act + await CreateHandler().Handle(new SendMotdCommand("hoppies-ybbb", "UAL123"), CancellationToken.None); + + // Assert + await _mediator.Received(1).Send( + new BeginDialogueCommand("YBBB", "UAL123", CpdlcUplinkResponseType.NoResponse, "WELCOME TO BRISBANE"), + Arg.Any()); + } + + [Fact] + public async Task Handle_WhenAircraftDisconnected_DoesNotSend() + { + // Arrange + _acarsConnectionManager.AddConfiguration(TestAcarsConnectionManager.CreateConfiguration("YBBB", 10, motd: "WELCOME TO BRISBANE")); + + // Act + await CreateHandler().Handle(new SendMotdCommand("hoppies-ybbb", "UAL123"), CancellationToken.None); + + // Assert + await _mediator.DidNotReceiveWithAnyArgs().Send(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task Handle_WhenNextDataAuthority_DoesNotSend() + { + // Arrange + _acarsConnectionManager.AddConfiguration(TestAcarsConnectionManager.CreateConfiguration("YBBB", 10, motd: "WELCOME TO BRISBANE")); + await AddAircraft("UAL123", DataAuthorityState.NextDataAuthority); + + // Act + await CreateHandler().Handle(new SendMotdCommand("hoppies-ybbb", "UAL123"), CancellationToken.None); + + // Assert + await _mediator.DidNotReceiveWithAnyArgs().Send(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task Handle_WhenTheMessageWasRemoved_DoesNotSend() + { + // Arrange + await AddAircraft("UAL123", DataAuthorityState.CurrentDataAuthority); + + // Act + await CreateHandler().Handle(new SendMotdCommand("hoppies-ybbb", "UAL123"), CancellationToken.None); + + // Assert + await _mediator.DidNotReceiveWithAnyArgs().Send(Arg.Any(), Arg.Any()); + } +} diff --git a/source/CPDLCServer.Tests/Handlers/AcknowledgeUplinkCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Uplinks/AcknowledgeUplinkCommandHandlerTests.cs similarity index 94% rename from source/CPDLCServer.Tests/Handlers/AcknowledgeUplinkCommandHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Uplinks/AcknowledgeUplinkCommandHandlerTests.cs index d337c1e..b73a9d9 100644 --- a/source/CPDLCServer.Tests/Handlers/AcknowledgeUplinkCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Uplinks/AcknowledgeUplinkCommandHandlerTests.cs @@ -1,10 +1,10 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Tests.Mocks; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Uplinks; public class AcknowledgeUplinkCommandHandlerTests { @@ -16,7 +16,7 @@ public async Task Handle_ClosesUplinkMessageManually() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var uplink = dialogue.AddUplink( 1, null, @@ -57,7 +57,7 @@ public async Task Handle_PublishesDialogueChangedNotification() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, @@ -95,7 +95,7 @@ public async Task Handle_ClosesDialogueWhenAllMessagesAreClosed() var publisher = new TestPublisher(); // Create an uplink that requires a response - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var uplink = dialogue.AddUplink( 1, null, @@ -135,7 +135,7 @@ public async Task Handle_KeepsDialogueOpenWhenOtherMessagesAreStillOpen() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var uplink1 = dialogue.AddUplink( 1, null, @@ -211,7 +211,7 @@ public async Task Handle_ThrowsWhenUplinkMessageNotFoundInDialogue() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, @@ -246,7 +246,7 @@ public async Task Handle_OnlyFindsUplinkMessages() var publisher = new TestPublisher(); // Create a dialogue with a downlink (not an uplink) - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink( 1, null, diff --git a/source/CPDLCServer.Tests/Handlers/BeginDialogueCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Uplinks/BeginDialogueCommandHandlerTests.cs similarity index 73% rename from source/CPDLCServer.Tests/Handlers/BeginDialogueCommandHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Uplinks/BeginDialogueCommandHandlerTests.cs index ef57462..b0bb757 100644 --- a/source/CPDLCServer.Tests/Handlers/BeginDialogueCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Uplinks/BeginDialogueCommandHandlerTests.cs @@ -1,12 +1,12 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Uplinks; public class BeginDialogueCommandHandlerTests { @@ -14,7 +14,7 @@ public class BeginDialogueCommandHandlerTests public async Task Handle_CreatesNewDialogue() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -24,10 +24,10 @@ public async Task Handle_CreatesNewDialogue() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new BeginDialogueCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); var command = new BeginDialogueCommand("BN-TSN_FSS", "UAL123", CpdlcUplinkResponseType.WilcoUnable, "CLIMB TO FL410"); @@ -47,7 +47,7 @@ public async Task Handle_UplinkHasNullMessageReference() { // A dialogue begun by the controller is never a reply - MessageReference must be null. // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -57,10 +57,10 @@ public async Task Handle_UplinkHasNullMessageReference() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new BeginDialogueCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); var command = new BeginDialogueCommand("BN-TSN_FSS", "UAL123", CpdlcUplinkResponseType.WilcoUnable, "CLIMB TO FL410"); @@ -74,10 +74,10 @@ public async Task Handle_UplinkHasNullMessageReference() } [Fact] - public async Task Handle_SendsUplinkViaAcarsClient() + public async Task Handle_SendsUplinkViaAcarsConnection() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -87,10 +87,10 @@ public async Task Handle_SendsUplinkViaAcarsClient() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new BeginDialogueCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); var command = new BeginDialogueCommand("BN-TSN_FSS", "UAL123", CpdlcUplinkResponseType.WilcoUnable, "CLIMB TO FL410"); @@ -98,17 +98,17 @@ public async Task Handle_SendsUplinkViaAcarsClient() await handler.Handle(command, CancellationToken.None); // Assert - var client = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Single(client.SentMessages); - Assert.Equal("UAL123", client.SentMessages[0].Recipient); - Assert.Equal("CLIMB TO FL410", client.SentMessages[0].Content); + var acarsConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Single(acarsConnection.SentMessages); + Assert.Equal("UAL123", acarsConnection.SentMessages[0].Recipient); + Assert.Equal("CLIMB TO FL410", acarsConnection.SentMessages[0].Content); } [Fact] public async Task Handle_PublishesDialogueChangedNotification() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -118,10 +118,10 @@ public async Task Handle_PublishesDialogueChangedNotification() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new BeginDialogueCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); var command = new BeginDialogueCommand("BN-TSN_FSS", "UAL123", CpdlcUplinkResponseType.WilcoUnable, "CLIMB TO FL410"); @@ -136,7 +136,7 @@ public async Task Handle_PublishesDialogueChangedNotification() public async Task Handle_ThrowsWhenAircraftNotConnected() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -146,7 +146,7 @@ public async Task Handle_ThrowsWhenAircraftNotConnected() // No aircraft added var handler = new BeginDialogueCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); var command = new BeginDialogueCommand("BN-TSN_FSS", "UAL123", CpdlcUplinkResponseType.WilcoUnable, "CLIMB TO FL410"); diff --git a/source/CPDLCServer.Tests/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommandHandlerTests.cs new file mode 100644 index 0000000..77f0e27 --- /dev/null +++ b/source/CPDLCServer.Tests/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommandHandlerTests.cs @@ -0,0 +1,45 @@ +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Tests.Mocks; +using Serilog.Core; + +namespace CPDLCServer.Tests.Cpdlc.Uplinks; + +public class MarkUplinkTransmissionFailedCommandHandlerTests +{ + [Fact] + public async Task Handle_MarksUplinkAsFailedAndPublishesDialogueChanged() + { + // Arrange + var dialogueRepository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var dialogue = new Dialogue("UAL123", "YBBB"); + var uplink = dialogue.AddUplink(3, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", DateTimeOffset.UtcNow); + await dialogueRepository.Add(dialogue, CancellationToken.None); + + var handler = new MarkUplinkTransmissionFailedCommandHandler(dialogueRepository, publisher, Logger.None); + + // Act + await handler.Handle(new MarkUplinkTransmissionFailedCommand(dialogue.Id, 3), CancellationToken.None); + + // Assert + Assert.True(uplink.DidTransmissionFail); + var notification = Assert.Single(publisher.PublishedNotifications.OfType()); + Assert.Same(dialogue, notification.Dialogue); + } + + [Fact] + public async Task Handle_DialogueNotFound_DoesNothing() + { + // Arrange + var publisher = new TestPublisher(); + var handler = new MarkUplinkTransmissionFailedCommandHandler(new TestDialogueRepository(), publisher, Logger.None); + + // Act + await handler.Handle(new MarkUplinkTransmissionFailedCommand(Guid.NewGuid(), 3), CancellationToken.None); + + // Assert + Assert.Empty(publisher.PublishedNotifications); + } +} diff --git a/source/CPDLCServer.Tests/Cpdlc/Uplinks/MessageIdProviderTests.cs b/source/CPDLCServer.Tests/Cpdlc/Uplinks/MessageIdProviderTests.cs new file mode 100644 index 0000000..a3b9805 --- /dev/null +++ b/source/CPDLCServer.Tests/Cpdlc/Uplinks/MessageIdProviderTests.cs @@ -0,0 +1,132 @@ +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Tests.Mocks; + +namespace CPDLCServer.Tests.Cpdlc.Uplinks; + +public class MessageIdProviderTests +{ + [Fact] + public async Task GetNextMessageId_FirstCall_ReturnsOne() + { + // Arrange + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var provider = new MessageIdProvider(dbContext); + + // Act + var messageId = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); + + // Assert + Assert.Equal(1, messageId); + } + + [Fact] + public async Task GetNextMessageId_SequentialCalls_IncrementsForSamePair() + { + // Arrange + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var provider = new MessageIdProvider(dbContext); + + // Act + var id1 = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); + var id2 = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); + var id3 = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); + + // Assert + Assert.Equal(1, id1); + Assert.Equal(2, id2); + Assert.Equal(3, id3); + } + + [Fact] + public async Task GetNextMessageId_DifferentCallsigns_MaintainsSeparateSequences() + { + // Arrange + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var provider = new MessageIdProvider(dbContext); + + // Act + var ual1 = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); + var dal1 = await provider.GetNextMessageId("YBBB", "DAL456", CancellationToken.None); + var ual2 = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); + var dal2 = await provider.GetNextMessageId("YBBB", "DAL456", CancellationToken.None); + + // Assert + Assert.Equal(1, ual1); + Assert.Equal(1, dal1); + Assert.Equal(2, ual2); + Assert.Equal(2, dal2); + } + + [Fact] + public async Task GetNextMessageId_DifferentStations_MaintainsSeparateSequences() + { + // Arrange + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var provider = new MessageIdProvider(dbContext); + + // Act + var ybbb1 = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); + var ymmm1 = await provider.GetNextMessageId("YMMM", "UAL123", CancellationToken.None); + var ybbb2 = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); + var ymmm2 = await provider.GetNextMessageId("YMMM", "UAL123", CancellationToken.None); + + // Assert + Assert.Equal(1, ybbb1); + Assert.Equal(1, ymmm1); + Assert.Equal(2, ybbb2); + Assert.Equal(2, ymmm2); + } + + [Fact] + public async Task GetNextMessageId_AfterRestart_ContinuesSequence() + { + // Arrange + using var database = new TestDatabase(); + + await using (var dbContext = database.CreateDbContext()) + { + var provider = new MessageIdProvider(dbContext); + await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); + await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act + await using var newDbContext = database.CreateDbContext(); + var newProvider = new MessageIdProvider(newDbContext); + var messageId = await newProvider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); + + // Assert + Assert.Equal(3, messageId); + } + + [Fact] + public async Task Remove_NextConnectionStartsAtFirstId() + { + // Arrange + using var database = new TestDatabase(); + await using (var dbContext = database.CreateDbContext()) + { + var provider = new MessageIdProvider(dbContext); + await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); + await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act + await using (var dbContext = database.CreateDbContext()) + { + await new MessageIdProvider(dbContext).Remove("YBBB", "UAL123", CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Assert + await using var readDbContext = database.CreateDbContext(); + Assert.Empty(readDbContext.MessageIdSequences); + Assert.Equal(1, await new MessageIdProvider(readDbContext).GetNextMessageId("YBBB", "UAL123", CancellationToken.None)); + } +} diff --git a/source/CPDLCServer.Tests/Handlers/ReplyToDownlinkCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Uplinks/ReplyToDownlinkCommandHandlerTests.cs similarity index 76% rename from source/CPDLCServer.Tests/Handlers/ReplyToDownlinkCommandHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Uplinks/ReplyToDownlinkCommandHandlerTests.cs index 02336d8..a79109a 100644 --- a/source/CPDLCServer.Tests/Handlers/ReplyToDownlinkCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Uplinks/ReplyToDownlinkCommandHandlerTests.cs @@ -1,12 +1,13 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Uplinks; public class ReplyToDownlinkCommandHandlerTests { @@ -17,7 +18,7 @@ public async Task Handle_AppendsUplinkToExistingDialogue_NotCreatingNew() // to the existing dialogue, not start a new one. // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -27,9 +28,9 @@ public async Task Handle_AppendsUplinkToExistingDialogue_NotCreatingNew() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink( 7, null, @@ -41,7 +42,7 @@ public async Task Handle_AppendsUplinkToExistingDialogue_NotCreatingNew() await dialogueRepository.Add(dialogue, CancellationToken.None); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); var command = new ReplyToDownlinkCommand("BN-TSN_FSS", dialogue.Id, 7, CpdlcUplinkResponseType.WilcoUnable, "DESCEND FL350"); @@ -64,7 +65,7 @@ public async Task Handle_UplinkMessageReferenceMatchesDownlinkId() // The outgoing uplink must carry the downlink's MessageId as its MessageReference // so the aircraft knows which of its messages is being replied to. // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -74,14 +75,14 @@ public async Task Handle_UplinkMessageReferenceMatchesDownlinkId() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink(7, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST DESCENT FL350", clock.UtcNow()); await dialogueRepository.Add(dialogue, CancellationToken.None); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); // Act await handler.Handle( @@ -101,7 +102,7 @@ public async Task Handle_UsesDialogueId_WhenMultipleDialoguesHaveSameDownlinkMes // same MessageId. The fix uses DialogueId for unambiguous lookup. // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -111,19 +112,19 @@ public async Task Handle_UsesDialogueId_WhenMultipleDialoguesHaveSameDownlinkMes var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); // Both dialogues have a downlink with MessageId=1 (aircraft re-used the same ID) - var dialogueA = new Dialogue("UAL123"); + var dialogueA = new Dialogue("UAL123", "YBBB"); dialogueA.AddDownlink(1, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST CLIMB FL350", clock.UtcNow()); await dialogueRepository.Add(dialogueA, CancellationToken.None); - var dialogueB = new Dialogue("UAL123"); + var dialogueB = new Dialogue("UAL123", "YBBB"); dialogueB.AddDownlink(1, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST DESCENT FL250", clock.UtcNow()); await dialogueRepository.Add(dialogueB, CancellationToken.None); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); // Controller explicitly replies to dialogueA await handler.Handle( @@ -136,10 +137,10 @@ await handler.Handle( } [Fact] - public async Task Handle_SendsUplinkViaAcarsClient() + public async Task Handle_SendsUplinkViaAcarsConnection() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -149,14 +150,14 @@ public async Task Handle_SendsUplinkViaAcarsClient() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink(7, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST DESCENT FL350", clock.UtcNow()); await dialogueRepository.Add(dialogue, CancellationToken.None); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); // Act await handler.Handle( @@ -164,18 +165,18 @@ await handler.Handle( CancellationToken.None); // Assert - var client = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Single(client.SentMessages); - Assert.Equal("UAL123", client.SentMessages[0].Recipient); - Assert.Equal("DESCEND FL350", client.SentMessages[0].Content); - Assert.Equal(7, client.SentMessages[0].MessageReference); + var acarsConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Single(acarsConnection.SentMessages); + Assert.Equal("UAL123", acarsConnection.SentMessages[0].Recipient); + Assert.Equal("DESCEND FL350", acarsConnection.SentMessages[0].Content); + Assert.Equal(7, acarsConnection.SentMessages[0].MessageReference); } [Fact] public async Task Handle_PublishesDialogueChangedNotification() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -185,14 +186,14 @@ public async Task Handle_PublishesDialogueChangedNotification() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink(7, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST DESCENT FL350", clock.UtcNow()); await dialogueRepository.Add(dialogue, CancellationToken.None); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); // Act await handler.Handle( @@ -209,7 +210,7 @@ await mediator.Received(1).Publish( public async Task Handle_ThrowsWhenDialogueNotFound() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -217,7 +218,7 @@ public async Task Handle_ThrowsWhenDialogueNotFound() var aircraftRepository = new TestAircraftRepository(); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); // Act & Assert await Assert.ThrowsAsync(() => @@ -230,7 +231,7 @@ await Assert.ThrowsAsync(() => public async Task Handle_ThrowsWhenAircraftNotConnected() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -238,12 +239,12 @@ public async Task Handle_ThrowsWhenAircraftNotConnected() var aircraftRepository = new TestAircraftRepository(); // Dialogue exists but aircraft is not in the repository - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink(1, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST DESCENT", clock.UtcNow()); await dialogueRepository.Add(dialogue, CancellationToken.None); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); // Act & Assert await Assert.ThrowsAsync(() => diff --git a/source/CPDLCServer.Tests/Cpdlc/Uplinks/UplinkTransmitterTests.cs b/source/CPDLCServer.Tests/Cpdlc/Uplinks/UplinkTransmitterTests.cs new file mode 100644 index 0000000..e10fad7 --- /dev/null +++ b/source/CPDLCServer.Tests/Cpdlc/Uplinks/UplinkTransmitterTests.cs @@ -0,0 +1,63 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Infrastructure; +using CPDLCServer.Tests.Mocks; +using MediatR; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using Serilog.Core; + +namespace CPDLCServer.Tests.Cpdlc.Uplinks; + +public class UplinkTransmitterTests +{ + static UplinkMessage CreateUplink(Guid dialogueId) => new( + dialogueId, + 3, + null, + "UAL123", + "BN-TSN_FSS", + CpdlcUplinkResponseType.WilcoUnable, + AlertType.None, + "CLIMB TO FL410", + DateTimeOffset.UtcNow); + + [Fact] + public void TransmitAfterCommit_SendSucceeds_DoesNotMarkUplinkAsFailed() + { + // Arrange + var acarsConnection = new TestAcarsConnection("YBBB"); + var unitOfWorkMediator = Substitute.For(); + var transmitter = new UplinkTransmitter(new TestUnitOfWork(), unitOfWorkMediator, Logger.None); + var uplink = CreateUplink(Guid.NewGuid()); + + // Act + transmitter.TransmitAfterCommit(acarsConnection, uplink); + + // Assert + Assert.Equal([uplink], acarsConnection.SentMessages); + unitOfWorkMediator.DidNotReceive().Send(Arg.Any(), Arg.Any()); + } + + [Fact] + public void TransmitAfterCommit_SendFails_MarksUplinkAsFailedThenThrows() + { + // Arrange + var acarsConnection = Substitute.For(); + acarsConnection.Send(Arg.Any(), Arg.Any()) + .ThrowsAsync(new HttpRequestException("Hoppie is not available")); + + var unitOfWorkMediator = Substitute.For(); + var transmitter = new UplinkTransmitter(new TestUnitOfWork(), unitOfWorkMediator, Logger.None); + var dialogueId = Guid.NewGuid(); + + // Act + Assert.Throws(() => transmitter.TransmitAfterCommit(acarsConnection, CreateUplink(dialogueId))); + + // Assert + unitOfWorkMediator.Received(1).Send( + new MarkUplinkTransmissionFailedCommand(dialogueId, 3), + Arg.Any()); + } +} diff --git a/source/CPDLCServer.Tests/Handlers/GetAtsuSettingsRequestHandlerTests.cs b/source/CPDLCServer.Tests/Handlers/GetAtsuSettingsRequestHandlerTests.cs deleted file mode 100644 index 33c3749..0000000 --- a/source/CPDLCServer.Tests/Handlers/GetAtsuSettingsRequestHandlerTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Tests.Mocks; - -namespace CPDLCServer.Tests.Handlers; - -public class GetAtsuSettingsRequestHandlerTests -{ - [Fact] - public async Task Handle_ReturnsSettingsForStation() - { - // Arrange - var clientManager = new TestClientManager(); - clientManager.AddConfiguration(TestClientManager.CreateConfiguration("NZZO", 27)); - var handler = new GetAtsuSettingsRequestHandler(clientManager); - - // Act - var result = await handler.Handle(new GetAtsuSettingsRequest("NZZO"), CancellationToken.None); - - // Assert - Assert.Equal("NZZO", result.StationId); - Assert.Equal(TimeSpan.FromMinutes(27), result.DefaultAdscReportingInterval); - } - - [Fact] - public async Task Handle_WhenStationNotConfigured_Throws() - { - // Arrange - var handler = new GetAtsuSettingsRequestHandler(new TestClientManager()); - - // Act & Assert - await Assert.ThrowsAnyAsync(() => - handler.Handle(new GetAtsuSettingsRequest("KZAK"), CancellationToken.None)); - } -} diff --git a/source/CPDLCServer.Tests/Handlers/RequestDefaultAdscContractCommandHandlerTests.cs b/source/CPDLCServer.Tests/Handlers/RequestDefaultAdscContractCommandHandlerTests.cs deleted file mode 100644 index ac4bd03..0000000 --- a/source/CPDLCServer.Tests/Handlers/RequestDefaultAdscContractCommandHandlerTests.cs +++ /dev/null @@ -1,97 +0,0 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using CPDLCServer.Tests.Mocks; -using MediatR; -using NSubstitute; -using Serilog.Core; - -namespace CPDLCServer.Tests.Handlers; - -public class RequestDefaultAdscContractCommandHandlerTests -{ - [Fact] - public async Task Handle_SendsDefaultIntervalViaAcarsClientForStation() - { - // Arrange - var clientManager = new TestClientManager(); - var handler = new RequestDefaultAdscContractCommandHandler( - clientManager, new TestAdscContractRepository(), Substitute.For(), new TestClock(), Logger.None); - - // Act - await handler.Handle(new RequestDefaultAdscContractCommand("YMMM", "UAL123"), CancellationToken.None); - - // Assert - TestClientManager sets the YMMM default to 20 minutes - var ybbbClient = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - var ymmmClient = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ymmm", CancellationToken.None); - Assert.Equal(TimeSpan.FromMinutes(20), ymmmClient.RequestedAdscContracts["UAL123"]); - Assert.Empty(ybbbClient.RequestedAdscContracts); - } - - [Fact] - public async Task Handle_WhenNoContractExists_AddsDefaultContract() - { - // Arrange - var contractRepository = new TestAdscContractRepository(); - var mediator = Substitute.For(); - var handler = new RequestDefaultAdscContractCommandHandler( - new TestClientManager(), contractRepository, mediator, new TestClock(), Logger.None); - - // Act - await handler.Handle(new RequestDefaultAdscContractCommand("YBBB", "UAL123"), CancellationToken.None); - - // Assert - TestClientManager sets the YBBB default to 10 minutes - var contract = await contractRepository.Find(new AdscContractKey("UAL123", "YBBB"), CancellationToken.None); - Assert.NotNull(contract); - Assert.Equal(TimeSpan.FromMinutes(10), contract.ReportingInterval); - Assert.Equal(AdscContractState.Sent, contract.DefaultContractState); - - await mediator.Received(1).Publish( - Arg.Is(n => n.Contract == contract), - Arg.Any()); - } - - [Fact] - public async Task Handle_LogsActivity() - { - // Arrange - var clock = new TestClock(); - var contractRepository = new TestAdscContractRepository(); - var handler = new RequestDefaultAdscContractCommandHandler( - new TestClientManager(), contractRepository, Substitute.For(), clock, Logger.None); - - // Act - await handler.Handle(new RequestDefaultAdscContractCommand("YBBB", "UAL123"), CancellationToken.None); - - // Assert - var contract = await contractRepository.Find(new AdscContractKey("UAL123", "YBBB"), CancellationToken.None); - Assert.NotNull(contract); - Assert.Equal(clock.UtcNow(), contract.LastActivity); - } - - [Fact] - public async Task Handle_WhenSelectedContractIsInUse_EndsSelectedContract() - { - // Arrange - var contractRepository = new TestAdscContractRepository(); - var existingContract = new AdscContract("UAL123", "YBBB"); - existingContract.RequestSelectedContract(TimeSpan.FromMinutes(2), DateTimeOffset.UtcNow.AddHours(1)); - existingContract.ReportReceived(); - await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), existingContract, CancellationToken.None); - - var handler = new RequestDefaultAdscContractCommandHandler( - new TestClientManager(), contractRepository, Substitute.For(), new TestClock(), Logger.None); - - // Act - await handler.Handle(new RequestDefaultAdscContractCommand("YBBB", "UAL123"), CancellationToken.None); - - // Assert - var contract = Assert.Single(await contractRepository.All(CancellationToken.None)); - Assert.Same(existingContract, contract); - Assert.Equal(TimeSpan.FromMinutes(10), contract.ReportingInterval); - Assert.Equal(AdscContractState.Sent, contract.DefaultContractState); - Assert.Null(contract.SelectedContractState); - Assert.Null(contract.SelectedContractEnds); - } -} diff --git a/source/CPDLCServer.Tests/Handlers/RequestSelectedAdscContractCommandHandlerTests.cs b/source/CPDLCServer.Tests/Handlers/RequestSelectedAdscContractCommandHandlerTests.cs deleted file mode 100644 index cb871af..0000000 --- a/source/CPDLCServer.Tests/Handlers/RequestSelectedAdscContractCommandHandlerTests.cs +++ /dev/null @@ -1,150 +0,0 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using CPDLCServer.Tests.Mocks; -using MediatR; -using NSubstitute; -using Serilog.Core; - -namespace CPDLCServer.Tests.Handlers; - -public class RequestSelectedAdscContractCommandHandlerTests -{ - [Fact] - public async Task Handle_SendsRequestViaAcarsClientForStation() - { - // Arrange - var clientManager = new TestClientManager(); - var handler = new RequestSelectedAdscContractCommandHandler( - clientManager, new TestAdscContractRepository(), Substitute.For(), new TestClock(), Logger.None); - - var command = new RequestSelectedAdscContractCommand("YBBB", "UAL123", TimeSpan.FromMinutes(5)); - - // Act - await handler.Handle(command, CancellationToken.None); - - // Assert - var ybbbClient = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - var ymmmClient = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ymmm", CancellationToken.None); - Assert.Equal(TimeSpan.FromMinutes(5), ybbbClient.RequestedAdscContracts["UAL123"]); - Assert.Empty(ymmmClient.RequestedAdscContracts); - } - - [Fact] - public async Task Handle_WhenNoContractExists_AddsSelectedContract() - { - // Arrange - var clock = new TestClock(); - var contractRepository = new TestAdscContractRepository(); - var mediator = Substitute.For(); - var handler = new RequestSelectedAdscContractCommandHandler( - new TestClientManager(), contractRepository, mediator, clock, Logger.None); - - var command = new RequestSelectedAdscContractCommand("YBBB", "UAL123", TimeSpan.FromMinutes(5)); - - // Act - await handler.Handle(command, CancellationToken.None); - - // Assert - var contract = await contractRepository.Find(new AdscContractKey("UAL123", "YBBB"), CancellationToken.None); - Assert.NotNull(contract); - Assert.Equal(TimeSpan.FromMinutes(5), contract.ReportingInterval); - Assert.Equal(TimeSpan.FromMinutes(5), contract.SelectedReportingInterval); - Assert.Equal(AdscContractState.Sent, contract.SelectedContractState); - Assert.Null(contract.DefaultContractState); - - await mediator.Received(1).Publish( - Arg.Is(n => n.Contract == contract), - Arg.Any()); - } - - [Fact] - public async Task Handle_SetsEndTimeFromRequestTime() - { - // Arrange - var clock = new TestClock(); - var clientManager = new TestClientManager(); - clientManager.AddConfiguration(TestClientManager.CreateConfiguration("YBBB", 10, selectedAdscContractDuration: 30)); - - var contractRepository = new TestAdscContractRepository(); - var handler = new RequestSelectedAdscContractCommandHandler( - clientManager, contractRepository, Substitute.For(), clock, Logger.None); - - var command = new RequestSelectedAdscContractCommand("YBBB", "UAL123", TimeSpan.FromMinutes(5)); - - // Act - await handler.Handle(command, CancellationToken.None); - - // Assert - var contract = await contractRepository.Find(new AdscContractKey("UAL123", "YBBB"), CancellationToken.None); - Assert.NotNull(contract); - Assert.Equal(clock.UtcNow().AddMinutes(30), contract.SelectedContractEnds); - } - - [Fact] - public async Task Handle_WhenDefaultContractExists_KeepsDefaultContractUntilAccepted() - { - // Arrange - var contractRepository = new TestAdscContractRepository(); - var existingContract = new AdscContract("UAL123", "YBBB"); - existingContract.RequestDefaultContract(TimeSpan.FromMinutes(10)); - existingContract.ReportReceived(); - await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), existingContract, CancellationToken.None); - - var handler = new RequestSelectedAdscContractCommandHandler( - new TestClientManager(), contractRepository, Substitute.For(), new TestClock(), Logger.None); - - var command = new RequestSelectedAdscContractCommand("YBBB", "UAL123", TimeSpan.FromMinutes(2)); - - // Act - await handler.Handle(command, CancellationToken.None); - - // Assert - var contract = Assert.Single(await contractRepository.All(CancellationToken.None)); - Assert.Same(existingContract, contract); - Assert.Equal(TimeSpan.FromMinutes(2), contract.ReportingInterval); - Assert.Equal(AdscContractState.Sent, contract.SelectedContractState); - Assert.Equal(AdscContractState.Accepted, contract.DefaultContractState); - } - - [Fact] - public async Task Handle_WhenIntervalIsLessThanMinimum_ThrowsAndSendsNothing() - { - // Arrange - var clientManager = new TestClientManager(); - var contractRepository = new TestAdscContractRepository(); - var handler = new RequestSelectedAdscContractCommandHandler( - clientManager, contractRepository, Substitute.For(), new TestClock(), Logger.None); - - var command = new RequestSelectedAdscContractCommand("YBBB", "UAL123", TimeSpan.FromSeconds(59)); - - // Act & Assert - await Assert.ThrowsAsync(() => handler.Handle(command, CancellationToken.None)); - - var client = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Empty(client.RequestedAdscContracts); - Assert.Empty(await contractRepository.All(CancellationToken.None)); - } - - [Fact] - public async Task Handle_WhenIntervalIsMinimum_SendsRequest() - { - // Arrange - var clientManager = new TestClientManager(); - var handler = new RequestSelectedAdscContractCommandHandler( - clientManager, new TestAdscContractRepository(), Substitute.For(), new TestClock(), Logger.None); - - var command = new RequestSelectedAdscContractCommand( - "YBBB", - "UAL123", - AdscContract.MinimumReportingInterval); - - // Act - await handler.Handle(command, CancellationToken.None); - - // Assert - var client = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Single(client.RequestedAdscContracts); - } -} diff --git a/source/CPDLCServer.Tests/Handlers/SendConnectionRequestCommandHandlerTests.cs b/source/CPDLCServer.Tests/Handlers/SendConnectionRequestCommandHandlerTests.cs deleted file mode 100644 index d091993..0000000 --- a/source/CPDLCServer.Tests/Handlers/SendConnectionRequestCommandHandlerTests.cs +++ /dev/null @@ -1,103 +0,0 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Tests.Mocks; -using Serilog.Core; - -namespace CPDLCServer.Tests.Handlers; - -public class SendConnectionRequestCommandHandlerTests -{ - [Fact] - public async Task Handle_SendsConnectionRequestUplink() - { - // Arrange - var clientManager = new TestClientManager(); - var messageIdProvider = new TestMessageIdProvider(); - messageIdProvider.SetNextId(5); - var clock = new TestClock(); - - var handler = new SendConnectionRequestCommandHandler(clientManager, messageIdProvider, clock, Logger.None); - - var command = new SendConnectionRequestCommand("UAL123", "YBBB"); - - // Act - await handler.Handle(command, CancellationToken.None); - - // Assert - var client = (TestAcarsClient)await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - var uplink = Assert.Single(client.SentMessages); - Assert.Equal("UAL123", uplink.Recipient); - Assert.Equal("CONNECTION REQUESTED @YBBB@", uplink.Content); - Assert.Equal(5, uplink.MessageId); - Assert.Null(uplink.MessageReference); - Assert.Equal(CpdlcUplinkResponseType.NoResponse, uplink.ResponseType); - Assert.Equal(clock.UtcNow(), uplink.Sent); - } - - [Fact] - public async Task Handle_SendsUplinkViaClientForSelectedStation() - { - // The uplink must go through the ACARS client of the selected ATSU, not another client. - // Arrange - var clientManager = new TestClientManager(); - var messageIdProvider = new TestMessageIdProvider(); - var clock = new TestClock(); - - var handler = new SendConnectionRequestCommandHandler(clientManager, messageIdProvider, clock, Logger.None); - - var command = new SendConnectionRequestCommand("UAL123", "YMMM"); - - // Act - await handler.Handle(command, CancellationToken.None); - - // Assert - var ymmmClient = (TestAcarsClient)await clientManager.GetAcarsClient("hoppies-ymmm", CancellationToken.None); - var ybbbClient = (TestAcarsClient)await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - - var uplink = Assert.Single(ymmmClient.SentMessages); - Assert.Equal("CONNECTION REQUESTED @YMMM@", uplink.Content); - Assert.Empty(ybbbClient.SentMessages); - } - - [Fact] - public async Task Handle_MatchesStationIdIgnoringCase() - { - // Arrange - var clientManager = new TestClientManager(); - var messageIdProvider = new TestMessageIdProvider(); - var clock = new TestClock(); - - var handler = new SendConnectionRequestCommandHandler(clientManager, messageIdProvider, clock, Logger.None); - - var command = new SendConnectionRequestCommand("UAL123", "ybbb"); - - // Act - await handler.Handle(command, CancellationToken.None); - - // Assert - var client = (TestAcarsClient)await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Single(client.SentMessages); - } - - [Fact] - public async Task Handle_ThrowsWhenNoClientForStation() - { - // Arrange - var clientManager = new TestClientManager(); - var messageIdProvider = new TestMessageIdProvider(); - var clock = new TestClock(); - - var handler = new SendConnectionRequestCommandHandler(clientManager, messageIdProvider, clock, Logger.None); - - var command = new SendConnectionRequestCommand("UAL123", "YPPP"); - - // Act & Assert - await Assert.ThrowsAnyAsync(() => handler.Handle(command, CancellationToken.None)); - - var ybbbClient = (TestAcarsClient)await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - var ymmmClient = (TestAcarsClient)await clientManager.GetAcarsClient("hoppies-ymmm", CancellationToken.None); - Assert.Empty(ybbbClient.SentMessages); - Assert.Empty(ymmmClient.SentMessages); - } -} diff --git a/source/CPDLCServer.Tests/Logging/LogAreaTests.cs b/source/CPDLCServer.Tests/Logging/LogAreaTests.cs new file mode 100644 index 0000000..665532d --- /dev/null +++ b/source/CPDLCServer.Tests/Logging/LogAreaTests.cs @@ -0,0 +1,26 @@ +using CPDLCServer.AcarsConnections.Stations; +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Logging; +using CPDLCServer.Settings; +using CPDLCServer.VatsimStatus; + +namespace CPDLCServer.Tests.Logging; + +public class LogAreaTests +{ + [Theory] + [InlineData(typeof(LogonCommand), LogArea.Cpdlc)] + [InlineData(typeof(ExpireAdscReportsRequest), LogArea.Adsc)] + [InlineData(typeof(ProduceVatsimAdscReportsRequest), LogArea.Adsc)] + [InlineData(typeof(RefreshAcarsCallsignsRequest), LogArea.Acars)] + [InlineData(typeof(SaveServerSettingsCommand), LogArea.System)] + public void ForType_UsesTheNamespaceOfTheType(Type type, string expectedArea) + { + // Act + var area = LogArea.ForType(type); + + // Assert + Assert.Equal(expectedArea, area); + } +} diff --git a/source/CPDLCServer.Tests/Logging/LogBufferTests.cs b/source/CPDLCServer.Tests/Logging/LogBufferTests.cs new file mode 100644 index 0000000..29acbd1 --- /dev/null +++ b/source/CPDLCServer.Tests/Logging/LogBufferTests.cs @@ -0,0 +1,133 @@ +using CPDLCServer.Logging; +using Serilog; +using Serilog.Events; + +namespace CPDLCServer.Tests.Logging; + +public class LogBufferTests +{ + [Fact] + public void Add_KeepsOnlyTheMostRecentEntries() + { + // Arrange + var logBuffer = new LogBuffer(capacity: 2); + + // Act + logBuffer.Add(CreateEntry("first")); + logBuffer.Add(CreateEntry("second")); + logBuffer.Add(CreateEntry("third")); + + // Assert + using var subscription = logBuffer.Subscribe(); + Assert.Equal(["second", "third"], subscription.RecentEntries.Select(e => e.Message)); + } + + [Fact] + public void Add_SetsIncreasingSequenceNumbers() + { + // Arrange + var logBuffer = new LogBuffer(); + + // Act + logBuffer.Add(CreateEntry("first")); + logBuffer.Add(CreateEntry("second")); + + // Assert + using var subscription = logBuffer.Subscribe(); + Assert.Equal([1L, 2L], subscription.RecentEntries.Select(e => e.Sequence)); + } + + [Fact] + public void Subscribe_ReceivesNewEntries() + { + // Arrange + var logBuffer = new LogBuffer(); + logBuffer.Add(CreateEntry("before")); + using var subscription = logBuffer.Subscribe(); + + // Act + logBuffer.Add(CreateEntry("after")); + + // Assert + Assert.Equal(["before"], subscription.RecentEntries.Select(e => e.Message)); + Assert.True(subscription.NewEntries.TryRead(out var entry)); + Assert.Equal("after", entry.Message); + Assert.False(subscription.NewEntries.TryRead(out _)); + } + + [Fact] + public void Dispose_StopsTheSubscription() + { + // Arrange + var logBuffer = new LogBuffer(); + var subscription = logBuffer.Subscribe(); + + // Act + subscription.Dispose(); + logBuffer.Add(CreateEntry("after")); + + // Assert + Assert.False(subscription.NewEntries.TryRead(out _)); + Assert.True(subscription.NewEntries.Completion.IsCompleted); + } + + [Fact] + public void Sink_WritesTheSameTextAsTheConsole() + { + // Arrange + var logBuffer = new LogBuffer(); + using var logger = new LoggerConfiguration() + .MinimumLevel.Verbose() + .WriteTo.Sink(new InMemoryLogBufferSink(logBuffer)) + .CreateLogger(); + + // Act + logger.ForContext("Station", "YBBB").Warning("Aircraft {Callsign} not seen", "UAL123"); + logger.Error(new InvalidOperationException("Send failed"), "Error sending message"); + + // Assert + using var subscription = logBuffer.Subscribe(); + var warning = subscription.RecentEntries[0]; + Assert.Equal(nameof(LogEventLevel.Warning), warning.Level); + Assert.Equal("WRN", warning.LevelCode); + Assert.Equal("Aircraft UAL123 not seen", warning.Message); + Assert.Null(warning.Exception); + + var error = subscription.RecentEntries[1]; + Assert.Equal("ERR", error.LevelCode); + Assert.Contains("Send failed", error.Exception); + } + + [Fact] + public void Sink_ReadsTheAreaAndTheAcarsConnection() + { + // Arrange + var logBuffer = new LogBuffer(); + using var logger = new LoggerConfiguration() + .MinimumLevel.Verbose() + .WriteTo.Sink(new InMemoryLogBufferSink(logBuffer)) + .CreateLogger(); + + // Act + logger + .ForContext(LogArea.PropertyName, LogArea.Acars) + .ForContext(LogArea.AcarsConnectionIdPropertyName, "Hoppies/YBBB") + .Information("Polling for messages"); + logger.Information("No area"); + + // Assert + using var subscription = logBuffer.Subscribe(); + var acarsEntry = subscription.RecentEntries[0]; + Assert.Equal(LogArea.Acars, acarsEntry.Area); + Assert.Equal("Hoppies/YBBB", acarsEntry.AcarsConnectionId); + + var systemEntry = subscription.RecentEntries[1]; + Assert.Equal(LogArea.System, systemEntry.Area); + Assert.Null(systemEntry.AcarsConnectionId); + } + + static LogEntry CreateEntry(string message) + { + return new LogEntry(0, "12:00:00", "Information", "INF", LogArea.System, null, message, null); + } +} diff --git a/source/CPDLCServer.Tests/Mocks/TestAcarsClient.cs b/source/CPDLCServer.Tests/Mocks/TestAcarsConnection.cs similarity index 90% rename from source/CPDLCServer.Tests/Mocks/TestAcarsClient.cs rename to source/CPDLCServer.Tests/Mocks/TestAcarsConnection.cs index de2d30e..dbec1db 100644 --- a/source/CPDLCServer.Tests/Mocks/TestAcarsClient.cs +++ b/source/CPDLCServer.Tests/Mocks/TestAcarsConnection.cs @@ -1,10 +1,12 @@ using System.Threading.Channels; -using CPDLCServer.Clients; -using CPDLCServer.Model; +using CPDLCServer.AcarsConnections; +using CPDLCServer.AdscContracts; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; namespace CPDLCServer.Tests.Mocks; -public class TestAcarsClient(string stationId) : IAcarsClient +public class TestAcarsConnection(string stationId) : IAcarsConnection { private readonly Channel _channel = Channel.CreateUnbounded(); private readonly Channel _adscChannel = Channel.CreateUnbounded(); diff --git a/source/CPDLCServer.Tests/Mocks/TestAcarsConnectionManager.cs b/source/CPDLCServer.Tests/Mocks/TestAcarsConnectionManager.cs new file mode 100644 index 0000000..40a41ef --- /dev/null +++ b/source/CPDLCServer.Tests/Mocks/TestAcarsConnectionManager.cs @@ -0,0 +1,116 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.AcarsConnections.ConnectionSettings; + +namespace CPDLCServer.Tests.Mocks; + +public class TestAcarsConnectionManager : IAcarsConnectionManager +{ + private readonly Dictionary _connections = new(); + private readonly Dictionary _configurations = new(); + + public TestAcarsConnectionManager() + { + AddConnection("hoppies-ybbb", new TestAcarsConnection("YBBB")); + AddConnection("hoppies-ymmm", new TestAcarsConnection("YMMM")); + AddConfiguration(CreateConfiguration("YBBB", 10)); + AddConfiguration(CreateConfiguration("YMMM", 20)); + } + + public void AddConnection(string acarsConnectionId, IAcarsConnection connection) + { + _connections[acarsConnectionId] = connection; + } + + public void AddConfiguration(HoppiesConfiguration configuration) + { + _configurations[configuration.StationIdentifier] = configuration; + } + + public static HoppiesConfiguration CreateConfiguration( + string stationId, + int defaultAdscReportingInterval, + string? motd = null) + { + return new HoppiesConfiguration + { + Url = new Uri("http://test.hoppie.nl/acars"), + AuthenticationCode = "TEST123", + StationIdentifier = stationId, + DefaultAdscReportingInterval = defaultAdscReportingInterval, + Motd = motd + }; + } + + public Task GetAcarsConnection(string acarsConnectionId, CancellationToken cancellationToken) + { + if (!_connections.TryGetValue(acarsConnectionId, out var connection)) + { + throw new ConfigurationNotFoundException(acarsConnectionId); + } + return Task.FromResult(connection); + } + + public Task GetAcarsConnectionForStation(string stationId, CancellationToken cancellationToken) + { + var connection = _connections.Values.FirstOrDefault(c => c.StationId == stationId); + if (connection is null) + { + throw new Exception($"No ACARS connection found for station '{stationId}'"); + } + return Task.FromResult(connection); + } + + public Task GetConfigurationForStation(string stationId, CancellationToken cancellationToken) + { + if (!_configurations.TryGetValue(stationId, out var configuration)) + { + throw new Exception($"No ACARS configuration found for station '{stationId}'"); + } + return Task.FromResult(configuration); + } + + public Task FindAcarsConnectionId(string stationId, CancellationToken cancellationToken) + { + var acarsConnectionId = _connections + .Where(c => string.Equals(c.Value.StationId, stationId, StringComparison.OrdinalIgnoreCase)) + .Select(c => c.Key) + .FirstOrDefault(); + + return Task.FromResult(acarsConnectionId); + } + + public bool ClientExists(string acarsConnectionId) + { + return _connections.ContainsKey(acarsConnectionId); + } + + // The calls to Start and Stop, in order + public List StartStopCalls { get; } = []; + public List StartedConnections { get; } = []; + public List StoppedConnections { get; } = []; + + public string[] GetAcarsConnectionIds() + { + return _connections.Keys.ToArray(); + } + + public bool IsRunning(Guid settingsId) + { + return StartedConnections.Any(s => s.Id == settingsId); + } + + public Task Start(AcarsConnectionSettings settings, CancellationToken cancellationToken) + { + StartStopCalls.Add($"Start {settings.Id}"); + StartedConnections.Add(settings); + return Task.CompletedTask; + } + + public Task Stop(Guid settingsId, CancellationToken cancellationToken) + { + StartStopCalls.Add($"Stop {settingsId}"); + StoppedConnections.Add(settingsId); + StartedConnections.RemoveAll(s => s.Id == settingsId); + return Task.CompletedTask; + } +} diff --git a/source/CPDLCServer.Tests/Mocks/TestAdministratorRepository.cs b/source/CPDLCServer.Tests/Mocks/TestAdministratorRepository.cs new file mode 100644 index 0000000..1530f29 --- /dev/null +++ b/source/CPDLCServer.Tests/Mocks/TestAdministratorRepository.cs @@ -0,0 +1,35 @@ +using CPDLCServer.Auth.Administrators; + +namespace CPDLCServer.Tests.Mocks; + +public class TestAdministratorRepository : IAdministratorRepository +{ + private readonly List _administrators = []; + + public Task Add(Administrator administrator, CancellationToken cancellationToken) + { + _administrators.Add(administrator); + return Task.CompletedTask; + } + + public Task Remove(Administrator administrator, CancellationToken cancellationToken) + { + _administrators.Remove(administrator); + return Task.CompletedTask; + } + + public Task FindByCid(string cid, CancellationToken cancellationToken) + { + return Task.FromResult(_administrators.FirstOrDefault(a => a.Cid == cid)); + } + + public Task All(CancellationToken cancellationToken) + { + return Task.FromResult(_administrators.OrderBy(a => a.Cid, StringComparer.Ordinal).ToArray()); + } + + public Task Any(CancellationToken cancellationToken) + { + return Task.FromResult(_administrators.Count > 0); + } +} diff --git a/source/CPDLCServer.Tests/Mocks/TestAdscContractRepository.cs b/source/CPDLCServer.Tests/Mocks/TestAdscContractRepository.cs index d7742f5..91dd5e1 100644 --- a/source/CPDLCServer.Tests/Mocks/TestAdscContractRepository.cs +++ b/source/CPDLCServer.Tests/Mocks/TestAdscContractRepository.cs @@ -1,29 +1,29 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts; namespace CPDLCServer.Tests.Mocks; public class TestAdscContractRepository : IAdscContractRepository { - private readonly InMemoryAdscContractRepository _inner = new(); + private readonly Dictionary _contracts = new(); public Task Add(AdscContractKey contractKey, AdscContract contract, CancellationToken cancellationToken) { - return _inner.Add(contractKey, contract, cancellationToken); + _contracts[contractKey] = contract; + return Task.CompletedTask; } public Task Find(AdscContractKey contractKey, CancellationToken cancellationToken) { - return _inner.Find(contractKey, cancellationToken); + return Task.FromResult(_contracts.GetValueOrDefault(contractKey)); } public Task All(CancellationToken cancellationToken) { - return _inner.All(cancellationToken); + return Task.FromResult(_contracts.Values.ToArray()); } public Task Remove(AdscContractKey contractKey, CancellationToken cancellationToken) { - return _inner.Remove(contractKey, cancellationToken); + return Task.FromResult(_contracts.Remove(contractKey)); } } diff --git a/source/CPDLCServer.Tests/Mocks/TestAdscMessageLogRepository.cs b/source/CPDLCServer.Tests/Mocks/TestAdscMessageLogRepository.cs index 093e5b4..40cfabc 100644 --- a/source/CPDLCServer.Tests/Mocks/TestAdscMessageLogRepository.cs +++ b/source/CPDLCServer.Tests/Mocks/TestAdscMessageLogRepository.cs @@ -1,5 +1,4 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts.MessageLog; namespace CPDLCServer.Tests.Mocks; diff --git a/source/CPDLCServer.Tests/Mocks/TestAdscReportRepository.cs b/source/CPDLCServer.Tests/Mocks/TestAdscReportRepository.cs index da963b2..b08c7fa 100644 --- a/source/CPDLCServer.Tests/Mocks/TestAdscReportRepository.cs +++ b/source/CPDLCServer.Tests/Mocks/TestAdscReportRepository.cs @@ -1,29 +1,50 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts.Reports; namespace CPDLCServer.Tests.Mocks; public class TestAdscReportRepository : IAdscReportRepository { - private readonly InMemoryAdscReportRepository _inner = new(); + private readonly List _reports = []; public Task Add(AircraftAdscReport report, CancellationToken cancellationToken) { - return _inner.Add(report, cancellationToken); + _reports.RemoveAll(r => r.Callsign == report.Callsign && r.StationId == report.StationId); + _reports.Add(report); + return Task.CompletedTask; } - public Task Find(string callsign, CancellationToken cancellationToken) + public Task Find(string callsign, string stationId, CancellationToken cancellationToken) { - return _inner.Find(callsign, cancellationToken); + return Task.FromResult(_reports.FirstOrDefault(r => r.Callsign == callsign && r.StationId == stationId)); + } + + public Task FindLatest(string callsign, CancellationToken cancellationToken) + { + var reports = _reports.Where(r => r.Callsign == callsign).ToArray(); + return Task.FromResult(reports.Length == 0 ? null : SelectLatest(reports)); + } + + public Task AllLatest(CancellationToken cancellationToken) + { + return Task.FromResult(_reports.GroupBy(r => r.Callsign).Select(SelectLatest).ToArray()); } public Task All(CancellationToken cancellationToken) { - return _inner.All(cancellationToken); + return Task.FromResult(_reports.ToArray()); + } + + public Task Remove(AircraftAdscReport report, CancellationToken cancellationToken) + { + _reports.Remove(report); + return Task.CompletedTask; } - public Task RemoveOlderThan(DateTimeOffset cutoff, CancellationToken cancellationToken) + static AircraftAdscReport SelectLatest(IEnumerable reports) { - return _inner.RemoveOlderThan(cutoff, cancellationToken); + return reports + .OrderByDescending(r => r.Report.Source == AdscReportSource.Hoppie) + .ThenByDescending(r => r.Report.Timestamp) + .First(); } } diff --git a/source/CPDLCServer.Tests/Mocks/TestAircraftRepository.cs b/source/CPDLCServer.Tests/Mocks/TestAircraftRepository.cs index 1c801d1..a210c88 100644 --- a/source/CPDLCServer.Tests/Mocks/TestAircraftRepository.cs +++ b/source/CPDLCServer.Tests/Mocks/TestAircraftRepository.cs @@ -1,29 +1,29 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.Cpdlc.Connections; namespace CPDLCServer.Tests.Mocks; public class TestAircraftRepository : IAircraftRepository { - private readonly InMemoryAircraftRepository _inner = new(); + private readonly Dictionary _connections = new(); public Task Add(AircraftKey aircraftKey, AircraftConnection connection, CancellationToken cancellationToken) { - return _inner.Add(aircraftKey, connection, cancellationToken); + _connections[aircraftKey] = connection; + return Task.CompletedTask; } public Task Find(AircraftKey aircraftKey, CancellationToken cancellationToken) { - return _inner.Find(aircraftKey, cancellationToken); + return Task.FromResult(_connections.GetValueOrDefault(aircraftKey)); } public Task All(CancellationToken cancellationToken) { - return _inner.All(cancellationToken); + return Task.FromResult(_connections.Values.ToArray()); } public Task Remove(AircraftKey aircraftKey, CancellationToken cancellationToken) { - return _inner.Remove(aircraftKey, cancellationToken); + return Task.FromResult(_connections.Remove(aircraftKey)); } } diff --git a/source/CPDLCServer.Tests/Mocks/TestClientManager.cs b/source/CPDLCServer.Tests/Mocks/TestClientManager.cs deleted file mode 100644 index a2ac026..0000000 --- a/source/CPDLCServer.Tests/Mocks/TestClientManager.cs +++ /dev/null @@ -1,87 +0,0 @@ -using CPDLCServer.Clients; -using CPDLCServer.Exceptions; - -namespace CPDLCServer.Tests.Mocks; - -public class TestClientManager : IClientManager -{ - private readonly Dictionary _clients = new(); - private readonly Dictionary _configurations = new(); - - public TestClientManager() - { - AddClient("hoppies-ybbb", new TestAcarsClient("YBBB")); - AddClient("hoppies-ymmm", new TestAcarsClient("YMMM")); - AddConfiguration(CreateConfiguration("YBBB", 10)); - AddConfiguration(CreateConfiguration("YMMM", 20)); - } - - public void AddClient(string acarsClientId, IAcarsClient client) - { - _clients[acarsClientId] = client; - } - - public void AddConfiguration(HoppiesConfiguration configuration) - { - _configurations[configuration.StationIdentifier] = configuration; - } - - public static HoppiesConfiguration CreateConfiguration( - string stationId, - int defaultAdscReportingInterval, - int selectedAdscContractDuration = 60) - { - return new HoppiesConfiguration - { - Url = new Uri("http://test.hoppie.nl/acars"), - AuthenticationCode = "TEST123", - FlightSimulationNetwork = "VATSIM", - StationIdentifier = stationId, - DefaultAdscReportingInterval = defaultAdscReportingInterval, - SelectedAdscContractDuration = selectedAdscContractDuration - }; - } - - public Task GetAcarsClient(string acarsClientId, CancellationToken cancellationToken) - { - if (!_clients.TryGetValue(acarsClientId, out var client)) - { - throw new ConfigurationNotFoundException(acarsClientId); - } - return Task.FromResult(client); - } - - public Task GetAcarsClientForStation(string stationId, CancellationToken cancellationToken) - { - var client = _clients.Values.FirstOrDefault(c => c.StationId == stationId); - if (client is null) - { - throw new Exception($"No ACARS client found for station '{stationId}'"); - } - return Task.FromResult(client); - } - - public Task GetConfigurationForStation(string stationId, CancellationToken cancellationToken) - { - if (!_configurations.TryGetValue(stationId, out var configuration)) - { - throw new Exception($"No ACARS configuration found for station '{stationId}'"); - } - return Task.FromResult(configuration); - } - - public Task FindAcarsClientId(string stationId, CancellationToken cancellationToken) - { - var acarsClientId = _clients - .Where(c => string.Equals(c.Value.StationId, stationId, StringComparison.OrdinalIgnoreCase)) - .Select(c => c.Key) - .FirstOrDefault(); - - return Task.FromResult(acarsClientId); - } - - public bool ClientExists(string acarsClientId) - { - return _clients.ContainsKey(acarsClientId); - } -} diff --git a/source/CPDLCServer.Tests/Mocks/TestControllerManager.cs b/source/CPDLCServer.Tests/Mocks/TestControllerManager.cs index aba052f..025820b 100644 --- a/source/CPDLCServer.Tests/Mocks/TestControllerManager.cs +++ b/source/CPDLCServer.Tests/Mocks/TestControllerManager.cs @@ -1,5 +1,4 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.Controllers; namespace CPDLCServer.Tests.Mocks; diff --git a/source/CPDLCServer.Tests/Mocks/TestDatabase.cs b/source/CPDLCServer.Tests/Mocks/TestDatabase.cs new file mode 100644 index 0000000..fc878c6 --- /dev/null +++ b/source/CPDLCServer.Tests/Mocks/TestDatabase.cs @@ -0,0 +1,35 @@ +using CPDLCServer.Persistence; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Tests.Mocks; + +// An in-memory SQLite database. The database exists while the connection is open. +// Use a new context for each unit of work, so that the tests read the saved data and not the tracked entities. +public sealed class TestDatabase : IDisposable +{ + readonly SqliteConnection _connection; + + public TestDatabase() + { + _connection = new SqliteConnection("Data Source=:memory:"); + _connection.Open(); + + using var dbContext = CreateDbContext(); + dbContext.Database.EnsureCreated(); + } + + public CpdlcDbContext CreateDbContext() + { + var options = new DbContextOptionsBuilder() + .UseSqlite(_connection) + .Options; + + return new CpdlcDbContext(options); + } + + public void Dispose() + { + _connection.Dispose(); + } +} diff --git a/source/CPDLCServer.Tests/Mocks/TestDialogueRepository.cs b/source/CPDLCServer.Tests/Mocks/TestDialogueRepository.cs index bd9f3a9..4e91c0e 100644 --- a/source/CPDLCServer.Tests/Mocks/TestDialogueRepository.cs +++ b/source/CPDLCServer.Tests/Mocks/TestDialogueRepository.cs @@ -1,41 +1,68 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Uplinks; namespace CPDLCServer.Tests.Mocks; public class TestDialogueRepository : IDialogueRepository { - private readonly InMemoryDialogueRepository _inner = new(); + private readonly List _dialogues = []; public Task Add(Dialogue dialogue, CancellationToken cancellationToken) { - return _inner.Add(dialogue, cancellationToken); + _dialogues.Add(dialogue); + return Task.CompletedTask; } public Task FindOpenDialogueByUplink( string aircraftCallsign, + string stationId, int uplinkMessageId, CancellationToken cancellationToken) { - return _inner.FindOpenDialogueByUplink( - aircraftCallsign, - uplinkMessageId, - cancellationToken); + var dialogue = _dialogues.FirstOrDefault(d => + d.AircraftCallsign == aircraftCallsign && + d.StationId == stationId && + !d.IsClosed && + d.Messages.OfType().Any(m => m.MessageId == uplinkMessageId)); + + return Task.FromResult(dialogue); } public Task FindById(Guid id, CancellationToken cancellationToken) { - return _inner.FindById(id, cancellationToken); + return Task.FromResult(_dialogues.FirstOrDefault(d => d.Id == id)); } - public Task All(CancellationToken cancellationToken) + public Task FindOpen(CancellationToken cancellationToken) + { + return Task.FromResult(_dialogues.Where(d => !d.IsClosed).ToArray()); + } + + public Task FindClosedAndNotArchived(CancellationToken cancellationToken) + { + return Task.FromResult(_dialogues.Where(d => d.IsClosed && !d.IsArchived).ToArray()); + } + + public Task FindOpenForAircraft(string aircraftCallsign, string stationId, CancellationToken cancellationToken) + { + return Task.FromResult(_dialogues + .Where(d => d.AircraftCallsign == aircraftCallsign && d.StationId == stationId && !d.IsClosed && !d.IsArchived) + .ToArray()); + } + + public Task RemoveOpenedBefore(DateTimeOffset cutoff, CancellationToken cancellationToken) { - return _inner.All(cancellationToken); + return Task.FromResult(_dialogues.RemoveAll(d => d.Opened < cutoff)); } + public Task All(CancellationToken cancellationToken) + { + return Task.FromResult(_dialogues.ToArray()); + } public Task Remove(Dialogue dialogue, CancellationToken cancellationToken) { - return _inner.Remove(dialogue, cancellationToken); + _dialogues.Remove(dialogue); + return Task.CompletedTask; } } diff --git a/source/CPDLCServer.Tests/Mocks/TestMessageIdProvider.cs b/source/CPDLCServer.Tests/Mocks/TestMessageIdProvider.cs index 84bd3ef..ebbce1a 100644 --- a/source/CPDLCServer.Tests/Mocks/TestMessageIdProvider.cs +++ b/source/CPDLCServer.Tests/Mocks/TestMessageIdProvider.cs @@ -1,4 +1,4 @@ -using CPDLCServer.Services; +using CPDLCServer.Cpdlc.Uplinks; namespace CPDLCServer.Tests.Mocks; @@ -6,13 +6,21 @@ public class TestMessageIdProvider : IMessageIdProvider { private int _nextId = 1; + public List<(string AcarsConnectionId, string Callsign)> Removed { get; } = []; + public Task GetNextMessageId(string stationId, string callsign, CancellationToken cancellationToken) { return Task.FromResult(_nextId++); } + public Task Remove(string acarsConnectionId, string callsign, CancellationToken cancellationToken) + { + Removed.Add((acarsConnectionId, callsign)); + return Task.CompletedTask; + } + public void SetNextId(int id) { _nextId = id; } -} \ No newline at end of file +} diff --git a/source/CPDLCServer.Tests/Mocks/TestServerSettingsProvider.cs b/source/CPDLCServer.Tests/Mocks/TestServerSettingsProvider.cs new file mode 100644 index 0000000..62bda7f --- /dev/null +++ b/source/CPDLCServer.Tests/Mocks/TestServerSettingsProvider.cs @@ -0,0 +1,43 @@ +using CPDLCServer.Settings; + +namespace CPDLCServer.Tests.Mocks; + +public class TestServerSettingsProvider(ServerSettings settings) : IServerSettingsProvider +{ + ServerSettings _settings = settings; + + // The settings are given in the constructor, so there are always settings + public Task SeedDefaults(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + + public Task Load(CancellationToken cancellationToken) + { + return Task.FromResult(_settings); + } + + public Task Save(ServerSettings settings, CancellationToken cancellationToken) + { + _settings = settings with + { + BannerImage = _settings.BannerImage, + BannerContentType = _settings.BannerContentType, + BannerVersion = _settings.BannerVersion + }; + return Task.CompletedTask; + } + + public Task LoadBranding(CancellationToken cancellationToken) + { + return Task.FromResult(new BrandingInfo(_settings.ServerName, _settings.Motd, _settings.BannerImage is not null, _settings.BannerVersion)); + } + + public Task<(byte[] Image, string ContentType)?> LoadBanner(CancellationToken cancellationToken) + { + (byte[] Image, string ContentType)? banner = _settings is { BannerImage: not null, BannerContentType: not null } + ? (_settings.BannerImage, _settings.BannerContentType) + : null; + return Task.FromResult(banner); + } +} diff --git a/source/CPDLCServer.Tests/Mocks/TestUnitOfWork.cs b/source/CPDLCServer.Tests/Mocks/TestUnitOfWork.cs new file mode 100644 index 0000000..8b565b9 --- /dev/null +++ b/source/CPDLCServer.Tests/Mocks/TestUnitOfWork.cs @@ -0,0 +1,12 @@ +using CPDLCServer.Persistence; + +namespace CPDLCServer.Tests.Mocks; + +// Runs each action immediately, so that the handler tests can check the messages after the handler returns +public class TestUnitOfWork : IUnitOfWork +{ + public void AfterCommit(Func action) + { + action(CancellationToken.None).GetAwaiter().GetResult(); + } +} diff --git a/source/CPDLCServer.Tests/Mocks/TestUplinkTransmitter.cs b/source/CPDLCServer.Tests/Mocks/TestUplinkTransmitter.cs new file mode 100644 index 0000000..60dc89b --- /dev/null +++ b/source/CPDLCServer.Tests/Mocks/TestUplinkTransmitter.cs @@ -0,0 +1,13 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.Cpdlc.Uplinks; + +namespace CPDLCServer.Tests.Mocks; + +// Sends each uplink immediately, so that the handler tests can check the messages after the handler returns +public class TestUplinkTransmitter : IUplinkTransmitter +{ + public void TransmitAfterCommit(IAcarsConnection acarsConnection, UplinkMessage uplink) + { + acarsConnection.Send(uplink, CancellationToken.None).GetAwaiter().GetResult(); + } +} diff --git a/source/CPDLCServer.Tests/Persistence/CpdlcDbContextTests.cs b/source/CPDLCServer.Tests/Persistence/CpdlcDbContextTests.cs new file mode 100644 index 0000000..20588e3 --- /dev/null +++ b/source/CPDLCServer.Tests/Persistence/CpdlcDbContextTests.cs @@ -0,0 +1,116 @@ +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Tests.Mocks; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Tests.Persistence; + +public class CpdlcDbContextTests +{ + static readonly DateTimeOffset Start = new(2026, 11, 15, 12, 0, 0, TimeSpan.Zero); + + [Fact] + public async Task SaveChanges_WhenEntityChangedByDifferentUnitOfWork_Throws() + { + // Arrange + using var database = new TestDatabase(); + var connection = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.NextDataAuthority); + await using (var dbContext = database.CreateDbContext()) + { + await new AircraftRepository(dbContext).Add(new("UAL123", "hoppies-ybbb"), connection, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + await using var first = database.CreateDbContext(); + await using var second = database.CreateDbContext(); + var firstConnection = await new AircraftRepository(first).Find(new("UAL123", "hoppies-ybbb"), CancellationToken.None); + var secondConnection = await new AircraftRepository(second).Find(new("UAL123", "hoppies-ybbb"), CancellationToken.None); + + firstConnection!.PromoteToCurrentDataAuthority(); + secondConnection!.SetNextDataAuthority("YMMM", Start); + + // Act + await first.SaveChangesAsync(); + + // Assert + await Assert.ThrowsAsync(() => second.SaveChangesAsync()); + } + + [Fact] + public async Task SaveChanges_WhenMessagesOfSameDialogueChangedByDifferentUnitOfWork_Throws() + { + // Arrange + using var database = new TestDatabase(); + var dialogue = new Dialogue("UAL123", "YBBB"); + dialogue.AddDownlink(1, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST CLIMB TO FL410", Start); + dialogue.AddDownlink(2, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST DIRECT TO BIXAD", Start); + await using (var dbContext = database.CreateDbContext()) + { + await new DialogueRepository(dbContext).Add(dialogue, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + await using var first = database.CreateDbContext(); + await using var second = database.CreateDbContext(); + var firstDialogue = await new DialogueRepository(first).FindById(dialogue.Id, CancellationToken.None); + var secondDialogue = await new DialogueRepository(second).FindById(dialogue.Id, CancellationToken.None); + + // Each unit of work changes a different message. Only the messages change, not the dialogue. + firstDialogue!.AcknowledgeDownlink(1, Start.AddMinutes(1)); + secondDialogue!.AcknowledgeDownlink(2, Start.AddMinutes(1)); + + // Act + await first.SaveChangesAsync(); + + // Assert + await Assert.ThrowsAsync(() => second.SaveChangesAsync()); + } + + [Fact] + public async Task SaveChanges_WhenSameEntityAddedByDifferentUnitOfWork_Throws() + { + // Arrange + using var database = new TestDatabase(); + await using var first = database.CreateDbContext(); + await using var second = database.CreateDbContext(); + + await new MessageIdProvider(first).GetNextMessageId("hoppies-ybbb", "UAL123", CancellationToken.None); + await new MessageIdProvider(second).GetNextMessageId("hoppies-ybbb", "UAL123", CancellationToken.None); + + // Act + await first.SaveChangesAsync(); + + // Assert + await Assert.ThrowsAnyAsync(() => second.SaveChangesAsync()); + } + + [Fact] + public async Task SaveChanges_WhenNoConflict_Saves() + { + // Arrange + using var database = new TestDatabase(); + var dialogue = new Dialogue("UAL123", "YBBB"); + dialogue.AddDownlink(1, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST CLIMB TO FL410", Start); + await using (var dbContext = database.CreateDbContext()) + { + await new DialogueRepository(dbContext).Add(dialogue, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act - two units of work, one after the other + foreach (var minutes in new[] { 1, 2 }) + { + await using var dbContext = database.CreateDbContext(); + var saved = await new DialogueRepository(dbContext).FindById(dialogue.Id, CancellationToken.None); + saved!.AddUplink(minutes + 10, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.NoResponse, AlertType.None, "STANDBY", Start.AddMinutes(minutes)); + await dbContext.SaveChangesAsync(); + } + + // Assert + await using var readDbContext = database.CreateDbContext(); + var result = await new DialogueRepository(readDbContext).FindById(dialogue.Id, CancellationToken.None); + Assert.Equal(3, result!.Messages.Count); + } +} diff --git a/source/CPDLCServer.Tests/Persistence/InMemoryAdscReportRepositoryTests.cs b/source/CPDLCServer.Tests/Persistence/InMemoryAdscReportRepositoryTests.cs deleted file mode 100644 index 0379004..0000000 --- a/source/CPDLCServer.Tests/Persistence/InMemoryAdscReportRepositoryTests.cs +++ /dev/null @@ -1,127 +0,0 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; - -namespace CPDLCServer.Tests.Persistence; - -public class InMemoryAdscReportRepositoryTests -{ - static readonly DateTimeOffset Start = new(2026, 10, 13, 12, 0, 0, TimeSpan.Zero); - - [Fact] - public async Task Add_KeepsLatestReportForEachAircraft() - { - // Arrange - var repository = new InMemoryAdscReportRepository(); - var first = CreateReport("UAL123", "YBBB", 0); - var second = CreateReport("UAL123", "YBBB", 5); - var other = CreateReport("QFA1", "YBBB", 0); - - // Act - await repository.Add(first, CancellationToken.None); - await repository.Add(second, CancellationToken.None); - await repository.Add(other, CancellationToken.None); - - // Assert - var reports = await repository.All(CancellationToken.None); - Assert.Equal(2, reports.Length); - Assert.Contains(second, reports); - Assert.Contains(other, reports); - } - - [Fact] - public async Task Add_WhenReportIsOlder_KeepsNewerReport() - { - // Arrange - var repository = new InMemoryAdscReportRepository(); - var newer = CreateReport("UAL123", "YBBB", 5); - var older = CreateReport("UAL123", "YMMM", 0); - - // Act - await repository.Add(newer, CancellationToken.None); - await repository.Add(older, CancellationToken.None); - - // Assert - Assert.Equal([newer], await repository.All(CancellationToken.None)); - } - - [Fact] - public async Task Add_WhenHoppieReportIsOlderThanVatsimReport_ReplacesVatsimReport() - { - // Arrange - var repository = new InMemoryAdscReportRepository(); - var vatsimReport = CreateReport("UAL123", "YBBB", 5, AdscReportSource.VATSIM); - var hoppieReport = CreateReport("UAL123", "YBBB", 0); - - // Act - await repository.Add(vatsimReport, CancellationToken.None); - await repository.Add(hoppieReport, CancellationToken.None); - - // Assert - Assert.Equal([hoppieReport], await repository.All(CancellationToken.None)); - } - - [Fact] - public async Task Add_WhenVatsimReportIsOlderThanHoppieReport_KeepsHoppieReport() - { - // Arrange - var repository = new InMemoryAdscReportRepository(); - var hoppieReport = CreateReport("UAL123", "YBBB", 5); - var vatsimReport = CreateReport("UAL123", "YBBB", 0, AdscReportSource.VATSIM); - - // Act - await repository.Add(hoppieReport, CancellationToken.None); - await repository.Add(vatsimReport, CancellationToken.None); - - // Assert - Assert.Equal([hoppieReport], await repository.All(CancellationToken.None)); - } - - [Fact] - public async Task Find_ReturnsLatestReportForAircraft() - { - // Arrange - var repository = new InMemoryAdscReportRepository(); - var report = CreateReport("UAL123", "YBBB", 0); - await repository.Add(report, CancellationToken.None); - - // Act & Assert - Assert.Equal(report, await repository.Find("UAL123", CancellationToken.None)); - Assert.Null(await repository.Find("QFA1", CancellationToken.None)); - } - - [Fact] - public async Task RemoveOlderThan_RemovesOnlyOlderReports() - { - // Arrange - var repository = new InMemoryAdscReportRepository(); - var older = CreateReport("UAL123", "YBBB", 0); - var atCutoff = CreateReport("QFA1", "YBBB", 5); - var newer = CreateReport("VOZ1", "YBBB", 10); - await repository.Add(older, CancellationToken.None); - await repository.Add(atCutoff, CancellationToken.None); - await repository.Add(newer, CancellationToken.None); - - // Act - await repository.RemoveOlderThan(atCutoff.Received, CancellationToken.None); - - // Assert - var reports = await repository.All(CancellationToken.None); - Assert.Equal(2, reports.Length); - Assert.Contains(atCutoff, reports); - Assert.Contains(newer, reports); - } - - static AircraftAdscReport CreateReport( - string callsign, - string stationId, - int minutes, - AdscReportSource source = AdscReportSource.Hoppie) - { - var timestamp = Start.AddMinutes(minutes); - return new AircraftAdscReport( - callsign, - stationId, - new AdscReport(timestamp, -33.9461, 151.1772, 37000, source), - timestamp.AddSeconds(30)); - } -} diff --git a/source/CPDLCServer.Tests/Persistence/PostgreSqlConnectionStringTests.cs b/source/CPDLCServer.Tests/Persistence/PostgreSqlConnectionStringTests.cs new file mode 100644 index 0000000..39fb9f2 --- /dev/null +++ b/source/CPDLCServer.Tests/Persistence/PostgreSqlConnectionStringTests.cs @@ -0,0 +1,47 @@ +using CPDLCServer.Persistence; +using Npgsql; + +namespace CPDLCServer.Tests.Persistence; + +public class PostgreSqlConnectionStringTests +{ + [Fact] + public void Parse_WithUrl_ReturnsKeyValueConnectionString() + { + // Act + var connectionString = PostgreSqlConnectionString.Parse( + "postgresql://cpdlc:p%40ss%3Aword@db.example.com:25060/cpdlc?sslmode=require"); + + // Assert + var builder = new NpgsqlConnectionStringBuilder(connectionString); + Assert.Equal("db.example.com", builder.Host); + Assert.Equal(25060, builder.Port); + Assert.Equal("cpdlc", builder.Database); + Assert.Equal("cpdlc", builder.Username); + Assert.Equal("p@ss:word", builder.Password); + Assert.Equal(SslMode.Require, builder.SslMode); + } + + [Fact] + public void Parse_WithPostgresScheme_ReturnsKeyValueConnectionString() + { + // Act + var connectionString = PostgreSqlConnectionString.Parse("postgres://cpdlc:secret@localhost/cpdlc"); + + // Assert + var builder = new NpgsqlConnectionStringBuilder(connectionString); + Assert.Equal("localhost", builder.Host); + Assert.Equal("cpdlc", builder.Database); + Assert.Equal("secret", builder.Password); + } + + [Fact] + public void Parse_WithKeyValueConnectionString_ReturnsTheSameValue() + { + // Arrange + const string value = "Host=localhost;Database=cpdlc;Username=cpdlc;Password=secret"; + + // Act & Assert + Assert.Equal(value, PostgreSqlConnectionString.Parse(value)); + } +} diff --git a/source/CPDLCServer.Tests/Persistence/UnitOfWorkTests.cs b/source/CPDLCServer.Tests/Persistence/UnitOfWorkTests.cs new file mode 100644 index 0000000..0452694 --- /dev/null +++ b/source/CPDLCServer.Tests/Persistence/UnitOfWorkTests.cs @@ -0,0 +1,105 @@ +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Persistence; +using CPDLCServer.Tests.Mocks; + +namespace CPDLCServer.Tests.Persistence; + +public class UnitOfWorkTests +{ + [Fact] + public async Task Commit_SavesChangesBeforeActions() + { + // Arrange + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var unitOfWork = new UnitOfWork(dbContext); + + var dialogue = new Dialogue("UAL123", "YBBB"); + await new DialogueRepository(dbContext).Add(dialogue, CancellationToken.None); + + var savedWhenActionRan = false; + unitOfWork.AfterCommit(async ct => + { + await using var readDbContext = database.CreateDbContext(); + savedWhenActionRan = await new DialogueRepository(readDbContext).FindById(dialogue.Id, ct) is not null; + }); + + // Act + await unitOfWork.Commit(CancellationToken.None); + + // Assert + Assert.True(savedWhenActionRan); + } + + [Fact] + public async Task AfterCommit_DoesNotRunActionBeforeCommit() + { + // Arrange + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var unitOfWork = new UnitOfWork(dbContext); + + var actionRan = false; + + // Act + unitOfWork.AfterCommit(_ => + { + actionRan = true; + return Task.CompletedTask; + }); + + // Assert + Assert.False(actionRan); + } + + [Fact] + public async Task Commit_RunsActionsInOrder() + { + // Arrange + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var unitOfWork = new UnitOfWork(dbContext); + + var order = new List(); + unitOfWork.AfterCommit(_ => + { + order.Add(1); + return Task.CompletedTask; + }); + unitOfWork.AfterCommit(_ => + { + order.Add(2); + return Task.CompletedTask; + }); + + // Act + await unitOfWork.Commit(CancellationToken.None); + + // Assert + Assert.Equal([1, 2], order); + } + + [Fact] + public async Task Commit_WhenActionFails_RunsOtherActionsThenThrows() + { + // Arrange + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var unitOfWork = new UnitOfWork(dbContext); + + var secondActionRan = false; + unitOfWork.AfterCommit(_ => throw new InvalidOperationException("Send failed")); + unitOfWork.AfterCommit(_ => + { + secondActionRan = true; + return Task.CompletedTask; + }); + + // Act + var exception = await Assert.ThrowsAsync(() => unitOfWork.Commit(CancellationToken.None)); + + // Assert + Assert.True(secondActionRan); + Assert.IsType(Assert.Single(exception.InnerExceptions)); + } +} diff --git a/source/CPDLCServer.Tests/Security/MasterKeyEncryptionTests.cs b/source/CPDLCServer.Tests/Security/MasterKeyEncryptionTests.cs new file mode 100644 index 0000000..1ba382d --- /dev/null +++ b/source/CPDLCServer.Tests/Security/MasterKeyEncryptionTests.cs @@ -0,0 +1,54 @@ +using System.Security.Cryptography; +using CPDLCServer.Security; + +namespace CPDLCServer.Tests.Security; + +public class MasterKeyEncryptionTests +{ + [Fact] + public void Encrypt_ThenDecrypt_ReturnsThePlaintext() + { + // Arrange + var encryption = new MasterKeyEncryption(NewKey()); + + // Act + var encrypted = encryption.Encrypt("secret"); + + // Assert + Assert.NotEqual("secret", encrypted); + Assert.Equal("secret", encryption.Decrypt(encrypted)); + } + + [Fact] + public void Encrypt_SameValueTwice_GivesDifferentResults() + { + // Arrange + var encryption = new MasterKeyEncryption(NewKey()); + + // Act & Assert + Assert.NotEqual(encryption.Encrypt("secret"), encryption.Encrypt("secret")); + } + + [Fact] + public void Decrypt_WithDifferentKey_Throws() + { + // Arrange + var encrypted = new MasterKeyEncryption(NewKey()).Encrypt("secret"); + var otherEncryption = new MasterKeyEncryption(NewKey()); + + // Act & Assert + Assert.ThrowsAny(() => otherEncryption.Decrypt(encrypted)); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("not-a-key")] + [InlineData("AAAAAAAAAAAAAAAAAAAAAA==")] + public void Constructor_WithMissingOrInvalidKey_Throws(string? masterKey) + { + Assert.Throws(() => new MasterKeyEncryption(masterKey!)); + } + + static string NewKey() => Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)); +} diff --git a/source/CPDLCServer.Tests/Services/MessageIdProviderTests.cs b/source/CPDLCServer.Tests/Services/MessageIdProviderTests.cs deleted file mode 100644 index 7f0563c..0000000 --- a/source/CPDLCServer.Tests/Services/MessageIdProviderTests.cs +++ /dev/null @@ -1,74 +0,0 @@ -using CPDLCServer.Services; - -namespace CPDLCServer.Tests.Services; - -public class MessageIdProviderTests -{ - [Fact] - public async Task GetNextMessageId_FirstCall_ReturnsOne() - { - // Arrange - var provider = new MessageIdProvider(); - - // Act - var messageId = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); - - // Assert - Assert.Equal(1, messageId); - } - - [Fact] - public async Task GetNextMessageId_SequentialCalls_IncrementsForSamePair() - { - // Arrange - var provider = new MessageIdProvider(); - - // Act - var id1 = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); - var id2 = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); - var id3 = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); - - // Assert - Assert.Equal(1, id1); - Assert.Equal(2, id2); - Assert.Equal(3, id3); - } - - [Fact] - public async Task GetNextMessageId_DifferentCallsigns_MaintainsSeparateSequences() - { - // Arrange - var provider = new MessageIdProvider(); - - // Act - var ual1 = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); - var dal1 = await provider.GetNextMessageId("YBBB", "DAL456", CancellationToken.None); - var ual2 = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); - var dal2 = await provider.GetNextMessageId("YBBB", "DAL456", CancellationToken.None); - - // Assert - Assert.Equal(1, ual1); - Assert.Equal(1, dal1); - Assert.Equal(2, ual2); - Assert.Equal(2, dal2); - } - - [Fact] - public async Task GetNextMessageId_DifferentStations_MaintainsSeparateSequences() - { - // Arrange - var provider = new MessageIdProvider(); - - // Act - var ybbb1 = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); - var ymmm1 = await provider.GetNextMessageId("YMMM", "UAL123", CancellationToken.None); - var ybbb2 = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); - var ymmm2 = await provider.GetNextMessageId("YMMM", "UAL123", CancellationToken.None); - - // Assert - Assert.Equal(1, ybbb1); - Assert.Equal(1, ymmm1); - Assert.Equal(2, ybbb2); - Assert.Equal(2, ymmm2); - } -} diff --git a/source/CPDLCServer.Tests/Services/MessageMonitorServiceTests.cs b/source/CPDLCServer.Tests/Services/MessageMonitorServiceTests.cs deleted file mode 100644 index b207adc..0000000 --- a/source/CPDLCServer.Tests/Services/MessageMonitorServiceTests.cs +++ /dev/null @@ -1,482 +0,0 @@ -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Services; -using CPDLCServer.Tests.Mocks; -using Serilog.Core; - -namespace CPDLCServer.Tests.Services; - -public class MessageMonitorServiceTests -{ - [Fact] - public async Task CheckForTimeouts_MarksPilotLate_WhenUplinkTimesOut() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - // Create an uplink that requires a response - var dialogue = new Dialogue("UAL123"); - var uplink = dialogue.AddUplink( - 1, - null, - "UAL123", - "BN-TSN_FSS", - CpdlcUplinkResponseType.WilcoUnable, - AlertType.None, - "CLIMB TO FL410", - startTime); - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time beyond pilot late timeout (2 minutes) - clock.SetUtcNow(startTime.AddMinutes(3)); - await service.CheckForTimeouts(CancellationToken.None); - - // Assert - Assert.True(uplink.IsPilotLate); - Assert.Single(publisher.PublishedNotifications); - var notification = Assert.IsType(publisher.PublishedNotifications[0]); - Assert.Equal(dialogue, notification.Dialogue); - } - - [Fact] - public async Task CheckForTimeouts_DoesNotMarkPilotLate_WhenTimeoutNotReached() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - var dialogue = new Dialogue("UAL123"); - var uplink = dialogue.AddUplink( - 1, - null, - "UAL123", - "BN-TSN_FSS", - CpdlcUplinkResponseType.WilcoUnable, - AlertType.None, - "CLIMB TO FL410", - startTime); - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time but not beyond timeout (1 minute < 2 minute timeout) - clock.SetUtcNow(startTime.AddMinutes(1)); - await service.CheckForTimeouts(CancellationToken.None); - - // Assert - Assert.False(uplink.IsPilotLate); - Assert.Empty(publisher.PublishedNotifications); - } - - [Fact] - public async Task CheckForTimeouts_IgnoresNoResponseUplinks() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - // Create an uplink that doesn't require a response - var dialogue = new Dialogue("UAL123"); - var uplink = dialogue.AddUplink( - 1, - null, - "UAL123", - "BN-TSN_FSS", - CpdlcUplinkResponseType.NoResponse, - AlertType.None, - "ROGER", - startTime); - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time beyond timeout - clock.SetUtcNow(startTime.AddMinutes(3)); - await service.CheckForTimeouts(CancellationToken.None); - - // Assert - should not be marked late since no response is needed - Assert.False(uplink.IsPilotLate); - Assert.Empty(publisher.PublishedNotifications); - } - - [Fact] - public async Task CheckForTimeouts_MarksControllerLate_WhenDownlinkTimesOut() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - // Create a downlink that requires a response - var dialogue = new Dialogue("UAL123"); - var downlink = dialogue.AddDownlink( - 1, - null, - "UAL123", - CpdlcDownlinkResponseType.ResponseRequired, - AlertType.None, - "REQUEST CLIMB FL410", - startTime); - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time beyond controller late timeout (2 minutes) - clock.SetUtcNow(startTime.AddMinutes(3)); - await service.CheckForTimeouts(CancellationToken.None); - - // Assert - Assert.True(downlink.IsControllerLate); - Assert.Single(publisher.PublishedNotifications); - var notification = Assert.IsType(publisher.PublishedNotifications[0]); - Assert.Equal(dialogue, notification.Dialogue); - } - - [Fact] - public async Task CheckForTimeouts_IgnoresClosedMessages() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - var dialogue = new Dialogue("UAL123"); - var uplink = dialogue.AddUplink( - 1, - null, - "UAL123", - "BN-TSN_FSS", - CpdlcUplinkResponseType.WilcoUnable, - AlertType.None, - "CLIMB TO FL410", - startTime); - - // Close the message - uplink.Close(startTime); - - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time beyond timeout - clock.SetUtcNow(startTime.AddMinutes(3)); - await service.CheckForTimeouts(CancellationToken.None); - - // Assert - closed messages should not be marked late - Assert.False(uplink.IsPilotLate); - Assert.Empty(publisher.PublishedNotifications); - } - - [Fact] - public async Task CheckForTimeouts_IgnoresClosedDialogues() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - // Create a self-closing uplink (NoResponse) - var dialogue = new Dialogue("UAL123"); - dialogue.AddUplink( - 1, - null, - "UAL123", - "BN-TSN_FSS", - CpdlcUplinkResponseType.NoResponse, - AlertType.None, - "ROGER", - startTime); - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time beyond timeout - clock.SetUtcNow(startTime.AddMinutes(3)); - await service.CheckForTimeouts(CancellationToken.None); - - // Assert - closed dialogues should be skipped - Assert.True(dialogue.IsClosed); - Assert.Empty(publisher.PublishedNotifications); - } - - [Fact] - public async Task ArchiveCompletedDialogues_ArchivesDialogue_WhenAllMessagesAcknowledgedAndDelayPassed() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - // Create a closed dialogue with acknowledged message - var dialogue = new Dialogue("UAL123"); - dialogue.AddUplink( - 1, - null, - "UAL123", - "BN-TSN_FSS", - CpdlcUplinkResponseType.NoResponse, - AlertType.None, - "ROGER", - startTime); // NoResponse uplinks are self-closing and auto-acknowledged - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time beyond archive delay (10 seconds) - clock.SetUtcNow(startTime.AddSeconds(15)); - await service.ArchiveCompletedDialogues(CancellationToken.None); - - // Assert - Assert.True(dialogue.IsArchived); - Assert.Single(publisher.PublishedNotifications); - var notification = Assert.IsType(publisher.PublishedNotifications[0]); - Assert.Equal(dialogue, notification.Dialogue); - } - - [Fact] - public async Task ArchiveCompletedDialogues_DoesNotArchive_WhenDelayNotPassed() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - var dialogue = new Dialogue("UAL123"); - dialogue.AddUplink( - 1, - null, - "UAL123", - "BN-TSN_FSS", - CpdlcUplinkResponseType.NoResponse, - AlertType.None, - "ROGER", - startTime); - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time but not enough (5 seconds < 10 second delay) - clock.SetUtcNow(startTime.AddSeconds(5)); - await service.ArchiveCompletedDialogues(CancellationToken.None); - - // Assert - Assert.False(dialogue.IsArchived); - Assert.Empty(publisher.PublishedNotifications); - } - - [Fact] - public async Task ArchiveCompletedDialogues_IgnoresOpenDialogues() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - // Create an open dialogue (requires response) - var dialogue = new Dialogue("UAL123"); - dialogue.AddUplink( - 1, - null, - "UAL123", - "BN-TSN_FSS", - CpdlcUplinkResponseType.WilcoUnable, - AlertType.None, - "CLIMB TO FL410", - startTime); - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time beyond archive delay - clock.SetUtcNow(startTime.AddSeconds(15)); - await service.ArchiveCompletedDialogues(CancellationToken.None); - - // Assert - open dialogues should not be archived - Assert.False(dialogue.IsClosed); - Assert.False(dialogue.IsArchived); - Assert.Empty(publisher.PublishedNotifications); - } - - [Fact] - public async Task ArchiveCompletedDialogues_IgnoresDialoguesWithoutAcknowledgements() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - // Create a downlink that's closed but not acknowledged - var dialogue = new Dialogue("UAL123"); - dialogue.AddDownlink( - 1, - null, - "UAL123", - CpdlcDownlinkResponseType.NoResponse, - AlertType.None, - "WILCO", - startTime); - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time beyond archive delay - clock.SetUtcNow(startTime.AddSeconds(15)); - await service.ArchiveCompletedDialogues(CancellationToken.None); - - // Assert - unacknowledged dialogues should not be archived - Assert.True(dialogue.IsClosed); - Assert.False(dialogue.IsArchived); - Assert.Empty(publisher.PublishedNotifications); - } - - [Fact] - public async Task CheckForTimeouts_HandlesMultipleDialogues() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - // Create multiple dialogues with different aircraft - var dialogue1 = new Dialogue("UAL123"); - var uplink1 = dialogue1.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB", startTime); - - var dialogue2 = new Dialogue("DAL456"); - var uplink2 = dialogue2.AddUplink(2, null, "DAL456", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "DESCEND", startTime); - - await repository.Add(dialogue1, CancellationToken.None); - await repository.Add(dialogue2, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time beyond timeout - clock.SetUtcNow(startTime.AddMinutes(3)); - await service.CheckForTimeouts(CancellationToken.None); - - // Assert - both should be marked late - Assert.True(uplink1.IsPilotLate); - Assert.True(uplink2.IsPilotLate); - Assert.Equal(2, publisher.PublishedNotifications.Count); - } - - [Fact] - public async Task PurgeOldAdscMessages_RemovesMessagesOlderThan24Hours() - { - // Arrange - var clock = new TestClock(); - var adscMessageLogRepository = new TestAdscMessageLogRepository(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - var oldEntry = new AdscMessageLogEntry( - startTime, - "Hoppies/YBBB", - "YBBB", - "UAL123", - AdscMessageDirection.Uplink, - "REQUEST PERIODIC 1"); - var newEntry = new AdscMessageLogEntry( - startTime.AddHours(2), - "Hoppies/YBBB", - "YBBB", - "UAL123", - AdscMessageDirection.Uplink, - "REQUEST PERIODIC 2"); - await adscMessageLogRepository.Add(oldEntry, CancellationToken.None); - await adscMessageLogRepository.Add(newEntry, CancellationToken.None); - - var service = new MessageMonitorService( - new TestDialogueRepository(), - adscMessageLogRepository, - new TestAdscReportRepository(), - clock, - new TestPublisher(), - Logger.None); - - // Act - advance time beyond the purge timeout (24 hours) for the old entry only - clock.SetUtcNow(startTime.AddHours(25)); - await service.PurgeOldAdscMessages(CancellationToken.None); - - // Assert - Assert.Equal([newEntry], await adscMessageLogRepository.All(CancellationToken.None)); - } - - [Fact] - public async Task PurgeOldAdscReports_RemovesReportsOlderThan24Hours() - { - // Arrange - var clock = new TestClock(); - var adscReportRepository = new TestAdscReportRepository(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - var oldReport = new AircraftAdscReport( - "UAL123", - "YBBB", - new AdscReport(startTime, -33.9461, 151.1772, 37000, AdscReportSource.Hoppie), - startTime); - var newReport = new AircraftAdscReport( - "QFA1", - "YBBB", - new AdscReport(startTime.AddHours(2), -33.9461, 151.1772, 37000, AdscReportSource.Hoppie), - startTime.AddHours(2)); - await adscReportRepository.Add(oldReport, CancellationToken.None); - await adscReportRepository.Add(newReport, CancellationToken.None); - - var service = new MessageMonitorService( - new TestDialogueRepository(), - new TestAdscMessageLogRepository(), - adscReportRepository, - clock, - new TestPublisher(), - Logger.None); - - // Act - advance time beyond the purge timeout (24 hours) for the old report only - clock.SetUtcNow(startTime.AddHours(25)); - await service.PurgeOldAdscReports(CancellationToken.None); - - // Assert - Assert.Equal([newReport], await adscReportRepository.All(CancellationToken.None)); - } -} diff --git a/source/CPDLCServer.Tests/Settings/BannerImageFormatTests.cs b/source/CPDLCServer.Tests/Settings/BannerImageFormatTests.cs new file mode 100644 index 0000000..826b923 --- /dev/null +++ b/source/CPDLCServer.Tests/Settings/BannerImageFormatTests.cs @@ -0,0 +1,30 @@ +using CPDLCServer.Settings; + +namespace CPDLCServer.Tests.Settings; + +public class BannerImageFormatTests +{ + [Fact] + public void FindContentType_FindsPngJpegAndWebp() + { + // Arrange + byte[] png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00]; + byte[] jpeg = [0xFF, 0xD8, 0xFF, 0xE0, 0x00]; + byte[] webp = [.."RIFF"u8, 0x00, 0x00, 0x00, 0x00, .."WEBP"u8, 0x00]; + + // Act & Assert + Assert.Equal("image/png", BannerImageFormat.FindContentType(png)); + Assert.Equal("image/jpeg", BannerImageFormat.FindContentType(jpeg)); + Assert.Equal("image/webp", BannerImageFormat.FindContentType(webp)); + } + + [Fact] + public void FindContentType_DoesNotAcceptSvg() + { + // Arrange + var svg = ""u8.ToArray(); + + // Act & Assert + Assert.Null(BannerImageFormat.FindContentType(svg)); + } +} diff --git a/source/CPDLCServer.Tests/Settings/PrivacyContactTests.cs b/source/CPDLCServer.Tests/Settings/PrivacyContactTests.cs new file mode 100644 index 0000000..c0b0ee9 --- /dev/null +++ b/source/CPDLCServer.Tests/Settings/PrivacyContactTests.cs @@ -0,0 +1,31 @@ +using CPDLCServer.Settings; + +namespace CPDLCServer.Tests.Settings; + +public class PrivacyContactTests +{ + [Theory] + [InlineData("privacy@example.com", true)] + [InlineData("https://example.com/privacy", true)] + [InlineData("http://example.com/privacy", true)] + [InlineData("", true)] + [InlineData(null, true)] + [InlineData("not a contact", false)] + [InlineData("javascript:alert(1)", false)] + [InlineData("ftp://example.com", false)] + [InlineData("Privacy ", false)] + public void IsValid_AcceptsAnEmailAddressOrAWebUrl(string? contact, bool expected) + { + // Act & Assert + Assert.Equal(expected, new PrivacyContactAttribute().IsValid(contact)); + } + + [Theory] + [InlineData("privacy@example.com", "mailto:privacy@example.com")] + [InlineData("https://example.com/privacy", "https://example.com/privacy")] + public void ToHref_MakesALink(string contact, string expected) + { + // Act & Assert + Assert.Equal(expected, PrivacyContactFormat.ToHref(contact)); + } +} diff --git a/source/CPDLCServer.Tests/Settings/ServerSettingsProviderTests.cs b/source/CPDLCServer.Tests/Settings/ServerSettingsProviderTests.cs new file mode 100644 index 0000000..14a9c6c --- /dev/null +++ b/source/CPDLCServer.Tests/Settings/ServerSettingsProviderTests.cs @@ -0,0 +1,114 @@ +using CPDLCServer.Settings; +using CPDLCServer.Tests.Mocks; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Tests.Settings; + +public class ServerSettingsProviderTests +{ + [Fact] + public async Task SeedDefaults_WhenNoSettings_AddsDefaults() + { + // Arrange + using var database = new TestDatabase(); + + // Act + await Seed(database); + + // Assert + await using var dbContext = database.CreateDbContext(); + var settings = await new ServerSettingsProvider(dbContext).Load(CancellationToken.None); + Assert.Equal(new ServerSettings(), settings); + } + + [Fact] + public async Task SeedDefaults_WhenSettingsExist_DoesNotChangeThem() + { + // Arrange + using var database = new TestDatabase(); + await Seed(database); + await SaveAndCommit(database, new ServerSettings { DialogueRetentionHours = 48 }); + + // Act + await Seed(database); + + // Assert + await using var dbContext = database.CreateDbContext(); + Assert.Equal(1, await dbContext.ServerSettings.CountAsync()); + var settings = await new ServerSettingsProvider(dbContext).Load(CancellationToken.None); + Assert.Equal(48, settings.DialogueRetentionHours); + } + + [Fact] + public async Task Save_ThenCommit_ThenLoad_ReturnsSavedSettings() + { + // Arrange + using var database = new TestDatabase(); + await Seed(database); + var settings = new ServerSettings + { + ConnectivityCheckIntervalMinutes = 5, + AircraftConnectionTimeoutMinutes = 20, + VatsimStatusEnabled = true, + VatsimStatusUrl = new Uri("https://example.com/vatsim-data.json") + }; + + // Act + await SaveAndCommit(database, settings); + + // Assert + await using var dbContext = database.CreateDbContext(); + Assert.Equal(settings, await new ServerSettingsProvider(dbContext).Load(CancellationToken.None)); + } + + [Fact] + public async Task Save_WithoutCommit_DoesNotChangeTheDatabase() + { + // Arrange + using var database = new TestDatabase(); + await Seed(database); + + // Act + await using (var dbContext = database.CreateDbContext()) + { + await new ServerSettingsProvider(dbContext).Save( + new ServerSettings { DialogueRetentionHours = 48 }, + CancellationToken.None); + } + + // Assert + await using var otherDbContext = database.CreateDbContext(); + var settings = await new ServerSettingsProvider(otherDbContext).Load(CancellationToken.None); + Assert.Equal(new ServerSettings().DialogueRetentionHours, settings.DialogueRetentionHours); + } + + [Fact] + public async Task Load_AfterSaveInTheSameScope_ReturnsTheUnsavedSettings() + { + // Arrange + using var database = new TestDatabase(); + await Seed(database); + await using var dbContext = database.CreateDbContext(); + var provider = new ServerSettingsProvider(dbContext); + + // Act + await provider.Save(new ServerSettings { DialogueRetentionHours = 48 }, CancellationToken.None); + + // Assert + Assert.Equal(48, (await provider.Load(CancellationToken.None)).DialogueRetentionHours); + } + + static async Task Seed(TestDatabase database) + { + await using var dbContext = database.CreateDbContext(); + await new ServerSettingsProvider(dbContext).SeedDefaults(CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + static async Task SaveAndCommit(TestDatabase database, ServerSettings settings) + { + await using var dbContext = database.CreateDbContext(); + await new ServerSettingsProvider(dbContext).Save(settings, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } +} diff --git a/source/CPDLCServer.Tests/Setup/CompleteSetupCommandHandlerTests.cs b/source/CPDLCServer.Tests/Setup/CompleteSetupCommandHandlerTests.cs new file mode 100644 index 0000000..5aab2d1 --- /dev/null +++ b/source/CPDLCServer.Tests/Setup/CompleteSetupCommandHandlerTests.cs @@ -0,0 +1,59 @@ +using CPDLCServer.Auth.Administrators; +using CPDLCServer.Settings; +using CPDLCServer.Setup; +using CPDLCServer.Tests.Mocks; +using Microsoft.Extensions.DependencyInjection; +using Serilog.Core; + +namespace CPDLCServer.Tests.Setup; + +public class CompleteSetupCommandHandlerTests +{ + readonly TestAdministratorRepository _administratorRepository = new(); + readonly TestServerSettingsProvider _settingsProvider = new(new ServerSettings()); + readonly TestClock _clock = new(); + + [Fact] + public async Task Handle_AddsTheAdministratorAndTheOperatorAndCompletesTheSetup() + { + // Arrange + var setupState = CreateSetupState(); + var handler = CreateHandler(setupState); + + // Act + await handler.Handle(new CompleteSetupCommand("1234567", " VATPAC ", " privacy@example.com "), CancellationToken.None); + + // Assert + Assert.NotNull(await _administratorRepository.FindByCid("1234567", CancellationToken.None)); + + var settings = await _settingsProvider.Load(CancellationToken.None); + Assert.Equal("VATPAC", settings.OperatorName); + Assert.Equal("privacy@example.com", settings.PrivacyContact); + + Assert.True(setupState.IsConfigured); + } + + [Fact] + public async Task Handle_WhenAnAdministratorExists_Throws() + { + // Arrange + await _administratorRepository.Add(new Administrator { Cid = "1111111" }, CancellationToken.None); + var handler = CreateHandler(CreateSetupState()); + + // Act & Assert + await Assert.ThrowsAsync(() => + handler.Handle(new CompleteSetupCommand("1234567", "VATPAC", "privacy@example.com"), CancellationToken.None)); + Assert.Null(await _administratorRepository.FindByCid("1234567", CancellationToken.None)); + Assert.Equal(string.Empty, (await _settingsProvider.Load(CancellationToken.None)).OperatorName); + } + + CompleteSetupCommandHandler CreateHandler(SetupState setupState) => + new(_administratorRepository, _settingsProvider, setupState, _clock, new TestUnitOfWork(), Logger.None); + + SetupState CreateSetupState() + { + var services = new ServiceCollection(); + services.AddSingleton(_administratorRepository); + return new SetupState(services.BuildServiceProvider().GetRequiredService()); + } +} diff --git a/source/CPDLCServer.Tests/Setup/SetupStateTests.cs b/source/CPDLCServer.Tests/Setup/SetupStateTests.cs new file mode 100644 index 0000000..4644294 --- /dev/null +++ b/source/CPDLCServer.Tests/Setup/SetupStateTests.cs @@ -0,0 +1,61 @@ +using CPDLCServer.Auth.Administrators; +using CPDLCServer.Setup; +using CPDLCServer.Tests.Mocks; +using Microsoft.Extensions.DependencyInjection; + +namespace CPDLCServer.Tests.Setup; + +public class SetupStateTests +{ + readonly TestAdministratorRepository _administratorRepository = new(); + + [Fact] + public async Task Load_WhenNoAdministrator_IsNotConfigured() + { + // Arrange + var setupState = CreateSetupState(); + + // Act + await setupState.Load(CancellationToken.None); + + // Assert + Assert.False(setupState.IsConfigured); + } + + [Fact] + public async Task Load_WhenAdministratorExists_IsConfigured() + { + // Arrange + await _administratorRepository.Add(new Administrator { Cid = "1234567" }, CancellationToken.None); + var setupState = CreateSetupState(); + + // Act + await setupState.Load(CancellationToken.None); + + // Assert + Assert.True(setupState.IsConfigured); + } + + [Fact] + public async Task MarkConfigured_CompletesTheSetup() + { + // Arrange + var setupState = CreateSetupState(); + await setupState.Load(CancellationToken.None); + + // Act + setupState.MarkConfigured(); + + // Assert + Assert.True(setupState.IsConfigured); + } + + SetupState CreateSetupState() + { + var services = new ServiceCollection(); + services.AddSingleton(_administratorRepository); + var serviceProvider = services.BuildServiceProvider(); + + return new SetupState(serviceProvider.GetRequiredService()); + } +} diff --git a/source/CPDLCServer.Tests/Handlers/ProduceVatsimAdscReportsRequestHandlerTests.cs b/source/CPDLCServer.Tests/VatsimStatus/ProduceVatsimAdscReportsRequestHandlerTests.cs similarity index 69% rename from source/CPDLCServer.Tests/Handlers/ProduceVatsimAdscReportsRequestHandlerTests.cs rename to source/CPDLCServer.Tests/VatsimStatus/ProduceVatsimAdscReportsRequestHandlerTests.cs index ce04325..a7c9a04 100644 --- a/source/CPDLCServer.Tests/Handlers/ProduceVatsimAdscReportsRequestHandlerTests.cs +++ b/source/CPDLCServer.Tests/VatsimStatus/ProduceVatsimAdscReportsRequestHandlerTests.cs @@ -1,20 +1,20 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using CPDLCServer.Services; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Settings; +using CPDLCServer.VatsimStatus; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.VatsimStatus; public class ProduceVatsimAdscReportsRequestHandlerTests { static readonly TimeSpan DefaultInterval = TimeSpan.FromMinutes(10); static readonly DateTimeOffset Now = new(2026, 10, 17, 12, 0, 0, TimeSpan.Zero); static readonly DateTimeOffset LastUpdated = Now.AddSeconds(-10); + static readonly TimeSpan ReportDelay = TimeSpan.FromMinutes(5); [Fact] public async Task Handle_WhenNoReport_PublishesVatsimReportAndAcceptsContract() @@ -25,7 +25,7 @@ public async Task Handle_WhenNoReport_PublishesVatsimReportAndAcceptsContract() contract.RequestDefaultContract(DefaultInterval); var mediator = Substitute.For(); - var handler = await CreateHandler(contractRepository, new TestAdscReportRepository(), mediator); + var handler = await CreateHandler(contractRepository, mediator); // Act await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); @@ -43,18 +43,33 @@ await mediator.Received(1).Publish( } [Fact] - public async Task Handle_WhenVatsimReportIsDue_PublishesVatsimReport() + public async Task Handle_WhenContractIsNewerThanReportDelay_PublishesNothing() { // Arrange var contractRepository = new TestAdscContractRepository(); - var contract = await AddContract(contractRepository); + var contract = await AddContract(contractRepository, Now - ReportDelay + TimeSpan.FromSeconds(1)); contract.RequestDefaultContract(DefaultInterval); - var reportRepository = new TestAdscReportRepository(); - await AddReport(reportRepository, AdscReportSource.VATSIM, Now - DefaultInterval); + var mediator = Substitute.For(); + var handler = await CreateHandler(contractRepository, mediator); + + // Act + await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); + + // Assert + await mediator.DidNotReceive().Publish(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task Handle_WhenContractIsReportDelayOld_PublishesVatsimReport() + { + // Arrange + var contractRepository = new TestAdscContractRepository(); + var contract = await AddContract(contractRepository, Now - ReportDelay); + contract.RequestDefaultContract(DefaultInterval); var mediator = Substitute.For(); - var handler = await CreateHandler(contractRepository, reportRepository, mediator); + var handler = await CreateHandler(contractRepository, mediator); // Act await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); @@ -64,39 +79,37 @@ public async Task Handle_WhenVatsimReportIsDue_PublishesVatsimReport() } [Fact] - public async Task Handle_WhenVatsimReportIsNotDue_PublishesNothing() + public async Task Handle_WhenVatsimReportIsDue_PublishesVatsimReport() { // Arrange var contractRepository = new TestAdscContractRepository(); var contract = await AddContract(contractRepository); contract.RequestDefaultContract(DefaultInterval); - var reportRepository = new TestAdscReportRepository(); - await AddReport(reportRepository, AdscReportSource.VATSIM, Now.AddMinutes(-5)); + ReceiveReport(contract, AdscReportSource.VATSIM, Now - DefaultInterval); var mediator = Substitute.For(); - var handler = await CreateHandler(contractRepository, reportRepository, mediator); + var handler = await CreateHandler(contractRepository, mediator); // Act await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); // Assert - await mediator.DidNotReceive().Publish(Arg.Any(), Arg.Any()); + await mediator.Received(1).Publish(Arg.Any(), Arg.Any()); } [Fact] - public async Task Handle_WhenHoppieReportIsTwoIntervalsLate_PublishesNothing() + public async Task Handle_WhenVatsimReportIsNotDue_PublishesNothing() { // Arrange var contractRepository = new TestAdscContractRepository(); var contract = await AddContract(contractRepository); contract.RequestDefaultContract(DefaultInterval); - var reportRepository = new TestAdscReportRepository(); - await AddReport(reportRepository, AdscReportSource.Hoppie, Now - DefaultInterval * 2); + ReceiveReport(contract, AdscReportSource.VATSIM, Now.AddMinutes(-5)); var mediator = Substitute.For(); - var handler = await CreateHandler(contractRepository, reportRepository, mediator); + var handler = await CreateHandler(contractRepository, mediator); // Act await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); @@ -106,24 +119,24 @@ public async Task Handle_WhenHoppieReportIsTwoIntervalsLate_PublishesNothing() } [Fact] - public async Task Handle_WhenHoppieReportIsMoreThanTwoIntervalsLate_PublishesVatsimReport() + public async Task Handle_WhenSourceIsHoppie_PublishesNothing() { // Arrange var contractRepository = new TestAdscContractRepository(); var contract = await AddContract(contractRepository); contract.RequestDefaultContract(DefaultInterval); - var reportRepository = new TestAdscReportRepository(); - await AddReport(reportRepository, AdscReportSource.Hoppie, Now - DefaultInterval * 2 - TimeSpan.FromSeconds(1)); + // The periodic report is due, but the report must come from Hoppie + ReceiveReport(contract, AdscReportSource.Hoppie, Now - DefaultInterval * 2 - TimeSpan.FromSeconds(1)); var mediator = Substitute.For(); - var handler = await CreateHandler(contractRepository, reportRepository, mediator); + var handler = await CreateHandler(contractRepository, mediator); // Act await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); // Assert - await mediator.Received(1).Publish(Arg.Any(), Arg.Any()); + await mediator.DidNotReceive().Publish(Arg.Any(), Arg.Any()); } [Fact] @@ -136,7 +149,7 @@ public async Task Handle_WhenContractIsRejected_PublishesNothing() contract.Reject(); var mediator = Substitute.For(); - var handler = await CreateHandler(contractRepository, new TestAdscReportRepository(), mediator); + var handler = await CreateHandler(contractRepository, mediator); // Act await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); @@ -152,14 +165,13 @@ public async Task Handle_WhenDemandRequestIsSent_PublishesVatsimReportAndAccepts var contractRepository = new TestAdscContractRepository(); var contract = await AddContract(contractRepository); contract.RequestDefaultContract(DefaultInterval); - contract.RequestDemandReport(); // The periodic report is not due - var reportRepository = new TestAdscReportRepository(); - await AddReport(reportRepository, AdscReportSource.VATSIM, Now.AddMinutes(-1)); + ReceiveReport(contract, AdscReportSource.VATSIM, Now.AddMinutes(-1)); + contract.RequestDemandReport(); var mediator = Substitute.For(); - var handler = await CreateHandler(contractRepository, reportRepository, mediator); + var handler = await CreateHandler(contractRepository, mediator); // Act await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); @@ -175,13 +187,11 @@ public async Task Handle_WhenDemandOnlyContractHasHoppieReport_PublishesNothing( // Arrange var contractRepository = new TestAdscContractRepository(); var contract = await AddContract(contractRepository); + ReceiveReport(contract, AdscReportSource.Hoppie, Now.AddHours(-1)); contract.RequestDemandReport(); - var reportRepository = new TestAdscReportRepository(); - await AddReport(reportRepository, AdscReportSource.Hoppie, Now.AddHours(-1)); - var mediator = Substitute.For(); - var handler = await CreateHandler(contractRepository, reportRepository, mediator); + var handler = await CreateHandler(contractRepository, mediator); // Act await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); @@ -190,6 +200,26 @@ public async Task Handle_WhenDemandOnlyContractHasHoppieReport_PublishesNothing( await mediator.DidNotReceive().Publish(Arg.Any(), Arg.Any()); } + [Fact] + public async Task Handle_WhenHoppieReportTimedOut_PublishesVatsimReport() + { + // Arrange + var contractRepository = new TestAdscContractRepository(); + var contract = await AddContract(contractRepository); + ReceiveReport(contract, AdscReportSource.Hoppie, Now.AddHours(-1)); + contract.ReportTimedOut(); + contract.RequestDemandReport(); + + var mediator = Substitute.For(); + var handler = await CreateHandler(contractRepository, mediator); + + // Act + await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); + + // Assert + await mediator.Received(1).Publish(Arg.Any(), Arg.Any()); + } + [Fact] public async Task Handle_WhenPilotIsNotEquipped_PublishesNothing() { @@ -201,7 +231,6 @@ public async Task Handle_WhenPilotIsNotEquipped_PublishesNothing() var mediator = Substitute.For(); var handler = await CreateHandler( contractRepository, - new TestAdscReportRepository(), mediator, isAdscEquipped: false); @@ -223,7 +252,6 @@ public async Task Handle_WhenPilotIsNotEquippedAndNonEquippedAircraftAreAllowed_ var mediator = Substitute.For(); var handler = await CreateHandler( contractRepository, - new TestAdscReportRepository(), mediator, isAdscEquipped: false, allowNonEquippedAircraft: true); @@ -240,12 +268,12 @@ public async Task Handle_WhenPilotIsNotInVatsimData_PublishesNothing() { // Arrange var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("QFA1", "YBBB"); + var contract = new AdscContract("QFA1", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); await contractRepository.Add(new AdscContractKey("QFA1", "YBBB"), contract, CancellationToken.None); contract.RequestDefaultContract(DefaultInterval); var mediator = Substitute.For(); - var handler = await CreateHandler(contractRepository, new TestAdscReportRepository(), mediator); + var handler = await CreateHandler(contractRepository, mediator); // Act await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); @@ -256,7 +284,6 @@ public async Task Handle_WhenPilotIsNotInVatsimData_PublishesNothing() static async Task CreateHandler( IAdscContractRepository contractRepository, - IAdscReportRepository reportRepository, IMediator mediator, bool isAdscEquipped = true, bool allowNonEquippedAircraft = false) @@ -271,29 +298,28 @@ [new VatsimPilot("UAL123", -33.9461, 151.1772, 37000, LastUpdated, isAdscEquippe return new ProduceVatsimAdscReportsRequestHandler( contractRepository, - reportRepository, pilotRepository, - new VatsimStatusConfiguration { Enabled = true, AllowNonEquippedAircraft = allowNonEquippedAircraft }, + new TestServerSettingsProvider(new ServerSettings + { + VatsimStatusEnabled = true, + VatsimStatusAllowNonEquippedAircraft = allowNonEquippedAircraft, + VatsimStatusReportDelayMinutes = (int)ReportDelay.TotalMinutes + }), clock, mediator, Logger.None); } - static async Task AddContract(IAdscContractRepository contractRepository) + // The contract was made before the report delay, unless the test gives a different time + static async Task AddContract(IAdscContractRepository contractRepository, DateTimeOffset? created = null) { - var contract = new AdscContract("UAL123", "YBBB"); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), created ?? DateTimeOffset.MinValue); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); return contract; } - static async Task AddReport(IAdscReportRepository reportRepository, AdscReportSource source, DateTimeOffset received) + static void ReceiveReport(AdscContract contract, AdscReportSource source, DateTimeOffset timestamp) { - await reportRepository.Add( - new AircraftAdscReport( - "UAL123", - "YBBB", - new AdscReport(received.AddSeconds(-30), -33.9461, 151.1772, 37000, source), - received), - CancellationToken.None); + contract.ReportReceived(new AdscReport(timestamp, -33.9461, 151.1772, 37000, source)); } } diff --git a/source/CPDLCServer.Tests/Model/VatsimPilotTests.cs b/source/CPDLCServer.Tests/VatsimStatus/VatsimPilotTests.cs similarity index 90% rename from source/CPDLCServer.Tests/Model/VatsimPilotTests.cs rename to source/CPDLCServer.Tests/VatsimStatus/VatsimPilotTests.cs index 2fc78e1..d06f76a 100644 --- a/source/CPDLCServer.Tests/Model/VatsimPilotTests.cs +++ b/source/CPDLCServer.Tests/VatsimStatus/VatsimPilotTests.cs @@ -1,6 +1,6 @@ -using CPDLCServer.Model; +using CPDLCServer.VatsimStatus; -namespace CPDLCServer.Tests.Model; +namespace CPDLCServer.Tests.VatsimStatus; public class VatsimPilotTests { diff --git a/source/CPDLCServer/AcarsConnections/AcarsConnectionManager.cs b/source/CPDLCServer/AcarsConnections/AcarsConnectionManager.cs new file mode 100644 index 0000000..29f969d --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/AcarsConnectionManager.cs @@ -0,0 +1,411 @@ +using System.Collections.Concurrent; +using CPDLCServer.AcarsConnections.ConnectionSettings; +using CPDLCServer.AcarsConnections.Hoppie; +using CPDLCServer.AcarsConnections.Traffic; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.MessageLog; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Infrastructure; +using CPDLCServer.Logging; +using CPDLCServer.Persistence; +using CPDLCServer.Security; +using Microsoft.EntityFrameworkCore; +using Serilog.Context; + +namespace CPDLCServer.AcarsConnections; + +public interface IAcarsConnectionManager +{ + Task GetAcarsConnection(string acarsConnectionId, CancellationToken cancellationToken); + Task GetAcarsConnectionForStation(string stationId, CancellationToken cancellationToken); + Task GetConfigurationForStation(string stationId, CancellationToken cancellationToken); + Task FindAcarsConnectionId(string stationId, CancellationToken cancellationToken); + + // The IDs of the connections that are running + string[] GetAcarsConnectionIds(); + bool IsRunning(Guid settingsId); + + // Connects to the upstream ACARS network + Task Start(AcarsConnectionSettings settings, CancellationToken cancellationToken); + + // Disconnects from the upstream ACARS network. Does nothing if the connection is not running. + Task Stop(Guid settingsId, CancellationToken cancellationToken); +} + +public class AcarsConnectionManager( + IServiceScopeFactory serviceScopeFactory, + MasterKeyEncryption masterKeyEncryption, + IUnitOfWorkMediator mediator, + IClock clock, + IAdscMessageLogRepository adscMessageLogRepository, + AcarsTrafficLog trafficLog, + ILogger logger) + : BackgroundService, IAcarsConnectionManager +{ + readonly SemaphoreSlim _semaphoreSlim = new(1, 1); + readonly ConcurrentDictionary _connections = []; + readonly ILogger _logger = logger + .ForContext() + .ForContext(LogArea.PropertyName, LogArea.Acars); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + var enabledSettings = await LoadEnabledSettings(stoppingToken); + _logger.Information("Starting ACARS connection manager with {Count} enabled connections", enabledSettings.Length); + + foreach (var settings in enabledSettings) + { + await StartWithRetry(settings, stoppingToken); + } + + _logger.Information("All ACARS connections initialized"); + + try + { + await Task.Delay(Timeout.Infinite, stoppingToken); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + _logger.Information("Stopping ACARS connection manager"); + } + } + + async Task LoadEnabledSettings(CancellationToken cancellationToken) + { + await using var scope = serviceScopeFactory.CreateAsyncScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + + return await dbContext.AcarsConnections + .AsNoTracking() + .Where(s => s.Enabled) + .ToArrayAsync(cancellationToken); + } + + async Task StartWithRetry(AcarsConnectionSettings settings, CancellationToken cancellationToken) + { + const int maxRetries = 5; + var retryDelay = TimeSpan.FromSeconds(1); + + for (var attempt = 0; attempt < maxRetries; attempt++) + { + try + { + await Start(settings, cancellationToken); + return; + } + catch (Exception ex) when (attempt < maxRetries - 1) + { + _logger.Warning( + ex, + "Failed to start ACARS connection for {StationId} (attempt {Attempt}/{MaxRetries}). Retrying in {Delay}", + settings.StationIdentifier, + attempt + 1, + maxRetries, + retryDelay); + + await Task.Delay(retryDelay, cancellationToken); + retryDelay *= 2; + } + catch (Exception ex) + { + _logger.Error( + ex, + "Failed to start ACARS connection for {StationId} after {MaxRetries} attempts. The connection will not be available", + settings.StationIdentifier, + maxRetries); + break; + } + } + } + + public async Task Start(AcarsConnectionSettings settings, CancellationToken cancellationToken) + { + using (await _semaphoreSlim.LockAsync(cancellationToken)) + { + var configuration = CreateConfiguration(settings); + if (_connections.ContainsKey(configuration.AcarsConnectionId)) + throw new InvalidOperationException($"ACARS connection {configuration.AcarsConnectionId} is already running"); + + var acarsConnectionHandle = await CreateAcarsConnection(settings.Id, configuration, cancellationToken); + _connections[configuration.AcarsConnectionId] = acarsConnectionHandle; + + _logger.Information("Started ACARS connection {AcarsConnectionId}", configuration.AcarsConnectionId); + } + } + + public async Task Stop(Guid settingsId, CancellationToken cancellationToken) + { + using (await _semaphoreSlim.LockAsync(cancellationToken)) + { + var (acarsConnectionId, acarsConnectionHandle) = _connections.FirstOrDefault(c => c.Value.SettingsId == settingsId); + if (acarsConnectionHandle is null) + return; + + _connections.TryRemove(acarsConnectionId, out _); + await acarsConnectionHandle.DisposeAsync(); + + _logger.Information("Stopped ACARS connection {AcarsConnectionId}", acarsConnectionId); + } + } + + public string[] GetAcarsConnectionIds() + { + return _connections.Keys.ToArray(); + } + + public bool IsRunning(Guid settingsId) + { + return _connections.Values.Any(h => h.SettingsId == settingsId); + } + + public Task GetAcarsConnection(string acarsConnectionId, CancellationToken cancellationToken) + { + if (!_connections.TryGetValue(acarsConnectionId, out var acarsConnectionHandle)) + { + throw new ConfigurationNotFoundException(acarsConnectionId); + } + + return Task.FromResult(acarsConnectionHandle.Connection); + } + + public Task GetAcarsConnectionForStation(string stationId, CancellationToken cancellationToken) + { + var acarsConnectionHandle = _connections.Values.FirstOrDefault(h => h.Connection.StationId == stationId); + if (acarsConnectionHandle is null) + { + throw new Exception($"No ACARS connection found for station '{stationId}'"); + } + + return Task.FromResult(acarsConnectionHandle.Connection); + } + + public Task GetConfigurationForStation(string stationId, CancellationToken cancellationToken) + { + var acarsConnectionHandle = _connections.Values.FirstOrDefault(h => h.Connection.StationId == stationId); + if (acarsConnectionHandle is null) + { + throw new Exception($"No ACARS configuration found for station '{stationId}'"); + } + + return Task.FromResult(acarsConnectionHandle.Configuration); + } + + public Task FindAcarsConnectionId(string stationId, CancellationToken cancellationToken) + { + var acarsConnectionId = _connections + .Where(c => string.Equals(c.Value.Connection.StationId, stationId, StringComparison.OrdinalIgnoreCase)) + .Select(c => c.Key) + .FirstOrDefault(); + + return Task.FromResult(acarsConnectionId); + } + + AcarsConfiguration CreateConfiguration(AcarsConnectionSettings settings) + { + return settings.Type switch + { + AcarsNetworkType.Hoppie => new HoppiesConfiguration + { + Url = settings.Url, + AuthenticationCode = masterKeyEncryption.Decrypt(settings.EncryptedAuthenticationCode), + StationIdentifier = settings.StationIdentifier, + DefaultAdscReportingInterval = settings.DefaultAdscReportingInterval, + Motd = settings.Motd, + MotdDelay = TimeSpan.FromSeconds(settings.MotdDelaySeconds) + }, + _ => throw new NotSupportedException($"ACARS network type {settings.Type} is not supported") + }; + } + + async Task CreateAcarsConnection( + Guid settingsId, + AcarsConfiguration configuration, + CancellationToken cancellationToken) + { + var acarsConnectionId = configuration.AcarsConnectionId; + + IAcarsConnection acarsConnection = configuration switch + { + HoppiesConfiguration hoppieConfig => CreateHoppieConnection(hoppieConfig), + _ => throw new NotSupportedException($"ACARS configuration type {configuration.GetType().Name} is not supported") + }; + + var stationId = acarsConnection.StationId; + + var subscribeTaskCancellationSource = new CancellationTokenSource(); + var subscribeTask = Task.WhenAll( + Subscribe( + acarsConnectionId, + stationId, + acarsConnection, + mediator, + subscribeTaskCancellationSource.Token), + SubscribeAdsc( + acarsConnectionId, + stationId, + acarsConnection, + mediator, + subscribeTaskCancellationSource.Token)); + + var acarsConnectionHandle = new AcarsConnectionHandle( + settingsId, + configuration, + acarsConnection, + subscribeTask, + subscribeTaskCancellationSource); + + await acarsConnection.Connect(cancellationToken); + + _logger.Information("Connected to ACARS connection {AcarsConnectionId}", acarsConnectionId); + + return acarsConnectionHandle; + } + + HoppieAcarsConnection CreateHoppieConnection(HoppiesConfiguration configuration) + { + var httpClient = new HttpClient(); + httpClient.BaseAddress = configuration.Url; + + return new HoppieAcarsConnection( + configuration, + httpClient, + clock, + adscMessageLogRepository, + trafficLog, + _logger.ForContext()); + } + + async Task Subscribe(string acarsConnectionId, string stationId, IAcarsConnection acarsConnection, IUnitOfWorkMediator mediator, CancellationToken cancellationToken) + { + var subscriptionLogger = _logger.ForContext(LogArea.AcarsConnectionIdPropertyName, acarsConnectionId); + + try + { + await foreach (var downlinkMessage in acarsConnection.MessageReader.ReadAllAsync(cancellationToken)) + { + // TODO: Make this configurable + // Linked to the subscription, so that a stopped connection does not wait for the timeout + using var publishTimeoutCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + publishTimeoutCancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(10)); + + // The handlers of the message write the ACARS connection ID in their log entries + using var _ = LogContext.PushProperty(LogArea.AcarsConnectionIdPropertyName, acarsConnectionId); + + try + { + await mediator.Publish( + new DownlinkReceivedNotification( + acarsConnectionId, + stationId, + downlinkMessage), + publishTimeoutCancellationTokenSource.Token); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + subscriptionLogger.Information("Subscription canceled"); + return; + } + catch (OperationCanceledException) when (publishTimeoutCancellationTokenSource.Token.IsCancellationRequested) + { + subscriptionLogger.Warning("Timeout handling downlink {Downlink}", downlinkMessage); + } + catch (Exception ex) + { + subscriptionLogger.Error(ex, "Failed to relay {MessageType}", downlinkMessage.GetType()); + } + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + subscriptionLogger.Information("Subscription canceled"); + } + } + + async Task SubscribeAdsc(string acarsConnectionId, string stationId, IAcarsConnection acarsConnection, IUnitOfWorkMediator mediator, CancellationToken cancellationToken) + { + var subscriptionLogger = _logger.ForContext(LogArea.AcarsConnectionIdPropertyName, acarsConnectionId); + + try + { + await foreach (var adscMessage in acarsConnection.AdscMessageReader.ReadAllAsync(cancellationToken)) + { + // TODO: Make this configurable + // Linked to the subscription, so that a stopped connection does not wait for the timeout + using var publishTimeoutCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + publishTimeoutCancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(10)); + + // The handlers of the message write the ACARS connection ID in their log entries + using var _ = LogContext.PushProperty(LogArea.AcarsConnectionIdPropertyName, acarsConnectionId); + + try + { + await mediator.Publish( + new AdscMessageReceivedNotification( + acarsConnectionId, + stationId, + adscMessage), + publishTimeoutCancellationTokenSource.Token); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + subscriptionLogger.Information("ADS-C subscription canceled"); + return; + } + catch (OperationCanceledException) when (publishTimeoutCancellationTokenSource.Token.IsCancellationRequested) + { + subscriptionLogger.Warning("Timeout handling ADS-C message {AdscMessage}", adscMessage); + } + catch (Exception ex) + { + subscriptionLogger.Error(ex, "Failed to relay {MessageType}", adscMessage.GetType()); + } + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + subscriptionLogger.Information("ADS-C subscription canceled"); + } + } + + record AcarsConnectionHandle( + Guid SettingsId, + AcarsConfiguration Configuration, + IAcarsConnection Connection, + Task SubscribeTask, + CancellationTokenSource SubscribeCancellationTokenSource) : IAsyncDisposable + { + public async ValueTask DisposeAsync() + { + await Connection.DisposeAsync(); + + await SubscribeCancellationTokenSource.CancelAsync(); + + try + { + await SubscribeTask; + } + catch (OperationCanceledException) + { + // Expected during shutdown + } + + SubscribeCancellationTokenSource.Dispose(); + SubscribeTask.Dispose(); + } + } + + public override async Task StopAsync(CancellationToken cancellationToken) + { + _logger.Information("Stopping ACARS connection manager and disposing all connections"); + + await base.StopAsync(cancellationToken); + + foreach (var (_, connectionHandle) in _connections) + { + await connectionHandle.DisposeAsync(); + } + + _connections.Clear(); + _semaphoreSlim.Dispose(); + } +} diff --git a/source/CPDLCServer/AcarsConnections/AcarsConnectionsServiceCollectionExtensions.cs b/source/CPDLCServer/AcarsConnections/AcarsConnectionsServiceCollectionExtensions.cs new file mode 100644 index 0000000..0b0ff43 --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/AcarsConnectionsServiceCollectionExtensions.cs @@ -0,0 +1,20 @@ +using CPDLCServer.AcarsConnections.Stations; +using CPDLCServer.AcarsConnections.Traffic; + +namespace CPDLCServer.AcarsConnections; + +public static class AcarsConnectionsServiceCollectionExtensions +{ + public static IServiceCollection AddAcarsConnections(this IServiceCollection services) + { + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddHostedService(sp => sp.GetRequiredService()); + + services.AddSingleton(); + services.AddHostedService(); + + return services; + } +} diff --git a/source/CPDLCServer/AcarsConnections/ConfigurationNotFoundException.cs b/source/CPDLCServer/AcarsConnections/ConfigurationNotFoundException.cs new file mode 100644 index 0000000..e4671ed --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/ConfigurationNotFoundException.cs @@ -0,0 +1,4 @@ +namespace CPDLCServer.AcarsConnections; + +public sealed class ConfigurationNotFoundException(string acarsConnectionId) + : Exception($"No ACARS configuration found for ACARS connection ID '{acarsConnectionId}'"); \ No newline at end of file diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettings.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettings.cs new file mode 100644 index 0000000..fbaf100 --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettings.cs @@ -0,0 +1,70 @@ +using System.ComponentModel.DataAnnotations; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; + +namespace CPDLCServer.AcarsConnections.ConnectionSettings; + +public enum AcarsNetworkType +{ + Hoppie +} + +// The settings of an ACARS connection. The initial values are the default values. +// The settings page binds its form to this type, so the form cannot set the ID or the encrypted authentication code. +public class AcarsConnectionSettings +{ + public const int MaxMotdLength = 200; + + [BindNever] + public Guid Id { get; init; } = Guid.NewGuid(); + + public AcarsNetworkType Type { get; set; } = AcarsNetworkType.Hoppie; + + // The server starts only the enabled connections + public bool Enabled { get; set; } = true; + + [Required] + [RegularExpression("^[A-Za-z0-9]+$", ErrorMessage = "Use only letters and digits.")] + public string StationIdentifier { get; set; } = string.Empty; + + [Required] + public Uri Url { get; set; } = new("http://www.hoppie.nl/acars/system/connect.html"); + + // Encrypted with the master key. Use MasterKeyEncryption to decrypt it. The plain code is not kept. + [BindNever] + [ValidateNever] + public string EncryptedAuthenticationCode { get; set; } = string.Empty; + + [Range(1, int.MaxValue)] + public int DefaultAdscReportingInterval { get; set; } = 10; + + // A CPDLC free text message that is sent to each aircraft after it logs on. "/" is not accepted, because the + // Hoppie packet uses it as a separator. + [StringLength(MaxMotdLength)] + [RegularExpression(@"^[A-Za-z0-9 .,:?'()+\-\r\n]*$", ErrorMessage = "Use only letters, digits, spaces and . , : ? ' ( ) + -")] + public string? Motd { get; set; } + + [Range(0, 3600)] + public int MotdDelaySeconds { get; set; } = 30; + + // Free text for the users. The server does not use it. + [StringLength(2000)] + public string? Notes { get; set; } + + // The ID of the running connection. The log entries and the traffic log use it. + public string AcarsConnectionId => Type switch + { + AcarsNetworkType.Hoppie => $"Hoppies/{StationIdentifier.ToUpperInvariant()}", + _ => throw new NotSupportedException($"ACARS network type {Type} is not supported") + }; + + // CPDLC free text is upper case on one line. An empty message is no message. + public static string? NormalizeMotd(string? motd) + { + if (string.IsNullOrWhiteSpace(motd)) + return null; + + var words = motd.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); + return string.Join(' ', words).ToUpperInvariant(); + } +} diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettingsConfiguration.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettingsConfiguration.cs new file mode 100644 index 0000000..835c716 --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettingsConfiguration.cs @@ -0,0 +1,24 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.AcarsConnections.ConnectionSettings; + +public class AcarsConnectionSettingsConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("AcarsConnections"); + + builder.HasKey(c => c.Id); + builder.Property(c => c.Id).ValueGeneratedNever(); + + builder.Property(c => c.Type).HasConversion(); + builder.Property(c => c.Url).HasConversion(); + + // Calculated from the type and the station identifier + builder.Ignore(c => c.AcarsConnectionId); + + // The ACARS connection ID comes from the station identifier, so only one connection can use a station identifier + builder.HasIndex(c => c.StationIdentifier).IsUnique(); + } +} diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/CreateAcarsConnectionCommand.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/CreateAcarsConnectionCommand.cs new file mode 100644 index 0000000..87c734e --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/CreateAcarsConnectionCommand.cs @@ -0,0 +1,6 @@ +using MediatR; + +namespace CPDLCServer.AcarsConnections.ConnectionSettings; + +// The authentication code is plain text. The handler encrypts it. +public record CreateAcarsConnectionCommand(AcarsConnectionSettings Settings, string? AuthenticationCode) : IRequest; diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/CreateAcarsConnectionCommandHandler.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/CreateAcarsConnectionCommandHandler.cs new file mode 100644 index 0000000..ee3695f --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/CreateAcarsConnectionCommandHandler.cs @@ -0,0 +1,34 @@ +using CPDLCServer.Persistence; +using CPDLCServer.Security; +using MediatR; + +namespace CPDLCServer.AcarsConnections.ConnectionSettings; + +public class CreateAcarsConnectionCommandHandler( + CpdlcDbContext dbContext, + MasterKeyEncryption masterKeyEncryption, + IAcarsConnectionManager acarsConnectionManager, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public Task Handle(CreateAcarsConnectionCommand request, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(request.AuthenticationCode)) + throw new ArgumentException("An authentication code is required for a new ACARS connection"); + + var settings = request.Settings; + settings.StationIdentifier = settings.StationIdentifier.ToUpperInvariant(); + settings.Motd = AcarsConnectionSettings.NormalizeMotd(settings.Motd); + settings.EncryptedAuthenticationCode = masterKeyEncryption.Encrypt(request.AuthenticationCode); + + dbContext.AcarsConnections.Add(settings); + + logger.Information("ACARS connection for {StationId} created", settings.StationIdentifier); + + if (settings.Enabled) + unitOfWork.AfterCommit(ct => acarsConnectionManager.Start(settings, ct)); + + return Task.FromResult(settings.Id); + } +} diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/DeleteAcarsConnectionCommand.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/DeleteAcarsConnectionCommand.cs new file mode 100644 index 0000000..b24e165 --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/DeleteAcarsConnectionCommand.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.AcarsConnections.ConnectionSettings; + +public record DeleteAcarsConnectionCommand(Guid Id) : IRequest; diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/DeleteAcarsConnectionCommandHandler.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/DeleteAcarsConnectionCommandHandler.cs new file mode 100644 index 0000000..b6548a3 --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/DeleteAcarsConnectionCommandHandler.cs @@ -0,0 +1,28 @@ +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.AcarsConnections.ConnectionSettings; + +public class DeleteAcarsConnectionCommandHandler( + CpdlcDbContext dbContext, + IAcarsConnectionManager acarsConnectionManager, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(DeleteAcarsConnectionCommand request, CancellationToken cancellationToken) + { + var settings = await dbContext.AcarsConnections.FindAsync([request.Id], cancellationToken); + if (settings is null) + { + logger.Warning("ACARS connection {Id} not found for deletion", request.Id); + return; + } + + dbContext.AcarsConnections.Remove(settings); + + logger.Information("ACARS connection for {StationId} deleted", settings.StationIdentifier); + + unitOfWork.AfterCommit(ct => acarsConnectionManager.Stop(request.Id, ct)); + } +} diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/UpdateAcarsConnectionCommand.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/UpdateAcarsConnectionCommand.cs new file mode 100644 index 0000000..00e360d --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/UpdateAcarsConnectionCommand.cs @@ -0,0 +1,6 @@ +using MediatR; + +namespace CPDLCServer.AcarsConnections.ConnectionSettings; + +// The authentication code is plain text. An empty value keeps the current authentication code. +public record UpdateAcarsConnectionCommand(Guid Id, AcarsConnectionSettings Settings, string? AuthenticationCode) : IRequest; diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/UpdateAcarsConnectionCommandHandler.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/UpdateAcarsConnectionCommandHandler.cs new file mode 100644 index 0000000..38a3d0a --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/UpdateAcarsConnectionCommandHandler.cs @@ -0,0 +1,45 @@ +using CPDLCServer.Persistence; +using CPDLCServer.Security; +using MediatR; + +namespace CPDLCServer.AcarsConnections.ConnectionSettings; + +public class UpdateAcarsConnectionCommandHandler( + CpdlcDbContext dbContext, + MasterKeyEncryption masterKeyEncryption, + IAcarsConnectionManager acarsConnectionManager, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(UpdateAcarsConnectionCommand request, CancellationToken cancellationToken) + { + var settings = await dbContext.AcarsConnections.FindAsync([request.Id], cancellationToken); + if (settings is null) + throw new InvalidOperationException($"ACARS connection {request.Id} not found"); + + var changes = request.Settings; + settings.Type = changes.Type; + settings.Enabled = changes.Enabled; + settings.StationIdentifier = changes.StationIdentifier.ToUpperInvariant(); + settings.Url = changes.Url; + settings.DefaultAdscReportingInterval = changes.DefaultAdscReportingInterval; + settings.Motd = AcarsConnectionSettings.NormalizeMotd(changes.Motd); + settings.MotdDelaySeconds = changes.MotdDelaySeconds; + settings.Notes = changes.Notes; + + if (!string.IsNullOrWhiteSpace(request.AuthenticationCode)) + settings.EncryptedAuthenticationCode = masterKeyEncryption.Encrypt(request.AuthenticationCode); + + logger.Information("ACARS connection for {StationId} updated", settings.StationIdentifier); + + // Start the connection again, so that it uses the new settings + unitOfWork.AfterCommit(async ct => + { + await acarsConnectionManager.Stop(settings.Id, ct); + + if (settings.Enabled) + await acarsConnectionManager.Start(settings, ct); + }); + } +} diff --git a/source/CPDLCServer/Clients/HoppieAcarsClient.cs b/source/CPDLCServer/AcarsConnections/Hoppie/HoppieAcarsConnection.cs similarity index 89% rename from source/CPDLCServer/Clients/HoppieAcarsClient.cs rename to source/CPDLCServer/AcarsConnections/Hoppie/HoppieAcarsConnection.cs index ae2c0d9..062a471 100644 --- a/source/CPDLCServer/Clients/HoppieAcarsClient.cs +++ b/source/CPDLCServer/AcarsConnections/Hoppie/HoppieAcarsConnection.cs @@ -1,624 +1,668 @@ -using System.Globalization; -using System.Threading.Channels; -using CPDLCServer.Exceptions; -using CPDLCServer.Infrastructure; -using CPDLCServer.Model; -using CPDLCServer.Persistence; - -namespace CPDLCServer.Clients; - -// TODO: Accept encoded messages via the API (i.e. UMxxx), translate from within the client. - -public class HoppieAcarsClient : IAcarsClient -{ - readonly Dictionary _uplinkMessageTranslations = new() - { - { "END SERVICE", "LOGOFF" } - }; - - readonly HoppiesConfiguration _configuration; - readonly HttpClient _httpClient; - readonly IClock _clock; - readonly IAdscMessageLogRepository _adscMessageLogRepository; - readonly ILogger _logger; - - readonly Channel _messageChannel = Channel.CreateUnbounded(); - readonly Channel _adscMessageChannel = Channel.CreateUnbounded(); - readonly Random _random = Random.Shared; - - CancellationTokenSource? _pollCancellationTokenSource; - Task? _pollTask; - DateTimeOffset? _lastSendTime; - - bool _disposed; - - public ChannelReader MessageReader => _messageChannel.Reader; - public ChannelReader AdscMessageReader => _adscMessageChannel.Reader; - public string StationId => _configuration.StationIdentifier; - - public HoppieAcarsClient(HoppiesConfiguration configuration, HttpClient httpClient, IClock clock, IAdscMessageLogRepository adscMessageLogRepository, ILogger logger) - { - _configuration = configuration; - _httpClient = httpClient; - _httpClient.Timeout = TimeSpan.FromSeconds(15); - _clock = clock; - _adscMessageLogRepository = adscMessageLogRepository; - _logger = logger.ForContext("ClientId", _configuration.ClientId); - } - - public Task Connect(CancellationToken cancellationToken) - { - if (_disposed) - throw new ObjectDisposedException(nameof(HoppieAcarsClient)); - - _pollCancellationTokenSource = new CancellationTokenSource(); - _pollTask = Poll(_pollCancellationTokenSource.Token); - - _logger.Information("Connected to Hoppies ACARS network"); - - return Task.CompletedTask; - } - - public async Task Send(UplinkMessage message, CancellationToken cancellationToken) - { - if (_disposed) - throw new ObjectDisposedException(nameof(HoppieAcarsClient)); - - var packet = SerializeCpdlcMessage(message); - await SendPacket(message.Recipient, "cpdlc", packet, cancellationToken); - } - - public async Task RequestPeriodicAdscContract(string callsign, TimeSpan reportingInterval, CancellationToken cancellationToken) - { - if (_disposed) - throw new ObjectDisposedException(nameof(HoppieAcarsClient)); - - var reportingIntervalSeconds = (int)reportingInterval.TotalSeconds; - if (reportingIntervalSeconds <= 0) - throw new ArgumentOutOfRangeException(nameof(reportingInterval), reportingInterval, "Reporting interval must be one second or more"); - - await SendAdscPacket(callsign, $"REQUEST PERIODIC {reportingIntervalSeconds}", cancellationToken); - } - - // Hoppie has no separate demand contract. A periodic request with an interval of zero asks for one report. - public async Task RequestAdscDemandReport(string callsign, CancellationToken cancellationToken) - { - if (_disposed) - throw new ObjectDisposedException(nameof(HoppieAcarsClient)); - - await SendAdscPacket(callsign, "REQUEST PERIODIC 0", cancellationToken); - } - - public async Task CancelAdscContract(string callsign, CancellationToken cancellationToken) - { - if (_disposed) - throw new ObjectDisposedException(nameof(HoppieAcarsClient)); - - await SendAdscPacket(callsign, "REQUEST CANCEL", cancellationToken); - } - - async Task SendAdscPacket(string callsign, string packet, CancellationToken cancellationToken) - { - await SendPacket(callsign, "ads-c", packet, cancellationToken); - await LogAdscPacket(callsign, AdscMessageDirection.Uplink, packet, cancellationToken); - } - - async Task LogAdscPacket(string callsign, AdscMessageDirection direction, string packet, CancellationToken cancellationToken) - { - var entry = new AdscMessageLogEntry( - _clock.UtcNow(), - _configuration.ClientId, - _configuration.StationIdentifier, - callsign, - direction, - packet); - await _adscMessageLogRepository.Add(entry, cancellationToken); - } - - async Task SendPacket(string to, string messageType, string packet, CancellationToken cancellationToken) - { - var parameters = new Dictionary - { - ["logon"] = _configuration.AuthenticationCode, - ["network"] = _configuration.FlightSimulationNetwork, - ["from"] = _configuration.StationIdentifier, - ["to"] = to, - ["type"] = messageType - }; - - if (!string.IsNullOrEmpty(packet)) - parameters["packet"] = packet; - - var content = new FormUrlEncodedContent(parameters); - - try - { - _logger.Verbose("Sending {MessageType} to {Recipient} with packet {Packet}", messageType, to, packet); - var response = await _httpClient.PostAsync(_configuration.Url, content, cancellationToken); - response.EnsureSuccessStatusCode(); - - var responseText = await response.Content.ReadAsStringAsync(cancellationToken); - _logger.Verbose("Send response: {Response}", responseText); - - _lastSendTime = _clock.UtcNow(); - } - catch (HttpRequestException ex) - { - _logger.Error(ex, "Failed to send message"); - throw; - } - catch (TaskCanceledException ex) when (ex.CancellationToken != cancellationToken) - { - _logger.Warning("Send request timed out, skipping"); - } - } - - public async Task ListConnections(CancellationToken cancellationToken) - { - if (_disposed) - throw new ObjectDisposedException(nameof(HoppieAcarsClient)); - - var parameters = new Dictionary - { - ["logon"] = _configuration.AuthenticationCode, - ["from"] = _configuration.StationIdentifier, - ["to"] = "SERVER", - ["type"] = "ping", - ["packet"] = "ALL-CALLSIGNS" - }; - - var content = new FormUrlEncodedContent(parameters); - - try - { - _logger.Verbose("Listing connections"); - var response = await _httpClient.PostAsync(_configuration.Url, content, cancellationToken); - response.EnsureSuccessStatusCode(); - - var responseText = await response.Content.ReadAsStringAsync(cancellationToken); - _logger.Verbose("ListConnections response: {Response}", responseText); - - // Parse the response to extract callsigns - if (string.IsNullOrWhiteSpace(responseText)) - return Array.Empty(); - - // Strip "ok" prefix if present - if (responseText.StartsWith("ok", StringComparison.OrdinalIgnoreCase)) - { - responseText = responseText[2..].TrimStart(); - } - - if (string.IsNullOrWhiteSpace(responseText)) - return Array.Empty(); - - // Strip curly braces if present - if (responseText.StartsWith('{') && responseText.EndsWith('}')) - { - responseText = responseText[1..^1].Trim(); - } - - if (string.IsNullOrWhiteSpace(responseText)) - return Array.Empty(); - - // The response contains space-separated callsigns - var callsigns = responseText - .Split(' ', StringSplitOptions.RemoveEmptyEntries) - .Where(s => !string.IsNullOrWhiteSpace(s)) - .ToArray(); - - _logger.Information("Found {Count} active connections", callsigns.Length); - return callsigns; - } - catch (HttpRequestException ex) - { - _logger.Error(ex, "Failed to list connections"); - throw; - } - catch (TaskCanceledException ex) when (ex.CancellationToken != cancellationToken) - { - _logger.Warning("ListConnections request timed out"); - return Array.Empty(); - } - } - - public async Task Disconnect(CancellationToken cancellationToken) - { - if (_disposed) - throw new ObjectDisposedException(nameof(HoppieAcarsClient)); - - if (_pollCancellationTokenSource is not null) - await _pollCancellationTokenSource.CancelAsync(); - - if (_pollTask is not null) - await _pollTask; - - _logger.Information("Disconnected from Hoppies ACARS network"); - } - - async Task Poll(CancellationToken cancellationToken) - { - try - { - while (!cancellationToken.IsCancellationRequested) - { - try - { - _logger.Verbose("Polling for messages"); - - var parameters = new Dictionary - { - ["logon"] = _configuration.AuthenticationCode, - ["from"] = _configuration.StationIdentifier, - ["to"] = "SERVER", - ["type"] = "poll" - }; - - var content = new FormUrlEncodedContent(parameters); - var response = await _httpClient.PostAsync(_configuration.Url, content, cancellationToken); - response.EnsureSuccessStatusCode(); - - var responseText = await response.Content.ReadAsStringAsync(cancellationToken); - - _logger.Verbose("Poll response: {Response}", responseText); - - if (!string.IsNullOrWhiteSpace(responseText) && responseText != "ok") - { - await ParseAndPublishDownlinkMessages(responseText, cancellationToken); - } - } - catch (HttpRequestException ex) - { - _logger.Error(ex, "Poll request failed"); - } - catch (TaskCanceledException ex) when (ex.CancellationToken != cancellationToken) - { - _logger.Warning("Poll request timed out, skipping this attempt"); - } - catch (Exception ex) - { - _logger.Error(ex, "Unhandled exception when polling messages"); - } - - var pollInterval = GetPollInterval(); - _logger.Verbose("Poll completed, waiting {PollInterval}", pollInterval); - await Task.Delay(pollInterval, cancellationToken); - } - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - _logger.Information("Stopping poll task"); - } - catch (Exception ex) - { - _logger.Fatal(ex, "Unhandled exception when polling messages"); - } - } - - async Task ParseAndPublishDownlinkMessages(string responseText, CancellationToken cancellationToken) - { - try - { - if (responseText.StartsWith("ok", StringComparison.OrdinalIgnoreCase)) - { - responseText = responseText[2..].TrimStart(); - } - - if (string.IsNullOrWhiteSpace(responseText)) - return; - - if (responseText.StartsWith("error", StringComparison.OrdinalIgnoreCase)) - { - _logger.Warning("Hoppie server error: {Error}", responseText); - return; - } - - var messages = ExtractMessages(responseText); - - _logger.Verbose("Extracted {Count} messages", messages.Count); - - foreach (var messageText in messages) - { - _logger.Verbose("Extracted: {Message}", messageText); - var (from, type, packet) = ParseMessage(messageText); - - switch (type.ToLowerInvariant()) - { - case "cpdlc": - var downlink = ParseCpdlcDownlink(from, packet); - _logger.Information("Received {MessageType} from {From}", type, from); - _messageChannel.Writer.TryWrite(downlink); - break; - - case "ads-c": - // Log the packet before it is parsed, so that packets that cannot be parsed are also in the log - await LogAdscPacket(from, AdscMessageDirection.Downlink, packet, cancellationToken); - - var adscMessage = ParseAdscDownlink(from, packet); - if (adscMessage is null) - break; - - _logger.Information("Received {MessageType} from {From}", type, from); - _adscMessageChannel.Writer.TryWrite(adscMessage); - break; - - default: - _logger.Information("Unsupported message type: {Type}", type); - break; - } - } - } - catch (Exception ex) - { - throw new MessageParseException("Failed to parse downlink messages", ex); - } - } - - static List ExtractMessages(string responseText) - { - var messages = new List(); - var depth = 0; - var currentMessage = new System.Text.StringBuilder(); - - for (var i = 0; i < responseText.Length; i++) - { - var c = responseText[i]; - - if (c == '{') - { - depth++; - if (depth == 1) - continue; - } - else if (c == '}') - { - depth--; - if (depth == 0) - { - messages.Add(currentMessage.ToString()); - currentMessage.Clear(); - continue; - } - } - - if (depth > 0) - { - currentMessage.Append(c); - } - } - - return messages; - } - - static (string from, string type, string packet) ParseMessage(string messageText) - { - var firstBraceIndex = messageText.IndexOf('{'); - if (firstBraceIndex == -1) - { - var parts = messageText.Split(' ', StringSplitOptions.RemoveEmptyEntries); - if (parts.Length < 2) - throw new Exception($"Invalid message format: {messageText}"); - - return (parts[0], parts[1], parts.Length > 2 ? string.Join(" ", parts[2..]) : string.Empty); - } - - var headerParts = messageText[..firstBraceIndex].Split(' ', StringSplitOptions.RemoveEmptyEntries); - if (headerParts.Length < 2) - throw new Exception($"Invalid message format: {messageText}"); - - var packet = messageText[(firstBraceIndex + 1)..]; - if (packet.EndsWith('}')) - packet = packet[..^1]; - - return (headerParts[0], headerParts[1], packet); - } - - ReceivedDownlink ParseCpdlcDownlink(string from, string packet) - { - if (packet.StartsWith("/DATA1/", StringComparison.OrdinalIgnoreCase)) - return ParseData1Downlink(from, packet); - - var parts = packet.Split('/', 6); - if (parts.Length != 6) - throw new MessageParseException($"Invalid CPDLC packet: Expected 6 components, got {parts.Length}: \"{packet}\""); - - var messageId = !string.IsNullOrEmpty(parts[2]) ? int.Parse(parts[2]) : -1; - int? replyToId = !string.IsNullOrEmpty(parts[3]) ? int.Parse(parts[3]) : null; - var responseType = parts[4] switch - { - "N" => CpdlcDownlinkResponseType.NoResponse, - "Y" => CpdlcDownlinkResponseType.ResponseRequired, - _ => throw new NotSupportedException($"Unsupported CPDLC downlink response type: {parts[4]}") - }; - - var content = parts[5]; - - return new ReceivedDownlink( - messageId, - replyToId, - from, - responseType, - AlertType.None, - content, - _clock.UtcNow()); - } - - // Some aircraft (for example, PMDG) send position reports in this format: - // /DATA1/*/*/*/*/FL380/*/0.84/ - // - // OVER MEPAB AT 0501Z, FL380, - // ESTIMATING ISTEM AT 0533Z, - // ... - // The first line is a header. The lines after the header contain the text of the report. - ReceivedDownlink ParseData1Downlink(string from, string packet) - { - var lines = packet.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - var content = lines.Length > 1 - ? string.Join(" ", lines[1..]) - : packet; - - return new ReceivedDownlink( - -1, - null, - from, - CpdlcDownlinkResponseType.NoResponse, - AlertType.None, - content, - _clock.UtcNow()); - } - - // Packet formats: - // REPORT [] - // REJECT - ReceivedAdscMessage? ParseAdscDownlink(string from, string packet) - { - var parts = packet.Split(' ', StringSplitOptions.RemoveEmptyEntries); - if (parts.Length == 0) - throw new MessageParseException("Invalid ADS-C packet: Packet is empty"); - - switch (parts[0]) - { - case "REJECT": - return new ReceivedAdscRejection(from, _clock.UtcNow()); - - case "REPORT": - if (parts.Length < 6) - throw new MessageParseException($"Invalid ADS-C report: Expected 6 or more components, got {parts.Length}: \"{packet}\""); - - if (!TryParseCoordinate(parts[3], 'N', 'S', 90, out var latitude) || - !TryParseCoordinate(parts[4], 'E', 'W', 180, out var longitude)) - { - _logger.Warning("Ignoring ADS-C report from {From}: Cannot read the position: \"{Packet}\"", from, packet); - return null; - } - - // Aircraft do not agree on the format of the optional groups, so ignore them - var report = new AdscReport( - ParseAdscTimestamp(parts[2]), - latitude, - longitude, - ParseAdscAltitude(parts[5]), - AdscReportSource.Hoppie); - - return new ReceivedAdscReport(from, report, _clock.UtcNow()); - - default: - throw new MessageParseException($"Unsupported ADS-C packet: \"{packet}\""); - } - } - - // Aircraft send coordinates in different formats. - // For example, a latitude can be "-33.9461", "S33.9461", or "33.9461S". - static bool TryParseCoordinate(string text, char positiveHemisphere, char negativeHemisphere, double maximum, out double coordinate) - { - coordinate = 0; - - var number = text.ToUpperInvariant(); - var sign = 1; - if (number.Length > 1 && (number[0] == positiveHemisphere || number[0] == negativeHemisphere)) - { - sign = number[0] == negativeHemisphere ? -1 : 1; - number = number[1..]; - } - else if (number.Length > 1 && (number[^1] == positiveHemisphere || number[^1] == negativeHemisphere)) - { - sign = number[^1] == negativeHemisphere ? -1 : 1; - number = number[..^1]; - } - - if (!double.TryParse(number, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var value)) - return false; - - coordinate = sign * value; - return Math.Abs(coordinate) <= maximum; - } - - // Some aircraft send the altitude in feet, and some send it in hundreds of feet. - // Below 10,000, the altitude is in hundreds of feet. - static int ParseAdscAltitude(string text) - { - var altitude = int.Parse(text, CultureInfo.InvariantCulture); - return altitude < 10_000 ? altitude * 100 : altitude; - } - - // The report time has the day of the month, the hour, and the minute (ddHHmm) in UTC. - // Use the current month, or the previous month if the day is in the future. - DateTimeOffset ParseAdscTimestamp(string text) - { - if (text.Length != 6) - throw new MessageParseException($"Invalid ADS-C report time: \"{text}\""); - - var day = int.Parse(text[..2], CultureInfo.InvariantCulture); - var hour = int.Parse(text[2..4], CultureInfo.InvariantCulture); - var minute = int.Parse(text[4..], CultureInfo.InvariantCulture); - - var now = _clock.UtcNow(); - var month = new DateTimeOffset(now.Year, now.Month, 1, 0, 0, 0, TimeSpan.Zero); - if (day > now.Day) - month = month.AddMonths(-1); - - return month.AddDays(day - 1).AddHours(hour).AddMinutes(minute); - } - - TimeSpan GetPollInterval() - { - if (_lastSendTime.HasValue) - { - var timeSinceLastSend = _clock.UtcNow() - _lastSendTime.Value; - if (timeSinceLastSend < TimeSpan.FromMinutes(1)) - { - return TimeSpan.FromSeconds(20); - } - } - - return TimeSpan.FromSeconds(_random.Next(45, 76)); - } - - string SerializeCpdlcMessage(UplinkMessage uplinkMessage) - { - var responseType = uplinkMessage.ResponseType switch - { - CpdlcUplinkResponseType.NoResponse => "NE", - CpdlcUplinkResponseType.WilcoUnable => "WU", - CpdlcUplinkResponseType.AffirmativeNegative => "AN", - CpdlcUplinkResponseType.Roger => "R", - _ => throw new ArgumentException($"Unexpected CpdlcResponseType: {uplinkMessage.ResponseType}") - }; - - var replyToId = uplinkMessage.MessageReference is not null - ? uplinkMessage.MessageReference.ToString() - : string.Empty; - - var content = GetTranslatedContent(uplinkMessage); - - return $"/data2/{uplinkMessage.MessageId}/{replyToId}/{responseType}/{content}"; - } - - string GetTranslatedContent(UplinkMessage uplinkMessage) - { - var translatedContent = uplinkMessage.Content; - foreach (var uplinkMessageTranslation in _uplinkMessageTranslations) - { - translatedContent = translatedContent.Replace(uplinkMessageTranslation.Key, uplinkMessageTranslation.Value); - } - - return translatedContent; - } - - public async ValueTask DisposeAsync() - { - if (_disposed) - return; - - await Disconnect(CancellationToken.None); - - if (_pollTask is not null) - _pollTask.Dispose(); - - if (_pollCancellationTokenSource is not null) - _pollCancellationTokenSource.Dispose(); - - _httpClient.Dispose(); - - _disposed = true; - } -} +using System.Diagnostics; +using System.Globalization; +using System.Threading.Channels; +using CPDLCServer.AcarsConnections.Traffic; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.MessageLog; +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Infrastructure; +using CPDLCServer.Logging; + +namespace CPDLCServer.AcarsConnections.Hoppie; + +// TODO: Accept encoded messages via the API (i.e. UMxxx), translate from within the connection. + +public class HoppieAcarsConnection : IAcarsConnection +{ + // The server is only for VATSIM + const string FlightSimulationNetwork = "VATSIM"; + + readonly Dictionary _uplinkMessageTranslations = new() + { + { "END SERVICE", "LOGOFF" } + }; + + readonly HoppiesConfiguration _configuration; + readonly HttpClient _httpClient; + readonly IClock _clock; + readonly IAdscMessageLogRepository _adscMessageLogRepository; + readonly AcarsTrafficLog _trafficLog; + readonly ILogger _logger; + + readonly Channel _messageChannel = Channel.CreateUnbounded(); + readonly Channel _adscMessageChannel = Channel.CreateUnbounded(); + readonly Random _random = Random.Shared; + + CancellationTokenSource? _pollCancellationTokenSource; + Task? _pollTask; + DateTimeOffset? _lastSendTime; + + bool _disposed; + + public ChannelReader MessageReader => _messageChannel.Reader; + public ChannelReader AdscMessageReader => _adscMessageChannel.Reader; + public string StationId => _configuration.StationIdentifier; + + public HoppieAcarsConnection( + HoppiesConfiguration configuration, + HttpClient httpClient, + IClock clock, + IAdscMessageLogRepository adscMessageLogRepository, + AcarsTrafficLog trafficLog, + ILogger logger) + { + _configuration = configuration; + _httpClient = httpClient; + _httpClient.Timeout = TimeSpan.FromSeconds(15); + _clock = clock; + _adscMessageLogRepository = adscMessageLogRepository; + _trafficLog = trafficLog; + _logger = logger + .ForContext(LogArea.PropertyName, LogArea.Acars) + .ForContext(LogArea.AcarsConnectionIdPropertyName, _configuration.AcarsConnectionId); + } + + public Task Connect(CancellationToken cancellationToken) + { + if (_disposed) + throw new ObjectDisposedException(nameof(HoppieAcarsConnection)); + + _pollCancellationTokenSource = new CancellationTokenSource(); + _pollTask = Poll(_pollCancellationTokenSource.Token); + + _logger.Information("Connected to Hoppies ACARS network"); + + return Task.CompletedTask; + } + + public async Task Send(UplinkMessage message, CancellationToken cancellationToken) + { + if (_disposed) + throw new ObjectDisposedException(nameof(HoppieAcarsConnection)); + + var packet = SerializeCpdlcMessage(message); + await SendPacket(message.Recipient, "cpdlc", packet, cancellationToken); + } + + public async Task RequestPeriodicAdscContract(string callsign, TimeSpan reportingInterval, CancellationToken cancellationToken) + { + if (_disposed) + throw new ObjectDisposedException(nameof(HoppieAcarsConnection)); + + var reportingIntervalSeconds = (int)reportingInterval.TotalSeconds; + if (reportingIntervalSeconds <= 0) + throw new ArgumentOutOfRangeException(nameof(reportingInterval), reportingInterval, "Reporting interval must be one second or more"); + + await SendAdscPacket(callsign, $"REQUEST PERIODIC {reportingIntervalSeconds}", cancellationToken); + } + + // Hoppie has no separate demand contract. A periodic request with an interval of zero asks for one report. + public async Task RequestAdscDemandReport(string callsign, CancellationToken cancellationToken) + { + if (_disposed) + throw new ObjectDisposedException(nameof(HoppieAcarsConnection)); + + await SendAdscPacket(callsign, "REQUEST PERIODIC 0", cancellationToken); + } + + public async Task CancelAdscContract(string callsign, CancellationToken cancellationToken) + { + if (_disposed) + throw new ObjectDisposedException(nameof(HoppieAcarsConnection)); + + await SendAdscPacket(callsign, "REQUEST CANCEL", cancellationToken); + } + + async Task SendAdscPacket(string callsign, string packet, CancellationToken cancellationToken) + { + await SendPacket(callsign, "ads-c", packet, cancellationToken); + await LogAdscPacket(callsign, AdscMessageDirection.Uplink, packet, cancellationToken); + } + + async Task LogAdscPacket(string callsign, AdscMessageDirection direction, string packet, CancellationToken cancellationToken) + { + var entry = new AdscMessageLogEntry( + _clock.UtcNow(), + _configuration.AcarsConnectionId, + _configuration.StationIdentifier, + callsign, + direction, + packet); + await _adscMessageLogRepository.Add(entry, cancellationToken); + } + + async Task SendPacket(string to, string messageType, string packet, CancellationToken cancellationToken) + { + var parameters = new Dictionary + { + ["logon"] = _configuration.AuthenticationCode, + ["network"] = FlightSimulationNetwork, + ["from"] = _configuration.StationIdentifier, + ["to"] = to, + ["type"] = messageType + }; + + if (!string.IsNullOrEmpty(packet)) + parameters["packet"] = packet; + + try + { + _logger.Verbose("Sending {MessageType} to {Recipient} with packet {Packet}", messageType, to, packet); + var responseText = await Post(parameters, cancellationToken); + _logger.Verbose("Send response: {Response}", responseText); + + _lastSendTime = _clock.UtcNow(); + } + catch (HttpRequestException ex) + { + _logger.Error(ex, "Failed to send message"); + throw; + } + catch (TaskCanceledException ex) when (ex.CancellationToken != cancellationToken) + { + _logger.Warning("Send request timed out, skipping"); + } + } + + // Sends a request to the ACARS network, and keeps the request and the response in the traffic log + async Task Post(Dictionary parameters, CancellationToken cancellationToken) + { + var time = _clock.UtcNow(); + var stopwatch = Stopwatch.StartNew(); + int? statusCode = null; + string? responseText = null; + string? error = null; + + try + { + var content = new FormUrlEncodedContent(parameters); + var response = await _httpClient.PostAsync(_configuration.Url, content, cancellationToken); + statusCode = (int)response.StatusCode; + responseText = await response.Content.ReadAsStringAsync(cancellationToken); + + response.EnsureSuccessStatusCode(); + return responseText; + } + catch (Exception ex) + { + error = ex.Message; + throw; + } + finally + { + _trafficLog.Add( + _configuration.AcarsConnectionId, + new AcarsTrafficEntry( + time, + parameters["type"], + AcarsTrafficLog.FormatRequest(parameters), + statusCode, + responseText, + stopwatch.Elapsed, + error)); + } + } + + public async Task ListConnections(CancellationToken cancellationToken) + { + if (_disposed) + throw new ObjectDisposedException(nameof(HoppieAcarsConnection)); + + var parameters = new Dictionary + { + ["logon"] = _configuration.AuthenticationCode, + ["from"] = _configuration.StationIdentifier, + ["to"] = "SERVER", + ["type"] = "ping", + ["packet"] = "ALL-CALLSIGNS" + }; + + try + { + _logger.Verbose("Listing connections"); + var responseText = await Post(parameters, cancellationToken); + _logger.Verbose("ListConnections response: {Response}", responseText); + + // Parse the response to extract callsigns + if (string.IsNullOrWhiteSpace(responseText)) + return Array.Empty(); + + // Strip "ok" prefix if present + if (responseText.StartsWith("ok", StringComparison.OrdinalIgnoreCase)) + { + responseText = responseText[2..].TrimStart(); + } + + if (string.IsNullOrWhiteSpace(responseText)) + return Array.Empty(); + + // Strip curly braces if present + if (responseText.StartsWith('{') && responseText.EndsWith('}')) + { + responseText = responseText[1..^1].Trim(); + } + + if (string.IsNullOrWhiteSpace(responseText)) + return Array.Empty(); + + // The response contains space-separated callsigns + var callsigns = responseText + .Split(' ', StringSplitOptions.RemoveEmptyEntries) + .Where(s => !string.IsNullOrWhiteSpace(s)) + .ToArray(); + + _logger.Information("Found {Count} active connections", callsigns.Length); + return callsigns; + } + catch (HttpRequestException ex) + { + _logger.Error(ex, "Failed to list connections"); + throw; + } + catch (TaskCanceledException ex) when (ex.CancellationToken != cancellationToken) + { + _logger.Warning("ListConnections request timed out"); + return Array.Empty(); + } + } + + public async Task Disconnect(CancellationToken cancellationToken) + { + if (_disposed) + throw new ObjectDisposedException(nameof(HoppieAcarsConnection)); + + if (_pollCancellationTokenSource is not null) + await _pollCancellationTokenSource.CancelAsync(); + + if (_pollTask is not null) + await _pollTask; + + _logger.Information("Disconnected from Hoppies ACARS network"); + } + + async Task Poll(CancellationToken cancellationToken) + { + try + { + while (!cancellationToken.IsCancellationRequested) + { + try + { + _logger.Verbose("Polling for messages"); + + var parameters = new Dictionary + { + ["logon"] = _configuration.AuthenticationCode, + ["from"] = _configuration.StationIdentifier, + ["to"] = "SERVER", + ["type"] = "poll" + }; + + var responseText = await Post(parameters, cancellationToken); + + _logger.Verbose("Poll response: {Response}", responseText); + + if (!string.IsNullOrWhiteSpace(responseText) && responseText != "ok") + { + await ParseAndPublishDownlinkMessages(responseText, cancellationToken); + } + } + catch (HttpRequestException ex) + { + _logger.Error(ex, "Poll request failed"); + } + catch (TaskCanceledException ex) when (ex.CancellationToken != cancellationToken) + { + _logger.Warning("Poll request timed out, skipping this attempt"); + } + catch (Exception ex) + { + _logger.Error(ex, "Unhandled exception when polling messages"); + } + + var pollInterval = GetPollInterval(); + _logger.Verbose("Poll completed, waiting {PollInterval}", pollInterval); + await Task.Delay(pollInterval, cancellationToken); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + _logger.Information("Stopping poll task"); + } + catch (Exception ex) + { + _logger.Fatal(ex, "Unhandled exception when polling messages"); + } + } + + async Task ParseAndPublishDownlinkMessages(string responseText, CancellationToken cancellationToken) + { + try + { + if (responseText.StartsWith("ok", StringComparison.OrdinalIgnoreCase)) + { + responseText = responseText[2..].TrimStart(); + } + + if (string.IsNullOrWhiteSpace(responseText)) + return; + + if (responseText.StartsWith("error", StringComparison.OrdinalIgnoreCase)) + { + _logger.Warning("Hoppie server error: {Error}", responseText); + return; + } + + var messages = ExtractMessages(responseText); + + _logger.Verbose("Extracted {Count} messages", messages.Count); + + foreach (var messageText in messages) + { + _logger.Verbose("Extracted: {Message}", messageText); + var (from, type, packet) = ParseMessage(messageText); + + switch (type.ToLowerInvariant()) + { + case "cpdlc": + var downlink = ParseCpdlcDownlink(from, packet); + _logger.Information("Received {MessageType} from {From}", type, from); + _messageChannel.Writer.TryWrite(downlink); + break; + + case "ads-c": + // Log the packet before it is parsed, so that packets that cannot be parsed are also in the log + await LogAdscPacket(from, AdscMessageDirection.Downlink, packet, cancellationToken); + + var adscMessage = ParseAdscDownlink(from, packet); + if (adscMessage is null) + break; + + _logger.Information("Received {MessageType} from {From}", type, from); + _adscMessageChannel.Writer.TryWrite(adscMessage); + break; + + default: + _logger.Information("Unsupported message type: {Type}", type); + break; + } + } + } + catch (Exception ex) + { + throw new MessageParseException("Failed to parse downlink messages", ex); + } + } + + static List ExtractMessages(string responseText) + { + var messages = new List(); + var depth = 0; + var currentMessage = new System.Text.StringBuilder(); + + for (var i = 0; i < responseText.Length; i++) + { + var c = responseText[i]; + + if (c == '{') + { + depth++; + if (depth == 1) + continue; + } + else if (c == '}') + { + depth--; + if (depth == 0) + { + messages.Add(currentMessage.ToString()); + currentMessage.Clear(); + continue; + } + } + + if (depth > 0) + { + currentMessage.Append(c); + } + } + + return messages; + } + + static (string from, string type, string packet) ParseMessage(string messageText) + { + var firstBraceIndex = messageText.IndexOf('{'); + if (firstBraceIndex == -1) + { + var parts = messageText.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length < 2) + throw new Exception($"Invalid message format: {messageText}"); + + return (parts[0], parts[1], parts.Length > 2 ? string.Join(" ", parts[2..]) : string.Empty); + } + + var headerParts = messageText[..firstBraceIndex].Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (headerParts.Length < 2) + throw new Exception($"Invalid message format: {messageText}"); + + var packet = messageText[(firstBraceIndex + 1)..]; + if (packet.EndsWith('}')) + packet = packet[..^1]; + + return (headerParts[0], headerParts[1], packet); + } + + ReceivedDownlink ParseCpdlcDownlink(string from, string packet) + { + if (packet.StartsWith("/DATA1/", StringComparison.OrdinalIgnoreCase)) + return ParseData1Downlink(from, packet); + + var parts = packet.Split('/', 6); + if (parts.Length != 6) + throw new MessageParseException($"Invalid CPDLC packet: Expected 6 components, got {parts.Length}: \"{packet}\""); + + var messageId = !string.IsNullOrEmpty(parts[2]) ? int.Parse(parts[2]) : -1; + int? replyToId = !string.IsNullOrEmpty(parts[3]) ? int.Parse(parts[3]) : null; + var responseType = parts[4] switch + { + "N" => CpdlcDownlinkResponseType.NoResponse, + "Y" => CpdlcDownlinkResponseType.ResponseRequired, + _ => throw new NotSupportedException($"Unsupported CPDLC downlink response type: {parts[4]}") + }; + + var content = parts[5]; + + return new ReceivedDownlink( + messageId, + replyToId, + from, + responseType, + AlertType.None, + content, + _clock.UtcNow()); + } + + // Some aircraft (for example, PMDG) send position reports in this format: + // /DATA1/*/*/*/*/FL380/*/0.84/ + // + // OVER MEPAB AT 0501Z, FL380, + // ESTIMATING ISTEM AT 0533Z, + // ... + // The first line is a header. The lines after the header contain the text of the report. + ReceivedDownlink ParseData1Downlink(string from, string packet) + { + var lines = packet.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + var content = lines.Length > 1 + ? string.Join(" ", lines[1..]) + : packet; + + return new ReceivedDownlink( + -1, + null, + from, + CpdlcDownlinkResponseType.NoResponse, + AlertType.None, + content, + _clock.UtcNow()); + } + + // Packet formats: + // REPORT [] + // REJECT + ReceivedAdscMessage? ParseAdscDownlink(string from, string packet) + { + var parts = packet.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length == 0) + throw new MessageParseException("Invalid ADS-C packet: Packet is empty"); + + switch (parts[0]) + { + case "REJECT": + return new ReceivedAdscRejection(from, _clock.UtcNow()); + + case "REPORT": + if (parts.Length < 6) + throw new MessageParseException($"Invalid ADS-C report: Expected 6 or more components, got {parts.Length}: \"{packet}\""); + + if (!TryParseCoordinate(parts[3], 'N', 'S', 90, out var latitude) || + !TryParseCoordinate(parts[4], 'E', 'W', 180, out var longitude)) + { + _logger.Warning("Ignoring ADS-C report from {From}: Cannot read the position: \"{Packet}\"", from, packet); + return null; + } + + // Aircraft do not agree on the format of the optional groups, so ignore them + var report = new AdscReport( + ParseAdscTimestamp(parts[2]), + latitude, + longitude, + ParseAdscAltitude(parts[5]), + AdscReportSource.Hoppie); + + return new ReceivedAdscReport(from, report, _clock.UtcNow()); + + default: + throw new MessageParseException($"Unsupported ADS-C packet: \"{packet}\""); + } + } + + // Aircraft send coordinates in different formats. + // For example, a latitude can be "-33.9461", "S33.9461", or "33.9461S". + static bool TryParseCoordinate(string text, char positiveHemisphere, char negativeHemisphere, double maximum, out double coordinate) + { + coordinate = 0; + + var number = text.ToUpperInvariant(); + var sign = 1; + if (number.Length > 1 && (number[0] == positiveHemisphere || number[0] == negativeHemisphere)) + { + sign = number[0] == negativeHemisphere ? -1 : 1; + number = number[1..]; + } + else if (number.Length > 1 && (number[^1] == positiveHemisphere || number[^1] == negativeHemisphere)) + { + sign = number[^1] == negativeHemisphere ? -1 : 1; + number = number[..^1]; + } + + if (!double.TryParse(number, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var value)) + return false; + + coordinate = sign * value; + return Math.Abs(coordinate) <= maximum; + } + + // Some aircraft send the altitude in feet, and some send it in hundreds of feet. + // Below 10,000, the altitude is in hundreds of feet. + static int ParseAdscAltitude(string text) + { + var altitude = int.Parse(text, CultureInfo.InvariantCulture); + return altitude < 10_000 ? altitude * 100 : altitude; + } + + // The report time has the day of the month, the hour, and the minute (ddHHmm) in UTC. + // Use the current month, or the previous month if the day is in the future. + DateTimeOffset ParseAdscTimestamp(string text) + { + if (text.Length != 6) + throw new MessageParseException($"Invalid ADS-C report time: \"{text}\""); + + var day = int.Parse(text[..2], CultureInfo.InvariantCulture); + var hour = int.Parse(text[2..4], CultureInfo.InvariantCulture); + var minute = int.Parse(text[4..], CultureInfo.InvariantCulture); + + var now = _clock.UtcNow(); + var month = new DateTimeOffset(now.Year, now.Month, 1, 0, 0, 0, TimeSpan.Zero); + if (day > now.Day) + month = month.AddMonths(-1); + + return month.AddDays(day - 1).AddHours(hour).AddMinutes(minute); + } + + TimeSpan GetPollInterval() + { + if (_lastSendTime.HasValue) + { + var timeSinceLastSend = _clock.UtcNow() - _lastSendTime.Value; + if (timeSinceLastSend < TimeSpan.FromMinutes(1)) + { + return TimeSpan.FromSeconds(20); + } + } + + return TimeSpan.FromSeconds(_random.Next(45, 76)); + } + + string SerializeCpdlcMessage(UplinkMessage uplinkMessage) + { + var responseType = uplinkMessage.ResponseType switch + { + CpdlcUplinkResponseType.NoResponse => "NE", + CpdlcUplinkResponseType.WilcoUnable => "WU", + CpdlcUplinkResponseType.AffirmativeNegative => "AN", + CpdlcUplinkResponseType.Roger => "R", + _ => throw new ArgumentException($"Unexpected CpdlcResponseType: {uplinkMessage.ResponseType}") + }; + + var replyToId = uplinkMessage.MessageReference is not null + ? uplinkMessage.MessageReference.ToString() + : string.Empty; + + var content = GetTranslatedContent(uplinkMessage); + + return $"/data2/{uplinkMessage.MessageId}/{replyToId}/{responseType}/{content}"; + } + + string GetTranslatedContent(UplinkMessage uplinkMessage) + { + var translatedContent = uplinkMessage.Content; + foreach (var uplinkMessageTranslation in _uplinkMessageTranslations) + { + translatedContent = translatedContent.Replace(uplinkMessageTranslation.Key, uplinkMessageTranslation.Value); + } + + return translatedContent; + } + + public async ValueTask DisposeAsync() + { + if (_disposed) + return; + + await Disconnect(CancellationToken.None); + + if (_pollTask is not null) + _pollTask.Dispose(); + + if (_pollCancellationTokenSource is not null) + _pollCancellationTokenSource.Dispose(); + + _httpClient.Dispose(); + + _disposed = true; + } +} diff --git a/source/CPDLCServer/Exceptions/MessageParseException.cs b/source/CPDLCServer/AcarsConnections/Hoppie/MessageParseException.cs similarity index 72% rename from source/CPDLCServer/Exceptions/MessageParseException.cs rename to source/CPDLCServer/AcarsConnections/Hoppie/MessageParseException.cs index c4f9953..a164c2a 100644 --- a/source/CPDLCServer/Exceptions/MessageParseException.cs +++ b/source/CPDLCServer/AcarsConnections/Hoppie/MessageParseException.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Exceptions; +namespace CPDLCServer.AcarsConnections.Hoppie; public class MessageParseException(string message, Exception? innerException = null) : Exception(message, innerException); \ No newline at end of file diff --git a/source/CPDLCServer/Clients/HoppiesConfiguration.cs b/source/CPDLCServer/AcarsConnections/HoppiesConfiguration.cs similarity index 57% rename from source/CPDLCServer/Clients/HoppiesConfiguration.cs rename to source/CPDLCServer/AcarsConnections/HoppiesConfiguration.cs index 1acccdc..e3c4d18 100644 --- a/source/CPDLCServer/Clients/HoppiesConfiguration.cs +++ b/source/CPDLCServer/AcarsConnections/HoppiesConfiguration.cs @@ -1,26 +1,28 @@ using System.Text.Json.Serialization; -namespace CPDLCServer.Clients; +namespace CPDLCServer.AcarsConnections; [JsonPolymorphic(TypeDiscriminatorPropertyName = "Type")] [JsonDerivedType(typeof(HoppiesConfiguration), "Hoppie")] public abstract class AcarsConfiguration { - public abstract string ClientId { get; } + public abstract string AcarsConnectionId { get; } // The reporting interval in minutes for the ADS-C contract that is requested when an aircraft logs on with CPDLC public int DefaultAdscReportingInterval { get; init; } = 10; - // The time in minutes from the request of a selected ADS-C contract to its end. After this time, the default contract is requested again. - public int SelectedAdscContractDuration { get; init; } = 60; + // A CPDLC free text message that is sent to each aircraft after it logs on. Null when there is no message. + public string? Motd { get; init; } + + // The time from the logon to the message of the day + public TimeSpan MotdDelay { get; init; } = TimeSpan.FromSeconds(30); } public class HoppiesConfiguration : AcarsConfiguration { - public override string ClientId => $"Hoppies/{StationIdentifier}"; + public override string AcarsConnectionId => $"Hoppies/{StationIdentifier}"; public required Uri Url { get; init; } public required string AuthenticationCode { get; init; } - public required string FlightSimulationNetwork { get; init; } public required string StationIdentifier { get; init; } } diff --git a/source/CPDLCServer/AcarsConnections/IAcarsConnection.cs b/source/CPDLCServer/AcarsConnections/IAcarsConnection.cs new file mode 100644 index 0000000..8b88a76 --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/IAcarsConnection.cs @@ -0,0 +1,64 @@ +using System.Threading.Channels; +using CPDLCServer.Contracts; +using CPDLCServer.AdscContracts; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; + +namespace CPDLCServer.AcarsConnections; + +/// +/// Manages the connection to the upstream ACARS network. +/// +public interface IAcarsConnection : IAsyncDisposable +{ + /// + /// The identifier of the station on the ACARS network. + /// + string StationId { get; } // TODO: Can we get rid of this, or consider it internal to the connection? + + /// + /// A where CPDLC downlink messages can be read. + /// + ChannelReader MessageReader { get; } + + /// + /// A where ADS-C messages can be read. + /// + ChannelReader AdscMessageReader { get; } + + /// + /// Initiates the connection to the ACARS network, and starts reading messages. + /// Use and to read the received messages. + /// + Task Connect(CancellationToken cancellationToken); + + /// + /// Transmits a CPDLC uplink message. + /// + Task Send(UplinkMessage message, CancellationToken cancellationToken); + + /// + /// Transmits a request for a periodic ADS contract. + /// + Task RequestPeriodicAdscContract(string callsign, TimeSpan reportingInterval, CancellationToken cancellationToken); + + /// + /// Transmits a request for an on-demand ADS report. + /// + Task RequestAdscDemandReport(string callsign, CancellationToken cancellationToken); + + /// + /// Notifies the termination of an ADS contract. + /// + Task CancelAdscContract(string callsign, CancellationToken cancellationToken); + + /// + /// Lists all clients connected to the ACARS network. + /// + Task ListConnections(CancellationToken cancellationToken); + + /// + /// Terminates the connection to the ACARS network, and stops receiving messages. + /// + Task Disconnect(CancellationToken cancellationToken); +} diff --git a/source/CPDLCServer/Services/AcarsConnectivityCheckService.cs b/source/CPDLCServer/AcarsConnections/Stations/AcarsConnectivityCheckService.cs similarity index 60% rename from source/CPDLCServer/Services/AcarsConnectivityCheckService.cs rename to source/CPDLCServer/AcarsConnections/Stations/AcarsConnectivityCheckService.cs index bc4ecb5..3b9d976 100644 --- a/source/CPDLCServer/Services/AcarsConnectivityCheckService.cs +++ b/source/CPDLCServer/AcarsConnections/Stations/AcarsConnectivityCheckService.cs @@ -1,53 +1,34 @@ -using CPDLCServer.Clients; -using CPDLCServer.Exceptions; -using CPDLCServer.Messages; -using MediatR; +using CPDLCServer.Infrastructure; +using CPDLCServer.Settings; -namespace CPDLCServer.Services; +namespace CPDLCServer.AcarsConnections.Stations; public class AcarsConnectivityCheckService : IHostedService, IDisposable { - readonly TimeSpan _checkInterval; #if DEBUG readonly TimeSpan _errorInterval = TimeSpan.FromSeconds(5); #else readonly TimeSpan _errorInterval = TimeSpan.FromMinutes(5); #endif - readonly AcarsConfiguration[] _acarsConfigurations; - readonly IMediator _mediator; + readonly IAcarsConnectionManager _acarsConnectionManager; + readonly IUnitOfWorkMediator _mediator; + readonly IServiceScopeFactory _serviceScopeFactory; readonly ILogger _logger; CancellationTokenSource? _cancellationTokenSource; Task? _task; - public AcarsConnectivityCheckService(IConfiguration configuration, IMediator mediator, ILogger logger) + public AcarsConnectivityCheckService( + IAcarsConnectionManager acarsConnectionManager, + IUnitOfWorkMediator mediator, + IServiceScopeFactory serviceScopeFactory, + ILogger logger) { + _acarsConnectionManager = acarsConnectionManager; _mediator = mediator; + _serviceScopeFactory = serviceScopeFactory; _logger = logger.ForContext(); - - var checkIntervalMinutes = configuration.GetValue("ConnectivityCheckIntervalMinutes", 15); - _checkInterval = TimeSpan.FromMinutes(checkIntervalMinutes); - - var acarsConfigurationSection = configuration.GetSection("Acars"); - var configurationList = new List(); - - foreach (var section in acarsConfigurationSection.GetChildren()) - { - var type = section["Type"]; - var config = type switch - { - "Hoppie" => section.Get(), - _ => throw new NotSupportedException($"ACARS configuration type '{type}' is not supported") - }; - - if (config is not null) - { - configurationList.Add(config); - } - } - - _acarsConfigurations = configurationList.ToArray(); } public Task StartAsync(CancellationToken cancellationToken) @@ -85,17 +66,28 @@ async Task DoWork(CancellationToken stoppingToken) { _logger.Debug("Checking aircraft connectivity"); - foreach (var acarsConfiguration in _acarsConfigurations) + // The connections can start and stop while the server is running, so get them each time + var acarsConnectionIds = _acarsConnectionManager.GetAcarsConnectionIds(); + if (acarsConnectionIds.Length == 0) + { + _logger.Debug("No ACARS connections are running, retrying"); + await Task.Delay(_errorInterval, stoppingToken); + continue; + } + + foreach (var acarsConnectionId in acarsConnectionIds) { using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); timeoutCts.CancelAfter(TimeSpan.FromMinutes(1)); await _mediator.Send( - new RefreshAcarsCallsignsRequest(acarsConfiguration.ClientId), + new RefreshAcarsCallsignsRequest(acarsConnectionId), timeoutCts.Token); } - await Task.Delay(_checkInterval, stoppingToken); + var settings = await LoadSettings(stoppingToken); + var checkInterval = TimeSpan.FromMinutes(settings.ConnectivityCheckIntervalMinutes); + await Task.Delay(checkInterval, stoppingToken); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { @@ -103,7 +95,7 @@ await _mediator.Send( } catch (ConfigurationNotFoundException) { - _logger.Debug("ACARS client not yet available, retrying"); + _logger.Debug("ACARS connection not yet available, retrying"); await Task.Delay(_errorInterval, stoppingToken); } catch (Exception ex) @@ -125,6 +117,14 @@ await _mediator.Send( _logger.Information("Stopped aircraft connectivity check service"); } + // The settings provider is scoped, and this service is a singleton + async Task LoadSettings(CancellationToken cancellationToken) + { + await using var scope = _serviceScopeFactory.CreateAsyncScope(); + var settingsProvider = scope.ServiceProvider.GetRequiredService(); + return await settingsProvider.Load(cancellationToken); + } + public void Dispose() { _cancellationTokenSource?.Dispose(); diff --git a/source/CPDLCServer/Messages/AcarsStationsChangedNotification.cs b/source/CPDLCServer/AcarsConnections/Stations/AcarsStationsChangedNotification.cs similarity index 67% rename from source/CPDLCServer/Messages/AcarsStationsChangedNotification.cs rename to source/CPDLCServer/AcarsConnections/Stations/AcarsStationsChangedNotification.cs index 0b063a6..12d6645 100644 --- a/source/CPDLCServer/Messages/AcarsStationsChangedNotification.cs +++ b/source/CPDLCServer/AcarsConnections/Stations/AcarsStationsChangedNotification.cs @@ -1,5 +1,5 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AcarsConnections.Stations; public record AcarsStationsChangedNotification(string[] Callsigns) : INotification; diff --git a/source/CPDLCServer/Handlers/AcarsStationsChangedNotificationHandler.cs b/source/CPDLCServer/AcarsConnections/Stations/AcarsStationsChangedNotificationHandler.cs similarity index 55% rename from source/CPDLCServer/Handlers/AcarsStationsChangedNotificationHandler.cs rename to source/CPDLCServer/AcarsConnections/Stations/AcarsStationsChangedNotificationHandler.cs index 3298576..3199914 100644 --- a/source/CPDLCServer/Handlers/AcarsStationsChangedNotificationHandler.cs +++ b/source/CPDLCServer/AcarsConnections/Stations/AcarsStationsChangedNotificationHandler.cs @@ -1,22 +1,25 @@ -using CPDLCServer.Hubs; -using CPDLCServer.Messages; +using CPDLCServer.Persistence; +using CPDLCServer.Web; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AcarsConnections.Stations; public class AcarsStationsChangedNotificationHandler( IHubContext hubContext, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { - public async Task Handle(AcarsStationsChangedNotification notification, CancellationToken cancellationToken) + public Task Handle(AcarsStationsChangedNotification notification, CancellationToken cancellationToken) { logger.Information("Broadcasting ACARS connected callsigns update ({Count} callsigns)", notification.Callsigns.Length); - await hubContext.Clients.All.SendAsync( + unitOfWork.AfterCommit(ct => hubContext.Clients.All.SendAsync( "AcarsStationsUpdated", notification.Callsigns, - cancellationToken); + ct)); + + return Task.CompletedTask; } } diff --git a/source/CPDLCServer/Persistence/IAcarsStationRepository.cs b/source/CPDLCServer/AcarsConnections/Stations/IAcarsStationRepository.cs similarity index 79% rename from source/CPDLCServer/Persistence/IAcarsStationRepository.cs rename to source/CPDLCServer/AcarsConnections/Stations/IAcarsStationRepository.cs index 7c3e5f1..268ef0a 100644 --- a/source/CPDLCServer/Persistence/IAcarsStationRepository.cs +++ b/source/CPDLCServer/AcarsConnections/Stations/IAcarsStationRepository.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Persistence; +namespace CPDLCServer.AcarsConnections.Stations; public interface IAcarsStationRepository { diff --git a/source/CPDLCServer/Persistence/InMemoryAcarsStationRepository.cs b/source/CPDLCServer/AcarsConnections/Stations/InMemoryAcarsStationRepository.cs similarity index 92% rename from source/CPDLCServer/Persistence/InMemoryAcarsStationRepository.cs rename to source/CPDLCServer/AcarsConnections/Stations/InMemoryAcarsStationRepository.cs index 5d05695..3a4b1a9 100644 --- a/source/CPDLCServer/Persistence/InMemoryAcarsStationRepository.cs +++ b/source/CPDLCServer/AcarsConnections/Stations/InMemoryAcarsStationRepository.cs @@ -1,6 +1,6 @@ -using CPDLCServer.Extensions; +using CPDLCServer.Infrastructure; -namespace CPDLCServer.Persistence; +namespace CPDLCServer.AcarsConnections.Stations; public class InMemoryAcarsStationRepository : IAcarsStationRepository { diff --git a/source/CPDLCServer/AcarsConnections/Stations/RefreshAcarsCallsignsRequest.cs b/source/CPDLCServer/AcarsConnections/Stations/RefreshAcarsCallsignsRequest.cs new file mode 100644 index 0000000..50c088c --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/Stations/RefreshAcarsCallsignsRequest.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.AcarsConnections.Stations; + +public record RefreshAcarsCallsignsRequest(string AcarsConnectionId) : IRequest; diff --git a/source/CPDLCServer/Handlers/RefreshAcarsCallsignsRequestHandler.cs b/source/CPDLCServer/AcarsConnections/Stations/RefreshAcarsCallsignsRequestHandler.cs similarity index 76% rename from source/CPDLCServer/Handlers/RefreshAcarsCallsignsRequestHandler.cs rename to source/CPDLCServer/AcarsConnections/Stations/RefreshAcarsCallsignsRequestHandler.cs index 0738375..74308c9 100644 --- a/source/CPDLCServer/Handlers/RefreshAcarsCallsignsRequestHandler.cs +++ b/source/CPDLCServer/AcarsConnections/Stations/RefreshAcarsCallsignsRequestHandler.cs @@ -1,13 +1,11 @@ -using CPDLCServer.Clients; +using CPDLCServer.Cpdlc.Connections; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AcarsConnections.Stations; public class RefreshAcarsCallsignsRequestHandler( - IClientManager clientManager, + IAcarsConnectionManager acarsConnectionManager, IAircraftRepository aircraftRepository, IAcarsStationRepository acarsConnectedCallsignsRepository, IMediator mediator, @@ -16,8 +14,8 @@ public class RefreshAcarsCallsignsRequestHandler( { public async Task Handle(RefreshAcarsCallsignsRequest request, CancellationToken cancellationToken) { - var client = await clientManager.GetAcarsClient(request.AcarsClientId, cancellationToken); - var activeConnections = await client.ListConnections(cancellationToken); + var acarsConnection = await acarsConnectionManager.GetAcarsConnection(request.AcarsConnectionId, cancellationToken); + var activeConnections = await acarsConnection.ListConnections(cancellationToken); // Update the repository and broadcast if changed var changed = await acarsConnectedCallsignsRepository.Update(activeConnections, cancellationToken); @@ -32,7 +30,7 @@ await mediator.Publish( // Update last seen for tracked connections var trackedConnections = await aircraftRepository.All(cancellationToken); var matchingConnections = trackedConnections - .Where(c => c.AcarsClientId == request.AcarsClientId) + .Where(c => c.AcarsConnectionId == request.AcarsConnectionId) .Where(c => activeConnections.Contains(c.Callsign)); var now = clock.UtcNow(); diff --git a/source/CPDLCServer/AcarsConnections/Traffic/AcarsTrafficEntry.cs b/source/CPDLCServer/AcarsConnections/Traffic/AcarsTrafficEntry.cs new file mode 100644 index 0000000..982f64c --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/Traffic/AcarsTrafficEntry.cs @@ -0,0 +1,16 @@ +namespace CPDLCServer.AcarsConnections.Traffic; + +// One HTTP request to the ACARS network and its response, as they were sent and received. +// The authentication code is not in the request. +public record AcarsTrafficEntry( + DateTimeOffset Time, + string Type, + string Request, + int? StatusCode, + string? Response, + TimeSpan Duration, + string? Error) +{ + // Most polls get no messages. The traffic page can hide them. + public bool IsEmptyPoll => Type == "poll" && Error is null && Response?.Trim() == "ok"; +} diff --git a/source/CPDLCServer/AcarsConnections/Traffic/AcarsTrafficLog.cs b/source/CPDLCServer/AcarsConnections/Traffic/AcarsTrafficLog.cs new file mode 100644 index 0000000..4132887 --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/Traffic/AcarsTrafficLog.cs @@ -0,0 +1,53 @@ +namespace CPDLCServer.AcarsConnections.Traffic; + +/// +/// Keeps the most recent requests to the ACARS network and their responses for each ACARS connection, so that an +/// administrator can see the raw data. The entries are kept only in memory, so a restart clears them. +/// +public class AcarsTrafficLog(int capacity = 500) +{ + public const string RedactedValue = "***"; + + // The names of the request fields that contain a secret + static readonly string[] SecretFields = ["logon"]; + + public int Capacity { get; } = capacity; + + readonly Lock _lock = new(); + readonly Dictionary> _entries = new(); + + public void Add(string acarsConnectionId, AcarsTrafficEntry entry) + { + lock (_lock) + { + if (!_entries.TryGetValue(acarsConnectionId, out var entries)) + { + entries = new Queue(); + _entries[acarsConnectionId] = entries; + } + + entries.Enqueue(entry); + if (entries.Count > Capacity) + entries.Dequeue(); + } + } + + // Newest entries first + public AcarsTrafficEntry[] Get(string acarsConnectionId) + { + lock (_lock) + { + return _entries.TryGetValue(acarsConnectionId, out var entries) + ? entries.Reverse().ToArray() + : []; + } + } + + // The request fields as text, one field on each line. The secrets are replaced. + public static string FormatRequest(IReadOnlyDictionary fields) + { + return string.Join( + '\n', + fields.Select(field => $"{field.Key}={(SecretFields.Contains(field.Key) ? RedactedValue : field.Value)}")); + } +} diff --git a/source/CPDLCServer/Model/AdscContract.cs b/source/CPDLCServer/AdscContracts/AdscContract.cs similarity index 67% rename from source/CPDLCServer/Model/AdscContract.cs rename to source/CPDLCServer/AdscContracts/AdscContract.cs index 401193e..e11c0bb 100644 --- a/source/CPDLCServer/Model/AdscContract.cs +++ b/source/CPDLCServer/AdscContracts/AdscContract.cs @@ -1,23 +1,32 @@ -namespace CPDLCServer.Model; +using CPDLCServer.AdscContracts.Reports; + +namespace CPDLCServer.AdscContracts; /// /// The ADS-C requests that an ATSU sent to an aircraft. /// The aircraft has only one periodic contract. A new periodic request replaces the previous one. /// /// The default contract uses the default reporting interval of the ATSU. -/// A controller can select a different reporting interval. The selected contract ends at a fixed time, then the default contract is requested again. +/// A controller can select a different reporting interval. The selected contract stays until a controller requests the default contract. /// A demand request asks for one report. /// /// -public class AdscContract(string callsign, string stationId) +public class AdscContract(string callsign, string stationId, TimeSpan defaultReportingInterval, DateTimeOffset created) { - // The ACARS clients poll for messages every 20 to 75 seconds. A shorter interval gives no more data. + // The ACARS connections poll for messages every 20 to 75 seconds. A shorter interval gives no more data. public static readonly TimeSpan MinimumReportingInterval = TimeSpan.FromSeconds(60); + // The maximum delivery time of a report + static readonly TimeSpan ReportDeliveryTolerance = TimeSpan.FromMinutes(3); + public string Callsign { get; } = callsign; public string StationId { get; } = stationId; - // The interval of the latest periodic request. Null when no periodic contract was requested. + // The time that the ATSU made the contract + public DateTimeOffset Created { get; } = created; + + public TimeSpan DefaultReportingInterval { get; private set; } = defaultReportingInterval; + public TimeSpan? ReportingInterval { get; private set; } public AdscContractState? DefaultContractState { get; private set; } @@ -25,14 +34,15 @@ public class AdscContract(string callsign, string stationId) public TimeSpan? SelectedReportingInterval { get; private set; } public AdscContractState? SelectedContractState { get; private set; } - // Null when no selected contract is in use - public DateTimeOffset? SelectedContractEnds { get; private set; } - public AdscContractState? DemandContractState { get; private set; } // The latest time that a request was sent, or that a message was received from the aircraft public DateTimeOffset LastActivity { get; private set; } + public DateTimeOffset? LastReportReceived { get; private set; } + + public AdscReportSource? ReportingSource { get; private set; } + public bool HasPeriodicContract => DefaultContractState is AdscContractState.Sent or AdscContractState.Accepted || SelectedContractState is AdscContractState.Sent or AdscContractState.Accepted; @@ -42,6 +52,10 @@ DefaultContractState is AdscContractState.Sent or AdscContractState.Accepted || HasPeriodicContract || DemandContractState is AdscContractState.Sent or AdscContractState.Accepted; + // A report expires when the next two periodic reports do not arrive. + // A contract with only a demand request uses the default reporting interval. + public TimeSpan ReportExpiry => (ReportingInterval ?? DefaultReportingInterval) * 2 + ReportDeliveryTolerance; + public void LogActivity(DateTimeOffset now) { LastActivity = now; @@ -53,23 +67,23 @@ public void LogActivity(DateTimeOffset now) /// public void RequestDefaultContract(TimeSpan reportingInterval) { + // The default reporting interval of the ATSU can change while the server is running + DefaultReportingInterval = reportingInterval; ReportingInterval = reportingInterval; DefaultContractState = AdscContractState.Sent; - if (SelectedContractState is AdscContractState.Sent or AdscContractState.Accepted) - { - SelectedReportingInterval = null; - SelectedContractState = null; - SelectedContractEnds = null; - } + if (SelectedContractState is not (AdscContractState.Sent or AdscContractState.Accepted)) + return; + + SelectedReportingInterval = null; + SelectedContractState = null; } - public void RequestSelectedContract(TimeSpan reportingInterval, DateTimeOffset ends) + public void RequestSelectedContract(TimeSpan reportingInterval) { ReportingInterval = reportingInterval; SelectedReportingInterval = reportingInterval; SelectedContractState = AdscContractState.Sent; - SelectedContractEnds = ends; } public void RequestDemandReport() @@ -81,30 +95,35 @@ public void RequestDemandReport() /// The aircraft does not acknowledge a request, so a report accepts the latest periodic request and the demand request. /// When the selected contract is accepted, it replaces the default contract on the aircraft. /// - /// True if the state of a request changed. - public bool ReportReceived() + public void ReportReceived(AdscReport report) { - var changed = false; + ReportingSource = report.Source; + LastReportReceived = report.Timestamp; if (SelectedContractState == AdscContractState.Sent) { SelectedContractState = AdscContractState.Accepted; DefaultContractState = null; - changed = true; } else if (DefaultContractState == AdscContractState.Sent) { DefaultContractState = AdscContractState.Accepted; - changed = true; } if (DemandContractState == AdscContractState.Sent) { DemandContractState = AdscContractState.Accepted; - changed = true; } + } - return changed; + /// + /// The last report is too old to show the position of the aircraft. + /// The time of the last report stays, so that the next periodic report is due immediately. + /// The source is removed, so that reports from VATSIM can replace the reports from Hoppie. + /// + public void ReportTimedOut() + { + ReportingSource = null; } /// @@ -119,7 +138,6 @@ public bool Reject() if (SelectedContractState is AdscContractState.Sent or AdscContractState.Accepted) { SelectedContractState = AdscContractState.Rejected; - SelectedContractEnds = null; selectedContractRejected = true; } else if (DefaultContractState is AdscContractState.Sent or AdscContractState.Accepted) @@ -128,7 +146,9 @@ public bool Reject() } if (DemandContractState == AdscContractState.Sent) + { DemandContractState = AdscContractState.Rejected; + } return selectedContractRejected; } diff --git a/source/CPDLCServer/Messages/AdscContractChangedNotification.cs b/source/CPDLCServer/AdscContracts/AdscContractChangedNotification.cs similarity index 64% rename from source/CPDLCServer/Messages/AdscContractChangedNotification.cs rename to source/CPDLCServer/AdscContracts/AdscContractChangedNotification.cs index bd3abdf..3f7efbe 100644 --- a/source/CPDLCServer/Messages/AdscContractChangedNotification.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractChangedNotification.cs @@ -1,6 +1,5 @@ -using CPDLCServer.Model; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AdscContracts; public record AdscContractChangedNotification(AdscContract Contract) : INotification; diff --git a/source/CPDLCServer/Handlers/AdscContractChangedNotificationHandler.cs b/source/CPDLCServer/AdscContracts/AdscContractChangedNotificationHandler.cs similarity index 77% rename from source/CPDLCServer/Handlers/AdscContractChangedNotificationHandler.cs rename to source/CPDLCServer/AdscContracts/AdscContractChangedNotificationHandler.cs index 0691adc..e0a2ae4 100644 --- a/source/CPDLCServer/Handlers/AdscContractChangedNotificationHandler.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractChangedNotificationHandler.cs @@ -1,15 +1,15 @@ -using CPDLCServer.Hubs; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Controllers; using CPDLCServer.Persistence; +using CPDLCServer.Web; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts; public class AdscContractChangedNotificationHandler( IControllerRepository controllerRepository, IHubContext hubContext, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { @@ -26,9 +26,10 @@ public async Task Handle(AdscContractChangedNotification notification, Cancellat return; } - await hubContext.Clients + var contractDto = AdscContractConverter.ToDto(contract); + unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(controllers.Select(c => c.ConnectionId)) - .SendAsync("AdscContractUpdated", AdscContractConverter.ToDto(contract), cancellationToken); + .SendAsync("AdscContractUpdated", contractDto, ct)); logger.Information( "Notified {ControllerCount} controller(s) about ADS-C contract change for {Callsign}", diff --git a/source/CPDLCServer/AdscContracts/AdscContractConfiguration.cs b/source/CPDLCServer/AdscContracts/AdscContractConfiguration.cs new file mode 100644 index 0000000..0d9010e --- /dev/null +++ b/source/CPDLCServer/AdscContracts/AdscContractConfiguration.cs @@ -0,0 +1,35 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.AdscContracts; + +public class AdscContractConfiguration : IEntityTypeConfiguration +{ + public const string IdProperty = "Id"; + + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("AdscContracts"); + + // The domain model has no ID, so the key is a shadow property + builder.Property(IdProperty); + builder.HasKey(IdProperty); + + builder.Property(c => c.Callsign); + builder.Property(c => c.StationId); + builder.Property(c => c.Created); + builder.Property(c => c.DefaultReportingInterval); + builder.Property(c => c.ReportingInterval); + builder.Property(c => c.DefaultContractState); + builder.Property(c => c.SelectedReportingInterval); + builder.Property(c => c.SelectedContractState); + builder.Property(c => c.DemandContractState); + builder.Property(c => c.LastActivity); + builder.Property(c => c.LastReportReceived); + builder.Property(c => c.ReportingSource); + + // One contract for each aircraft and ATSU. + // Two units of work that add the same contract at the same time cannot both commit. + builder.HasIndex(c => new { c.Callsign, c.StationId }).IsUnique(); + } +} diff --git a/source/CPDLCServer/Model/AdscContractConverter.cs b/source/CPDLCServer/AdscContracts/AdscContractConverter.cs similarity index 80% rename from source/CPDLCServer/Model/AdscContractConverter.cs rename to source/CPDLCServer/AdscContracts/AdscContractConverter.cs index 95562a1..79a2af9 100644 --- a/source/CPDLCServer/Model/AdscContractConverter.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractConverter.cs @@ -1,6 +1,7 @@ +using CPDLCServer.AdscContracts.Reports; using CPDLCServer.Contracts; -namespace CPDLCServer.Model; +namespace CPDLCServer.AdscContracts; public static class AdscContractConverter { @@ -10,10 +11,10 @@ public static AdscContractDto ToDto(AdscContract contract) contract.Callsign, contract.StationId, contract.ReportingInterval, + contract.DefaultReportingInterval, ToDto(contract.DefaultContractState), contract.SelectedReportingInterval, ToDto(contract.SelectedContractState), - contract.SelectedContractEnds, ToDto(contract.DemandContractState)); } @@ -30,12 +31,12 @@ public static AdscReportDto ToDto(string callsign, string stationId, AdscReport ToDto(report.Source)); } - static Contracts.AdscReportSource ToDto(AdscReportSource source) + static Contracts.AdscReportSource ToDto(Reports.AdscReportSource source) { return source switch { - AdscReportSource.Hoppie => Contracts.AdscReportSource.Hoppie, - AdscReportSource.VATSIM => Contracts.AdscReportSource.VATSIM, + Reports.AdscReportSource.Hoppie => Contracts.AdscReportSource.Hoppie, + Reports.AdscReportSource.VATSIM => Contracts.AdscReportSource.VATSIM, _ => throw new ArgumentException($"Unknown ADS-C report source: {source}") }; } diff --git a/source/CPDLCServer/Services/AdscContractExpiryService.cs b/source/CPDLCServer/AdscContracts/AdscContractExpiryService.cs similarity index 74% rename from source/CPDLCServer/Services/AdscContractExpiryService.cs rename to source/CPDLCServer/AdscContracts/AdscContractExpiryService.cs index d03f0e9..d1b5f28 100644 --- a/source/CPDLCServer/Services/AdscContractExpiryService.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractExpiryService.cs @@ -1,27 +1,17 @@ -using CPDLCServer.Messages; -using MediatR; +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Infrastructure; -namespace CPDLCServer.Services; +namespace CPDLCServer.AdscContracts; -public class AdscContractExpiryService : IHostedService, IDisposable +public class AdscContractExpiryService(IUnitOfWorkMediator mediator, ILogger logger) : IHostedService, IDisposable { readonly TimeSpan _checkInterval = TimeSpan.FromMinutes(1); - readonly TimeSpan _contractTimeout; - readonly IMediator _mediator; - readonly ILogger _logger; + readonly ILogger _logger = logger.ForContext(); CancellationTokenSource? _cancellationTokenSource; Task? _task; - public AdscContractExpiryService(IConfiguration configuration, IMediator mediator, ILogger logger) - { - _mediator = mediator; - _logger = logger.ForContext(); - - _contractTimeout = configuration.GetValue("AdscContractTimeout", TimeSpan.FromMinutes(120)); - } - public Task StartAsync(CancellationToken cancellationToken) { if (_cancellationTokenSource is not null || _task is not null) @@ -55,12 +45,16 @@ async Task DoWork(CancellationToken stoppingToken) { try { - _logger.Debug("Checking for ended ADS-C contracts"); + _logger.Debug("Checking for ended ADS-C contracts and expired ADS-C data"); using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); timeoutCts.CancelAfter(TimeSpan.FromMinutes(1)); - await _mediator.Send(new EndExpiredAdscContractsRequest(_contractTimeout), timeoutCts.Token); + await mediator.Send(new EndExpiredAdscContractsRequest(), timeoutCts.Token); + + // After the contracts, so that the reports of removed contracts expire immediately + await mediator.Send(new ExpireAdscReportsRequest(), timeoutCts.Token); + await mediator.Send(new PurgeExpiredAdscDataRequest(), timeoutCts.Token); await Task.Delay(_checkInterval, stoppingToken); } @@ -70,7 +64,7 @@ async Task DoWork(CancellationToken stoppingToken) } catch (Exception ex) { - _logger.Error(ex, "Error checking for ended ADS-C contracts"); + _logger.Error(ex, "Error checking for ended ADS-C contracts and expired ADS-C data"); await Task.Delay(_checkInterval, stoppingToken); } } diff --git a/source/CPDLCServer/Messages/AdscContractRemovedNotification.cs b/source/CPDLCServer/AdscContracts/AdscContractRemovedNotification.cs similarity index 75% rename from source/CPDLCServer/Messages/AdscContractRemovedNotification.cs rename to source/CPDLCServer/AdscContracts/AdscContractRemovedNotification.cs index 5332347..5625da2 100644 --- a/source/CPDLCServer/Messages/AdscContractRemovedNotification.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractRemovedNotification.cs @@ -1,5 +1,5 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AdscContracts; public record AdscContractRemovedNotification(string Callsign, string StationId) : INotification; diff --git a/source/CPDLCServer/Handlers/AdscContractRemovedNotificationHandler.cs b/source/CPDLCServer/AdscContracts/AdscContractRemovedNotificationHandler.cs similarity index 83% rename from source/CPDLCServer/Handlers/AdscContractRemovedNotificationHandler.cs rename to source/CPDLCServer/AdscContracts/AdscContractRemovedNotificationHandler.cs index e03a5f9..57d63a2 100644 --- a/source/CPDLCServer/Handlers/AdscContractRemovedNotificationHandler.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractRemovedNotificationHandler.cs @@ -1,14 +1,15 @@ -using CPDLCServer.Hubs; -using CPDLCServer.Messages; +using CPDLCServer.Controllers; using CPDLCServer.Persistence; +using CPDLCServer.Web; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts; public class AdscContractRemovedNotificationHandler( IControllerRepository controllerRepository, IHubContext hubContext, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { @@ -23,9 +24,9 @@ public async Task Handle(AdscContractRemovedNotification notification, Cancellat return; } - await hubContext.Clients + unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(controllers.Select(c => c.ConnectionId)) - .SendAsync("AdscContractRemoved", notification.Callsign, notification.StationId, cancellationToken); + .SendAsync("AdscContractRemoved", notification.Callsign, notification.StationId, ct)); logger.Information( "Notified {ControllerCount} controller(s) about removed ADS-C contract for {Callsign}", diff --git a/source/CPDLCServer/AdscContracts/AdscContractRepository.cs b/source/CPDLCServer/AdscContracts/AdscContractRepository.cs new file mode 100644 index 0000000..2c5c082 --- /dev/null +++ b/source/CPDLCServer/AdscContracts/AdscContractRepository.cs @@ -0,0 +1,46 @@ +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.AdscContracts; + +// The changes are saved when the unit of work is committed. +// Queries load the rows into the context, then read the local entities, so that the results include entities that are +// added in the unit of work and exclude entities that are removed in it. +public class AdscContractRepository(CpdlcDbContext dbContext) : IAdscContractRepository +{ + public async Task Add(AdscContractKey contractKey, AdscContract contract, CancellationToken cancellationToken) + { + // A new contract replaces the contract with the same key + var existing = await Find(contractKey, cancellationToken); + if (existing is not null) + dbContext.AdscContracts.Remove(existing); + + dbContext.AdscContracts.Add(contract); + } + + public async Task Find(AdscContractKey contractKey, CancellationToken cancellationToken) + { + await dbContext.AdscContracts + .Where(c => c.Callsign == contractKey.Callsign && c.StationId == contractKey.StationId) + .LoadAsync(cancellationToken); + + return dbContext.AdscContracts.Local + .FirstOrDefault(c => c.Callsign == contractKey.Callsign && c.StationId == contractKey.StationId); + } + + public async Task All(CancellationToken cancellationToken) + { + await dbContext.AdscContracts.LoadAsync(cancellationToken); + return dbContext.AdscContracts.Local.ToArray(); + } + + public async Task Remove(AdscContractKey contractKey, CancellationToken cancellationToken) + { + var contract = await Find(contractKey, cancellationToken); + if (contract is null) + return false; + + dbContext.AdscContracts.Remove(contract); + return true; + } +} diff --git a/source/CPDLCServer/Model/AdscContractState.cs b/source/CPDLCServer/AdscContracts/AdscContractState.cs similarity index 81% rename from source/CPDLCServer/Model/AdscContractState.cs rename to source/CPDLCServer/AdscContracts/AdscContractState.cs index 38abd2c..58fc6d1 100644 --- a/source/CPDLCServer/Model/AdscContractState.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractState.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.AdscContracts; // The aircraft does not acknowledge a request. The first report after the request accepts it. public enum AdscContractState diff --git a/source/CPDLCServer/AdscContracts/AdscContractsServiceCollectionExtensions.cs b/source/CPDLCServer/AdscContracts/AdscContractsServiceCollectionExtensions.cs new file mode 100644 index 0000000..28af032 --- /dev/null +++ b/source/CPDLCServer/AdscContracts/AdscContractsServiceCollectionExtensions.cs @@ -0,0 +1,18 @@ +using CPDLCServer.AdscContracts.MessageLog; +using CPDLCServer.AdscContracts.Reports; + +namespace CPDLCServer.AdscContracts; + +public static class AdscContractsServiceCollectionExtensions +{ + public static IServiceCollection AddAdsContracts(this IServiceCollection services) + { + services.AddScoped(); + services.AddHostedService(); + + services.AddScoped(); + services.AddSingleton(); + + return services; + } +} diff --git a/source/CPDLCServer/Messages/AdscMessageReceivedNotification.cs b/source/CPDLCServer/AdscContracts/AdscMessageReceivedNotification.cs similarity index 62% rename from source/CPDLCServer/Messages/AdscMessageReceivedNotification.cs rename to source/CPDLCServer/AdscContracts/AdscMessageReceivedNotification.cs index 42243cd..3311b12 100644 --- a/source/CPDLCServer/Messages/AdscMessageReceivedNotification.cs +++ b/source/CPDLCServer/AdscContracts/AdscMessageReceivedNotification.cs @@ -1,10 +1,9 @@ -using CPDLCServer.Model; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AdscContracts; public record AdscMessageReceivedNotification( - string AcarsClientId, + string AcarsConnectionId, string StationId, ReceivedAdscMessage Message) : INotification; diff --git a/source/CPDLCServer/Handlers/AdscMessageReceivedNotificationHandler.cs b/source/CPDLCServer/AdscContracts/AdscMessageReceivedNotificationHandler.cs similarity index 77% rename from source/CPDLCServer/Handlers/AdscMessageReceivedNotificationHandler.cs rename to source/CPDLCServer/AdscContracts/AdscMessageReceivedNotificationHandler.cs index d315bbb..1bb1225 100644 --- a/source/CPDLCServer/Handlers/AdscMessageReceivedNotificationHandler.cs +++ b/source/CPDLCServer/AdscContracts/AdscMessageReceivedNotificationHandler.cs @@ -1,11 +1,11 @@ -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AcarsConnections; +using CPDLCServer.AdscContracts.Reports; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts; public class AdscMessageReceivedNotificationHandler( + IAcarsConnectionManager acarsConnectionManager, IAdscContractRepository adscContractRepository, IMediator mediator, ILogger logger) @@ -44,15 +44,8 @@ public async Task Handle(AdscMessageReceivedNotification notification, Cancellat "ADS-C report received from {Callsign}", message.Sender); - if (contract.ReportReceived()) - { - logger.Information( - "{Callsign} accepted the ADS-C contract with {StationId}", - message.Sender, - notification.StationId); - - await mediator.Publish(new AdscContractChangedNotification(contract), cancellationToken); - } + contract.ReportReceived(reportMessage.Report); + await mediator.Publish(new AdscContractChangedNotification(contract), cancellationToken); await mediator.Publish( new AdscReportReceivedNotification( @@ -75,8 +68,12 @@ await mediator.Publish( // Re-establish the default contract if (selectedContractRejected) { + var configuration = await acarsConnectionManager.GetConfigurationForStation(notification.StationId, cancellationToken); await mediator.Send( - new RequestDefaultAdscContractCommand(notification.StationId, message.Sender), + new RequestPeriodicAdscContractCommand( + notification.StationId, + message.Sender, + TimeSpan.FromMinutes(configuration.DefaultAdscReportingInterval)), cancellationToken); } break; diff --git a/source/CPDLCServer/Messages/CancelAdscContractCommand.cs b/source/CPDLCServer/AdscContracts/CancelAdscContractCommand.cs similarity index 75% rename from source/CPDLCServer/Messages/CancelAdscContractCommand.cs rename to source/CPDLCServer/AdscContracts/CancelAdscContractCommand.cs index c066148..3de2af3 100644 --- a/source/CPDLCServer/Messages/CancelAdscContractCommand.cs +++ b/source/CPDLCServer/AdscContracts/CancelAdscContractCommand.cs @@ -1,6 +1,6 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AdscContracts; public record CancelAdscContractCommand( string StationId, diff --git a/source/CPDLCServer/Handlers/CancelAdscContractCommandHandler.cs b/source/CPDLCServer/AdscContracts/CancelAdscContractCommandHandler.cs similarity index 75% rename from source/CPDLCServer/Handlers/CancelAdscContractCommandHandler.cs rename to source/CPDLCServer/AdscContracts/CancelAdscContractCommandHandler.cs index 0d10970..2d6c74f 100644 --- a/source/CPDLCServer/Handlers/CancelAdscContractCommandHandler.cs +++ b/source/CPDLCServer/AdscContracts/CancelAdscContractCommandHandler.cs @@ -1,14 +1,14 @@ -using CPDLCServer.Clients; -using CPDLCServer.Messages; +using CPDLCServer.AcarsConnections; using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts; public class CancelAdscContractCommandHandler( - IClientManager clientManager, + IAcarsConnectionManager acarsConnectionManager, IAdscContractRepository adscContractRepository, IMediator mediator, + IUnitOfWork unitOfWork, ILogger logger) : IRequestHandler { @@ -30,8 +30,8 @@ public async Task Handle(CancelAdscContractCommand request, CancellationToken ca request.Callsign, request.StationId); - var client = await clientManager.GetAcarsClientForStation(request.StationId, cancellationToken); - await client.CancelAdscContract(request.Callsign, cancellationToken); + var acarsConnection = await acarsConnectionManager.GetAcarsConnectionForStation(request.StationId, cancellationToken); + unitOfWork.AfterCommit(ct => acarsConnection.CancelAdscContract(request.Callsign, ct)); await adscContractRepository.Remove(contractKey, cancellationToken); diff --git a/source/CPDLCServer/AdscContracts/CancelAdscContractOnConnectionEndedHandler.cs b/source/CPDLCServer/AdscContracts/CancelAdscContractOnConnectionEndedHandler.cs new file mode 100644 index 0000000..b97dda6 --- /dev/null +++ b/source/CPDLCServer/AdscContracts/CancelAdscContractOnConnectionEndedHandler.cs @@ -0,0 +1,59 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.Cpdlc.Connections; +using MediatR; + +namespace CPDLCServer.AdscContracts; + +// VATSIM accommodation: in real operations, ADS-C does not depend on CPDLC. +// The aircraft makes ADS-C contracts after an AFN logon, and an ATSU usually keeps its contract after a CPDLC transfer, +// until the aircraft is clear of its airspace. +// Hoppie has no AFN logon, so the CPDLC connection is the only signal that an aircraft is online. +// Thus the server cancels the ADS-C contract when the CPDLC connection ends, and when a new logon resets it. +public class CancelAdscContractOnConnectionEndedHandler( + IAcarsConnectionManager acarsConnectionManager, + IAdscContractRepository adscContractRepository, + IMediator mediator, + ILogger logger) + : INotificationHandler, + INotificationHandler, + INotificationHandler +{ + public async Task Handle(AircraftConnectionTerminated notification, CancellationToken cancellationToken) + { + await CancelContract(notification.Callsign, notification.StationId, cancellationToken); + } + + public async Task Handle(AircraftConnectionLost notification, CancellationToken cancellationToken) + { + var acarsConnection = await acarsConnectionManager.GetAcarsConnection(notification.AcarsConnectionId, cancellationToken); + await CancelContract(notification.Callsign, acarsConnection.StationId, cancellationToken); + } + + // The contract was made with the previous logon. + // Cancel it, so that the server requests a new contract for the new logon. + public async Task Handle(AircraftConnectionReset notification, CancellationToken cancellationToken) + { + await CancelContract(notification.Callsign, notification.StationId, cancellationToken); + } + + async Task CancelContract(string callsign, string stationId, CancellationToken cancellationToken) + { + // A failure here must not stop the other handlers for the ended CPDLC connection + try + { + var contract = await adscContractRepository.Find(new AdscContractKey(callsign, stationId), cancellationToken); + if (contract is null) + return; + + await mediator.Send(new CancelAdscContractCommand(stationId, callsign), cancellationToken); + } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + { + logger.Error( + ex, + "Failed to cancel ADS-C contract with {Callsign} for {StationId}", + callsign, + stationId); + } + } +} diff --git a/source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequest.cs b/source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequest.cs new file mode 100644 index 0000000..503d114 --- /dev/null +++ b/source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequest.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.AdscContracts; + +public record EndExpiredAdscContractsRequest : IRequest; diff --git a/source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequestHandler.cs b/source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequestHandler.cs new file mode 100644 index 0000000..8404d8d --- /dev/null +++ b/source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequestHandler.cs @@ -0,0 +1,84 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.Infrastructure; +using CPDLCServer.Persistence; +using CPDLCServer.Settings; +using MediatR; + +namespace CPDLCServer.AdscContracts; + +public class EndExpiredAdscContractsRequestHandler( + IAcarsConnectionManager acarsConnectionManager, + IAdscContractRepository adscContractRepository, + IServerSettingsProvider settingsProvider, + IClock clock, + ServerStartTime serverStartTime, + IMediator mediator, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(EndExpiredAdscContractsRequest request, CancellationToken cancellationToken) + { + var settings = await settingsProvider.Load(cancellationToken); + var contractTimeout = TimeSpan.FromMinutes(settings.AdscContractTimeoutMinutes); + var contracts = await adscContractRepository.All(cancellationToken); + var now = clock.UtcNow(); + + // The last activity times do not change while the server is stopped + var canApplyContractTimeout = now - serverStartTime.Started > contractTimeout; + + foreach (var contract in contracts) + { + if (!canApplyContractTimeout || now - contract.LastActivity <= contractTimeout) + continue; + + // A failure for one aircraft must not stop the other aircraft + try + { + await CancelInactiveContract(contract, cancellationToken); + } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + { + logger.Error( + ex, + "Failed to remove inactive ADS-C contract with {Callsign} for {StationId}", + contract.Callsign, + contract.StationId); + } + } + } + + async Task CancelInactiveContract(AdscContract contract, CancellationToken cancellationToken) + { + logger.Information( + "ADS-C contract with {Callsign} from {StationId} has no activity since {LastActivity}, cancelling", + contract.Callsign, + contract.StationId, + contract.LastActivity); + + // The aircraft is possibly not on the ACARS network any more. + // Remove the contract, even if the ACARS network cannot cancel it. + unitOfWork.AfterCommit(async ct => + { + try + { + var acarsConnection = await acarsConnectionManager.GetAcarsConnectionForStation(contract.StationId, ct); + await acarsConnection.CancelAdscContract(contract.Callsign, ct); + } + catch (Exception ex) when (!ct.IsCancellationRequested) + { + logger.Warning( + ex, + "Failed to cancel ADS-C contract with {Callsign} for {StationId} on the ACARS network", + contract.Callsign, + contract.StationId); + } + }); + + await adscContractRepository.Remove(new AdscContractKey(contract.Callsign, contract.StationId), cancellationToken); + + await mediator.Publish( + new AdscContractRemovedNotification(contract.Callsign, contract.StationId), + cancellationToken); + } +} diff --git a/source/CPDLCServer/Messages/GetAdscContractsRequest.cs b/source/CPDLCServer/AdscContracts/GetAdscContractsRequest.cs similarity index 83% rename from source/CPDLCServer/Messages/GetAdscContractsRequest.cs rename to source/CPDLCServer/AdscContracts/GetAdscContractsRequest.cs index f8d90f7..dc33dcf 100644 --- a/source/CPDLCServer/Messages/GetAdscContractsRequest.cs +++ b/source/CPDLCServer/AdscContracts/GetAdscContractsRequest.cs @@ -1,7 +1,7 @@ using CPDLCServer.Contracts; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AdscContracts; public record GetAdscContractsRequest : IRequest; diff --git a/source/CPDLCServer/Handlers/GetAdscContractsRequestHandler.cs b/source/CPDLCServer/AdscContracts/GetAdscContractsRequestHandler.cs similarity index 83% rename from source/CPDLCServer/Handlers/GetAdscContractsRequestHandler.cs rename to source/CPDLCServer/AdscContracts/GetAdscContractsRequestHandler.cs index 454e9f6..f149ce7 100644 --- a/source/CPDLCServer/Handlers/GetAdscContractsRequestHandler.cs +++ b/source/CPDLCServer/AdscContracts/GetAdscContractsRequestHandler.cs @@ -1,9 +1,6 @@ -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts; public class GetAdscContractsRequestHandler(IAdscContractRepository adscContractRepository) : IRequestHandler diff --git a/source/CPDLCServer/Persistence/IAdscContractRepository.cs b/source/CPDLCServer/AdscContracts/IAdscContractRepository.cs similarity index 88% rename from source/CPDLCServer/Persistence/IAdscContractRepository.cs rename to source/CPDLCServer/AdscContracts/IAdscContractRepository.cs index fddd90c..233537c 100644 --- a/source/CPDLCServer/Persistence/IAdscContractRepository.cs +++ b/source/CPDLCServer/AdscContracts/IAdscContractRepository.cs @@ -1,6 +1,4 @@ -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; +namespace CPDLCServer.AdscContracts; public interface IAdscContractRepository { diff --git a/source/CPDLCServer/Model/AdscMessageLogEntry.cs b/source/CPDLCServer/AdscContracts/MessageLog/AdscMessageLogEntry.cs similarity index 79% rename from source/CPDLCServer/Model/AdscMessageLogEntry.cs rename to source/CPDLCServer/AdscContracts/MessageLog/AdscMessageLogEntry.cs index 36568a4..7295163 100644 --- a/source/CPDLCServer/Model/AdscMessageLogEntry.cs +++ b/source/CPDLCServer/AdscContracts/MessageLog/AdscMessageLogEntry.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.AdscContracts.MessageLog; public enum AdscMessageDirection { @@ -9,7 +9,7 @@ public enum AdscMessageDirection // An ADS-C packet as it was sent to or received from the ACARS network public record AdscMessageLogEntry( DateTimeOffset Time, - string AcarsClientId, + string AcarsConnectionId, string StationId, string Callsign, AdscMessageDirection Direction, diff --git a/source/CPDLCServer/Persistence/IAdscMessageLogRepository.cs b/source/CPDLCServer/AdscContracts/MessageLog/IAdscMessageLogRepository.cs similarity index 83% rename from source/CPDLCServer/Persistence/IAdscMessageLogRepository.cs rename to source/CPDLCServer/AdscContracts/MessageLog/IAdscMessageLogRepository.cs index e7848d3..acc640c 100644 --- a/source/CPDLCServer/Persistence/IAdscMessageLogRepository.cs +++ b/source/CPDLCServer/AdscContracts/MessageLog/IAdscMessageLogRepository.cs @@ -1,6 +1,4 @@ -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; +namespace CPDLCServer.AdscContracts.MessageLog; public interface IAdscMessageLogRepository { diff --git a/source/CPDLCServer/Persistence/InMemoryAdscMessageLogRepository.cs b/source/CPDLCServer/AdscContracts/MessageLog/InMemoryAdscMessageLogRepository.cs similarity index 93% rename from source/CPDLCServer/Persistence/InMemoryAdscMessageLogRepository.cs rename to source/CPDLCServer/AdscContracts/MessageLog/InMemoryAdscMessageLogRepository.cs index dd749a2..51eadbd 100644 --- a/source/CPDLCServer/Persistence/InMemoryAdscMessageLogRepository.cs +++ b/source/CPDLCServer/AdscContracts/MessageLog/InMemoryAdscMessageLogRepository.cs @@ -1,7 +1,6 @@ -using CPDLCServer.Extensions; -using CPDLCServer.Model; +using CPDLCServer.Infrastructure; -namespace CPDLCServer.Persistence; +namespace CPDLCServer.AdscContracts.MessageLog; public class InMemoryAdscMessageLogRepository : IAdscMessageLogRepository { diff --git a/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequest.cs b/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequest.cs new file mode 100644 index 0000000..c7b8d8d --- /dev/null +++ b/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequest.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.AdscContracts; + +public record PurgeExpiredAdscDataRequest : IRequest; diff --git a/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequestHandler.cs b/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequestHandler.cs new file mode 100644 index 0000000..f729f4a --- /dev/null +++ b/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequestHandler.cs @@ -0,0 +1,23 @@ +using CPDLCServer.AdscContracts.MessageLog; +using CPDLCServer.Infrastructure; +using MediatR; + +namespace CPDLCServer.AdscContracts; + +public class PurgeExpiredAdscDataRequestHandler( + IAdscMessageLogRepository adscMessageLogRepository, + IClock clock) + : IRequestHandler +{ + // The privacy policy shows this value + public static readonly TimeSpan MessageLogRetention = TimeSpan.FromHours(24); + + // The ADS-C reports are not purged here. Each contract keeps only its latest report, and the report expires + // soon after the next periodic reports do not arrive (ExpireAdscReportsRequestHandler). + public async Task Handle(PurgeExpiredAdscDataRequest request, CancellationToken cancellationToken) + { + var now = clock.UtcNow(); + + await adscMessageLogRepository.RemoveOlderThan(now - MessageLogRetention, cancellationToken); + } +} diff --git a/source/CPDLCServer/Model/ReceivedAdscMessage.cs b/source/CPDLCServer/AdscContracts/ReceivedAdscMessage.cs similarity index 87% rename from source/CPDLCServer/Model/ReceivedAdscMessage.cs rename to source/CPDLCServer/AdscContracts/ReceivedAdscMessage.cs index fb90cc5..c20beff 100644 --- a/source/CPDLCServer/Model/ReceivedAdscMessage.cs +++ b/source/CPDLCServer/AdscContracts/ReceivedAdscMessage.cs @@ -1,4 +1,5 @@ -namespace CPDLCServer.Model; +using CPDLCServer.AdscContracts.Reports; +namespace CPDLCServer.AdscContracts; // Raw ADS-C data as parsed from an ACARS packet, before being assigned to a contract. public abstract record ReceivedAdscMessage(string Sender, DateTimeOffset Received); diff --git a/source/CPDLCServer/Model/AdscReport.cs b/source/CPDLCServer/AdscContracts/Reports/AdscReport.cs similarity index 80% rename from source/CPDLCServer/Model/AdscReport.cs rename to source/CPDLCServer/AdscContracts/Reports/AdscReport.cs index 1f1d216..e559aaa 100644 --- a/source/CPDLCServer/Model/AdscReport.cs +++ b/source/CPDLCServer/AdscContracts/Reports/AdscReport.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.AdscContracts.Reports; // ADS-C basic group. Altitude is in feet. public record AdscReport( diff --git a/source/CPDLCServer/AdscContracts/Reports/AdscReportExpiredNotification.cs b/source/CPDLCServer/AdscContracts/Reports/AdscReportExpiredNotification.cs new file mode 100644 index 0000000..9b868d0 --- /dev/null +++ b/source/CPDLCServer/AdscContracts/Reports/AdscReportExpiredNotification.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.AdscContracts.Reports; + +public record AdscReportExpiredNotification(string Callsign, string StationId) : INotification; diff --git a/source/CPDLCServer/AdscContracts/Reports/AdscReportExpiredNotificationHandler.cs b/source/CPDLCServer/AdscContracts/Reports/AdscReportExpiredNotificationHandler.cs new file mode 100644 index 0000000..3371a1d --- /dev/null +++ b/source/CPDLCServer/AdscContracts/Reports/AdscReportExpiredNotificationHandler.cs @@ -0,0 +1,36 @@ +using CPDLCServer.Controllers; +using CPDLCServer.Persistence; +using CPDLCServer.Web; +using MediatR; +using Microsoft.AspNetCore.SignalR; + +namespace CPDLCServer.AdscContracts.Reports; + +public class AdscReportExpiredNotificationHandler( + IControllerRepository controllerRepository, + IHubContext hubContext, + IUnitOfWork unitOfWork, + ILogger logger) + : INotificationHandler +{ + public async Task Handle(AdscReportExpiredNotification notification, CancellationToken cancellationToken) + { + var controllers = await controllerRepository.All(cancellationToken); + if (controllers.Length == 0) + { + logger.Verbose( + "No controllers to notify about expired ADS-C report from {Callsign}", + notification.Callsign); + return; + } + + unitOfWork.AfterCommit(ct => hubContext.Clients + .Clients(controllers.Select(c => c.ConnectionId)) + .SendAsync("AdscReportExpired", notification.Callsign, notification.StationId, ct)); + + logger.Information( + "Notified {ControllerCount} controller(s) about expired ADS-C report from {Callsign}", + controllers.Length, + notification.Callsign); + } +} diff --git a/source/CPDLCServer/Messages/AdscReportReceivedNotification.cs b/source/CPDLCServer/AdscContracts/Reports/AdscReportReceivedNotification.cs similarity index 75% rename from source/CPDLCServer/Messages/AdscReportReceivedNotification.cs rename to source/CPDLCServer/AdscContracts/Reports/AdscReportReceivedNotification.cs index 6770cdc..a7ffc8f 100644 --- a/source/CPDLCServer/Messages/AdscReportReceivedNotification.cs +++ b/source/CPDLCServer/AdscContracts/Reports/AdscReportReceivedNotification.cs @@ -1,7 +1,6 @@ -using CPDLCServer.Model; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AdscContracts.Reports; public record AdscReportReceivedNotification( string Callsign, diff --git a/source/CPDLCServer/Handlers/AdscReportReceivedNotificationHandler.cs b/source/CPDLCServer/AdscContracts/Reports/AdscReportReceivedNotificationHandler.cs similarity index 86% rename from source/CPDLCServer/Handlers/AdscReportReceivedNotificationHandler.cs rename to source/CPDLCServer/AdscContracts/Reports/AdscReportReceivedNotificationHandler.cs index e1a41f3..32e0a31 100644 --- a/source/CPDLCServer/Handlers/AdscReportReceivedNotificationHandler.cs +++ b/source/CPDLCServer/AdscContracts/Reports/AdscReportReceivedNotificationHandler.cs @@ -1,16 +1,16 @@ -using CPDLCServer.Hubs; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Controllers; using CPDLCServer.Persistence; +using CPDLCServer.Web; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts.Reports; public class AdscReportReceivedNotificationHandler( IAdscReportRepository adscReportRepository, IControllerRepository controllerRepository, IHubContext hubContext, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { @@ -36,9 +36,9 @@ await adscReportRepository.Add( notification.Report, notification.Received); - await hubContext.Clients + unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(controllers.Select(c => c.ConnectionId)) - .SendAsync("AdscReportReceived", reportDto, cancellationToken); + .SendAsync("AdscReportReceived", reportDto, ct)); logger.Information( "Notified {ControllerCount} controller(s) about ADS-C report from {Callsign}", diff --git a/source/CPDLCServer/AdscContracts/Reports/AdscReportRepository.cs b/source/CPDLCServer/AdscContracts/Reports/AdscReportRepository.cs new file mode 100644 index 0000000..9326ea7 --- /dev/null +++ b/source/CPDLCServer/AdscContracts/Reports/AdscReportRepository.cs @@ -0,0 +1,68 @@ +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.AdscContracts.Reports; + +// The changes are saved when the unit of work is committed. +// Queries load the rows into the context, then read the local entities, so that the results include entities that are +// added in the unit of work and exclude entities that are removed in it. +public class AdscReportRepository(CpdlcDbContext dbContext) : IAdscReportRepository +{ + public async Task Add(AircraftAdscReport report, CancellationToken cancellationToken) + { + var previous = await Find(report.Callsign, report.StationId, cancellationToken); + if (previous is not null) + dbContext.AdscReports.Remove(previous); + + dbContext.AdscReports.Add(report); + } + + public async Task Find(string callsign, string stationId, CancellationToken cancellationToken) + { + await dbContext.AdscReports + .Where(r => r.Callsign == callsign && r.StationId == stationId) + .LoadAsync(cancellationToken); + + return dbContext.AdscReports.Local.FirstOrDefault(r => r.Callsign == callsign && r.StationId == stationId); + } + + public async Task FindLatest(string callsign, CancellationToken cancellationToken) + { + await dbContext.AdscReports + .Where(r => r.Callsign == callsign) + .LoadAsync(cancellationToken); + + var reports = dbContext.AdscReports.Local.Where(r => r.Callsign == callsign).ToArray(); + return reports.Length == 0 ? null : SelectLatest(reports); + } + + public async Task AllLatest(CancellationToken cancellationToken) + { + var reports = await All(cancellationToken); + return reports + .GroupBy(r => r.Callsign) + .Select(SelectLatest) + .ToArray(); + } + + public async Task All(CancellationToken cancellationToken) + { + await dbContext.AdscReports.LoadAsync(cancellationToken); + return dbContext.AdscReports.Local.ToArray(); + } + + public Task Remove(AircraftAdscReport report, CancellationToken cancellationToken) + { + dbContext.AdscReports.Remove(report); + return Task.CompletedTask; + } + + // An aircraft can report to more than one ATSU, so the reports can arrive out of order + static AircraftAdscReport SelectLatest(IEnumerable reports) + { + return reports + .OrderByDescending(r => r.Report.Source == AdscReportSource.Hoppie) + .ThenByDescending(r => r.Report.Timestamp) + .First(); + } +} diff --git a/source/CPDLCServer/Model/AdscReportSource.cs b/source/CPDLCServer/AdscContracts/Reports/AdscReportSource.cs similarity index 83% rename from source/CPDLCServer/Model/AdscReportSource.cs rename to source/CPDLCServer/AdscContracts/Reports/AdscReportSource.cs index 5172ea6..e415cfa 100644 --- a/source/CPDLCServer/Model/AdscReportSource.cs +++ b/source/CPDLCServer/AdscContracts/Reports/AdscReportSource.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.AdscContracts.Reports; // The system that supplied the ADS-C report public enum AdscReportSource diff --git a/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReport.cs b/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReport.cs new file mode 100644 index 0000000..6700223 --- /dev/null +++ b/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReport.cs @@ -0,0 +1,14 @@ +namespace CPDLCServer.AdscContracts.Reports; + +// An ADS-C report from an aircraft, and the ATSU that received it +public record AircraftAdscReport( + string Callsign, + string StationId, + AdscReport Report, + DateTimeOffset Received) +{ + // EF Core uses this constructor, because it cannot give the Report to the primary constructor + private AircraftAdscReport() : this(null!, null!, null!, default) + { + } +} diff --git a/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReportConfiguration.cs b/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReportConfiguration.cs new file mode 100644 index 0000000..4bd1bbc --- /dev/null +++ b/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReportConfiguration.cs @@ -0,0 +1,33 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.AdscContracts.Reports; + +public class AircraftAdscReportConfiguration : IEntityTypeConfiguration +{ + public const string IdProperty = "Id"; + + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("AdscReports"); + + // The domain model has no ID, so the key is a shadow property + builder.Property(IdProperty); + builder.HasKey(IdProperty); + + builder.Property(r => r.Callsign); + builder.Property(r => r.StationId); + builder.Property(r => r.Received); + + builder.ComplexProperty(r => r.Report, report => + { + report.Property(r => r.Timestamp).HasColumnName("Timestamp"); + report.Property(r => r.Latitude).HasColumnName("Latitude"); + report.Property(r => r.Longitude).HasColumnName("Longitude"); + report.Property(r => r.Altitude).HasColumnName("Altitude"); + report.Property(r => r.Source).HasColumnName("Source"); + }); + + builder.HasIndex(r => new { r.Callsign, r.StationId }).IsUnique(); + } +} diff --git a/source/CPDLCServer/AdscContracts/Reports/ExpireAdscReportsRequest.cs b/source/CPDLCServer/AdscContracts/Reports/ExpireAdscReportsRequest.cs new file mode 100644 index 0000000..58cb32d --- /dev/null +++ b/source/CPDLCServer/AdscContracts/Reports/ExpireAdscReportsRequest.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.AdscContracts.Reports; + +public record ExpireAdscReportsRequest : IRequest; diff --git a/source/CPDLCServer/AdscContracts/Reports/ExpireAdscReportsRequestHandler.cs b/source/CPDLCServer/AdscContracts/Reports/ExpireAdscReportsRequestHandler.cs new file mode 100644 index 0000000..bef048c --- /dev/null +++ b/source/CPDLCServer/AdscContracts/Reports/ExpireAdscReportsRequestHandler.cs @@ -0,0 +1,51 @@ +using CPDLCServer.Infrastructure; +using MediatR; + +namespace CPDLCServer.AdscContracts.Reports; + +/// +/// Removes the ADS-C reports that are too old to show the position of the aircraft. +/// +/// A report expires when the time since the last report of its contract is more than the report expiry of the contract. +/// A report without a contract expires immediately, because the aircraft does not send more reports. +/// +/// +public class ExpireAdscReportsRequestHandler( + IAdscReportRepository adscReportRepository, + IAdscContractRepository adscContractRepository, + IClock clock, + IMediator mediator, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(ExpireAdscReportsRequest request, CancellationToken cancellationToken) + { + var reports = await adscReportRepository.All(cancellationToken); + var now = clock.UtcNow(); + + // Load all of the contracts in one query, not one query for each report + var contracts = await adscContractRepository.All(cancellationToken); + var contractsByKey = contracts.ToDictionary(c => new AdscContractKey(c.Callsign, c.StationId)); + + foreach (var report in reports) + { + var contract = contractsByKey.GetValueOrDefault(new AdscContractKey(report.Callsign, report.StationId)); + + if (contract?.LastReportReceived is not null && now - contract.LastReportReceived.Value <= contract.ReportExpiry) + continue; + + logger.Information( + "ADS-C report from {Callsign} to {StationId} at {Timestamp} has expired", + report.Callsign, + report.StationId, + report.Report.Timestamp); + + contract?.ReportTimedOut(); + await adscReportRepository.Remove(report, cancellationToken); + + await mediator.Publish( + new AdscReportExpiredNotification(report.Callsign, report.StationId), + cancellationToken); + } + } +} diff --git a/source/CPDLCServer/Messages/GetAdscReportsRequest.cs b/source/CPDLCServer/AdscContracts/Reports/GetAdscReportsRequest.cs similarity index 79% rename from source/CPDLCServer/Messages/GetAdscReportsRequest.cs rename to source/CPDLCServer/AdscContracts/Reports/GetAdscReportsRequest.cs index 29a3dfb..cc886bc 100644 --- a/source/CPDLCServer/Messages/GetAdscReportsRequest.cs +++ b/source/CPDLCServer/AdscContracts/Reports/GetAdscReportsRequest.cs @@ -1,7 +1,7 @@ using CPDLCServer.Contracts; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AdscContracts.Reports; public record GetAdscReportsRequest : IRequest; diff --git a/source/CPDLCServer/Handlers/GetAdscReportsRequestHandler.cs b/source/CPDLCServer/AdscContracts/Reports/GetAdscReportsRequestHandler.cs similarity index 73% rename from source/CPDLCServer/Handlers/GetAdscReportsRequestHandler.cs rename to source/CPDLCServer/AdscContracts/Reports/GetAdscReportsRequestHandler.cs index 78dc784..0b618e7 100644 --- a/source/CPDLCServer/Handlers/GetAdscReportsRequestHandler.cs +++ b/source/CPDLCServer/AdscContracts/Reports/GetAdscReportsRequestHandler.cs @@ -1,9 +1,6 @@ -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts.Reports; public class GetAdscReportsRequestHandler(IAdscReportRepository adscReportRepository) : IRequestHandler @@ -12,7 +9,7 @@ public async Task Handle( GetAdscReportsRequest request, CancellationToken cancellationToken) { - var reports = await adscReportRepository.All(cancellationToken); + var reports = await adscReportRepository.AllLatest(cancellationToken); var reportDtos = reports .Select(r => AdscContractConverter.ToDto(r.Callsign, r.StationId, r.Report, r.Received)) .ToArray(); diff --git a/source/CPDLCServer/AdscContracts/Reports/IAdscReportRepository.cs b/source/CPDLCServer/AdscContracts/Reports/IAdscReportRepository.cs new file mode 100644 index 0000000..213a63d --- /dev/null +++ b/source/CPDLCServer/AdscContracts/Reports/IAdscReportRepository.cs @@ -0,0 +1,17 @@ +namespace CPDLCServer.AdscContracts.Reports; + +// Holds one report for each ADS-C contract (aircraft and ATSU) +public interface IAdscReportRepository +{ + // Adds the report. The report replaces the previous report of the same aircraft and ATSU. + Task Add(AircraftAdscReport report, CancellationToken cancellationToken); + Task Find(string callsign, string stationId, CancellationToken cancellationToken); + + // The latest report of an aircraft, from all the ATSUs. + // A report from Hoppie is used before a report from VATSIM. Then the report with the latest timestamp is used. + Task FindLatest(string callsign, CancellationToken cancellationToken); + Task AllLatest(CancellationToken cancellationToken); + + Task All(CancellationToken cancellationToken); + Task Remove(AircraftAdscReport report, CancellationToken cancellationToken); +} diff --git a/source/CPDLCServer/Messages/RequestAdscDemandReportCommand.cs b/source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommand.cs similarity index 73% rename from source/CPDLCServer/Messages/RequestAdscDemandReportCommand.cs rename to source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommand.cs index 47f0f4e..089085c 100644 --- a/source/CPDLCServer/Messages/RequestAdscDemandReportCommand.cs +++ b/source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommand.cs @@ -1,6 +1,6 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AdscContracts.Reports; public record RequestAdscDemandReportCommand( string StationId, diff --git a/source/CPDLCServer/Handlers/RequestAdscDemandReportCommandHandler.cs b/source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommandHandler.cs similarity index 68% rename from source/CPDLCServer/Handlers/RequestAdscDemandReportCommandHandler.cs rename to source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommandHandler.cs index 9cb51c8..9e075dd 100644 --- a/source/CPDLCServer/Handlers/RequestAdscDemandReportCommandHandler.cs +++ b/source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommandHandler.cs @@ -1,17 +1,16 @@ -using CPDLCServer.Clients; +using CPDLCServer.AcarsConnections; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts.Reports; public class RequestAdscDemandReportCommandHandler( - IClientManager clientManager, + IAcarsConnectionManager acarsConnectionManager, IAdscContractRepository adscContractRepository, IMediator mediator, IClock clock, + IUnitOfWork unitOfWork, ILogger logger) : IRequestHandler { @@ -22,8 +21,8 @@ public async Task Handle(RequestAdscDemandReportCommand request, CancellationTok request.Callsign, request.StationId); - var client = await clientManager.GetAcarsClientForStation(request.StationId, cancellationToken); - await client.RequestAdscDemandReport(request.Callsign, cancellationToken); + var acarsConnection = await acarsConnectionManager.GetAcarsConnectionForStation(request.StationId, cancellationToken); + unitOfWork.AfterCommit(ct => acarsConnection.RequestAdscDemandReport(request.Callsign, ct)); // A demand report does not change the periodic contract. // Without a contract, the report would be ignored, so add a contract with only the demand request. @@ -31,7 +30,8 @@ public async Task Handle(RequestAdscDemandReportCommand request, CancellationTok var contract = await adscContractRepository.Find(contractKey, cancellationToken); if (contract is null) { - contract = new AdscContract(request.Callsign, request.StationId); + var configuration = await acarsConnectionManager.GetConfigurationForStation(request.StationId, cancellationToken); + contract = new AdscContract(request.Callsign, request.StationId, TimeSpan.FromMinutes(configuration.DefaultAdscReportingInterval), clock.UtcNow()); await adscContractRepository.Add(contractKey, contract, cancellationToken); } diff --git a/source/CPDLCServer/Handlers/RequestAdscContractOnConnectionEstablishedHandler.cs b/source/CPDLCServer/AdscContracts/RequestAdscContractOnConnectionEstablishedHandler.cs similarity index 74% rename from source/CPDLCServer/Handlers/RequestAdscContractOnConnectionEstablishedHandler.cs rename to source/CPDLCServer/AdscContracts/RequestAdscContractOnConnectionEstablishedHandler.cs index 7239dd9..3923d00 100644 --- a/source/CPDLCServer/Handlers/RequestAdscContractOnConnectionEstablishedHandler.cs +++ b/source/CPDLCServer/AdscContracts/RequestAdscContractOnConnectionEstablishedHandler.cs @@ -1,10 +1,11 @@ -using CPDLCServer.Messages; -using CPDLCServer.Persistence; +using CPDLCServer.AcarsConnections; +using CPDLCServer.Cpdlc.Connections; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts; public class RequestAdscContractOnConnectionEstablishedHandler( + IAcarsConnectionManager acarsConnectionManager, IAdscContractRepository adscContractRepository, IMediator mediator, ILogger logger) @@ -28,8 +29,12 @@ public async Task Handle(AircraftConnectionEstablished notification, Cancellatio return; } + var configuration = await acarsConnectionManager.GetConfigurationForStation(notification.StationId, cancellationToken); await mediator.Send( - new RequestDefaultAdscContractCommand(notification.StationId, notification.Callsign), + new RequestPeriodicAdscContractCommand( + notification.StationId, + notification.Callsign, + TimeSpan.FromMinutes(configuration.DefaultAdscReportingInterval)), cancellationToken); } catch (Exception ex) when (!cancellationToken.IsCancellationRequested) diff --git a/source/CPDLCServer/AdscContracts/RequestPeriodicAdscContractCommand.cs b/source/CPDLCServer/AdscContracts/RequestPeriodicAdscContractCommand.cs new file mode 100644 index 0000000..99617e2 --- /dev/null +++ b/source/CPDLCServer/AdscContracts/RequestPeriodicAdscContractCommand.cs @@ -0,0 +1,11 @@ +using MediatR; + +namespace CPDLCServer.AdscContracts; + +// A reporting interval that is the same as the default reporting interval of the ATSU requests the default contract. +// Any other reporting interval requests a selected contract. +public record RequestPeriodicAdscContractCommand( + string StationId, + string Callsign, + TimeSpan ReportingInterval) + : IRequest; diff --git a/source/CPDLCServer/AdscContracts/RequestPeriodicAdscContractCommandHandler.cs b/source/CPDLCServer/AdscContracts/RequestPeriodicAdscContractCommandHandler.cs new file mode 100644 index 0000000..35c0619 --- /dev/null +++ b/source/CPDLCServer/AdscContracts/RequestPeriodicAdscContractCommandHandler.cs @@ -0,0 +1,61 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.Infrastructure; +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.AdscContracts; + +public class RequestPeriodicAdscContractCommandHandler( + IAcarsConnectionManager acarsConnectionManager, + IAdscContractRepository adscContractRepository, + IMediator mediator, + IClock clock, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(RequestPeriodicAdscContractCommand request, CancellationToken cancellationToken) + { + if (request.ReportingInterval < AdscContract.MinimumReportingInterval) + throw new ArgumentOutOfRangeException( + nameof(request.ReportingInterval), + request.ReportingInterval, + $"Reporting interval must be {AdscContract.MinimumReportingInterval.TotalSeconds} seconds or more"); + + var configuration = await acarsConnectionManager.GetConfigurationForStation(request.StationId, cancellationToken); + var defaultReportingInterval = TimeSpan.FromMinutes(configuration.DefaultAdscReportingInterval); + var isDefaultContract = request.ReportingInterval == defaultReportingInterval; + + logger.Information( + "Requesting {ContractType} ADS-C contract with {Callsign} from {StationId} (Interval: {ReportingInterval})", + isDefaultContract ? "default" : "selected", + request.Callsign, + request.StationId, + request.ReportingInterval); + + var acarsConnection = await acarsConnectionManager.GetAcarsConnectionForStation(request.StationId, cancellationToken); + unitOfWork.AfterCommit(ct => acarsConnection.RequestPeriodicAdscContract(request.Callsign, request.ReportingInterval, ct)); + + var contractKey = new AdscContractKey(request.Callsign, request.StationId); + var contract = await adscContractRepository.Find(contractKey, cancellationToken); + var now = clock.UtcNow(); + if (contract is null) + { + contract = new AdscContract(request.Callsign, request.StationId, defaultReportingInterval, now); + await adscContractRepository.Add(contractKey, contract, cancellationToken); + } + + if (isDefaultContract) + { + contract.RequestDefaultContract(request.ReportingInterval); + } + else + { + contract.RequestSelectedContract(request.ReportingInterval); + } + + contract.LogActivity(now); + + await mediator.Publish(new AdscContractChangedNotification(contract), cancellationToken); + } +} diff --git a/source/CPDLCServer/Auth/AdministratorRequirement.cs b/source/CPDLCServer/Auth/AdministratorRequirement.cs new file mode 100644 index 0000000..4bd708f --- /dev/null +++ b/source/CPDLCServer/Auth/AdministratorRequirement.cs @@ -0,0 +1,25 @@ +using CPDLCServer.Auth.Administrators; +using Microsoft.AspNetCore.Authorization; + +namespace CPDLCServer.Auth; + +// Only an administrator can open the Configuration area. +// The handler reads the database for each request, so a removed administrator loses access immediately. +public class AdministratorRequirement : IAuthorizationRequirement +{ + public const string PolicyName = "Administrator"; +} + +public class AdministratorRequirementHandler(IAdministratorRepository administratorRepository) + : AuthorizationHandler +{ + protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, AdministratorRequirement requirement) + { + var cid = context.User.GetCid(); + if (cid is null) + return; + + if (await administratorRepository.FindByCid(cid, CancellationToken.None) is not null) + context.Succeed(requirement); + } +} diff --git a/source/CPDLCServer/Auth/Administrators/AddAdministratorCommand.cs b/source/CPDLCServer/Auth/Administrators/AddAdministratorCommand.cs new file mode 100644 index 0000000..aefe676 --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/AddAdministratorCommand.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.Auth.Administrators; + +public record AddAdministratorCommand(string Cid) : IRequest; diff --git a/source/CPDLCServer/Auth/Administrators/AddAdministratorCommandHandler.cs b/source/CPDLCServer/Auth/Administrators/AddAdministratorCommandHandler.cs new file mode 100644 index 0000000..fe495e2 --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/AddAdministratorCommandHandler.cs @@ -0,0 +1,29 @@ +using CPDLCServer.Infrastructure; +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.Auth.Administrators; + +public class AddAdministratorCommandHandler( + IAdministratorRepository administratorRepository, + IClock clock, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(AddAdministratorCommand request, CancellationToken cancellationToken) + { + if (await administratorRepository.FindByCid(request.Cid, cancellationToken) is not null) + throw new InvalidOperationException($"{request.Cid} is already an administrator"); + + await administratorRepository.Add( + new Administrator { Cid = request.Cid, Added = clock.UtcNow() }, + cancellationToken); + + unitOfWork.AfterCommit(_ => + { + logger.Information("Administrator {Cid} added", request.Cid); + return Task.CompletedTask; + }); + } +} diff --git a/source/CPDLCServer/Auth/Administrators/Administrator.cs b/source/CPDLCServer/Auth/Administrators/Administrator.cs new file mode 100644 index 0000000..f7250e4 --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/Administrator.cs @@ -0,0 +1,12 @@ +namespace CPDLCServer.Auth.Administrators; + +// A VATSIM user that can open the Configuration area of the dashboard +public class Administrator +{ + public required string Cid { get; init; } + + // The VATSIM API does not give the name for a CID, so the name is not known until the administrator logs in + public string? Name { get; set; } + + public DateTimeOffset Added { get; init; } +} diff --git a/source/CPDLCServer/Auth/Administrators/AdministratorConfiguration.cs b/source/CPDLCServer/Auth/Administrators/AdministratorConfiguration.cs new file mode 100644 index 0000000..5bbd609 --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/AdministratorConfiguration.cs @@ -0,0 +1,15 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.Auth.Administrators; + +public class AdministratorConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("Administrators"); + + builder.HasKey(a => a.Cid); + builder.Property(a => a.Cid).HasMaxLength(VatsimCid.MaxLength).ValueGeneratedNever(); + } +} diff --git a/source/CPDLCServer/Auth/Administrators/AdministratorRepository.cs b/source/CPDLCServer/Auth/Administrators/AdministratorRepository.cs new file mode 100644 index 0000000..062a368 --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/AdministratorRepository.cs @@ -0,0 +1,39 @@ +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Auth.Administrators; + +// The changes are saved when the unit of work is committed. +// Queries load the rows into the context, then read the local entities, so that the results include entities that are +// added in the unit of work and exclude entities that are removed in it. +public class AdministratorRepository(CpdlcDbContext dbContext) : IAdministratorRepository +{ + public Task Add(Administrator administrator, CancellationToken cancellationToken) + { + dbContext.Administrators.Add(administrator); + return Task.CompletedTask; + } + + public Task Remove(Administrator administrator, CancellationToken cancellationToken) + { + dbContext.Administrators.Remove(administrator); + return Task.CompletedTask; + } + + public async Task FindByCid(string cid, CancellationToken cancellationToken) + { + return await dbContext.Administrators.FindAsync([cid], cancellationToken); + } + + public async Task All(CancellationToken cancellationToken) + { + await dbContext.Administrators.LoadAsync(cancellationToken); + return dbContext.Administrators.Local.OrderBy(a => a.Cid, StringComparer.Ordinal).ToArray(); + } + + public async Task Any(CancellationToken cancellationToken) + { + await dbContext.Administrators.LoadAsync(cancellationToken); + return dbContext.Administrators.Local.Count > 0; + } +} diff --git a/source/CPDLCServer/Auth/Administrators/IAdministratorRepository.cs b/source/CPDLCServer/Auth/Administrators/IAdministratorRepository.cs new file mode 100644 index 0000000..0d4f366 --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/IAdministratorRepository.cs @@ -0,0 +1,10 @@ +namespace CPDLCServer.Auth.Administrators; + +public interface IAdministratorRepository +{ + Task Add(Administrator administrator, CancellationToken cancellationToken); + Task Remove(Administrator administrator, CancellationToken cancellationToken); + Task FindByCid(string cid, CancellationToken cancellationToken); + Task All(CancellationToken cancellationToken); + Task Any(CancellationToken cancellationToken); +} diff --git a/source/CPDLCServer/Auth/Administrators/RemoveAdministratorCommand.cs b/source/CPDLCServer/Auth/Administrators/RemoveAdministratorCommand.cs new file mode 100644 index 0000000..4af321f --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/RemoveAdministratorCommand.cs @@ -0,0 +1,6 @@ +using MediatR; + +namespace CPDLCServer.Auth.Administrators; + +// The current user cannot remove their own access, so that the server always has an administrator +public record RemoveAdministratorCommand(string Cid, string CurrentUserCid) : IRequest; diff --git a/source/CPDLCServer/Auth/Administrators/RemoveAdministratorCommandHandler.cs b/source/CPDLCServer/Auth/Administrators/RemoveAdministratorCommandHandler.cs new file mode 100644 index 0000000..86f1154 --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/RemoveAdministratorCommandHandler.cs @@ -0,0 +1,33 @@ +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.Auth.Administrators; + +public class RemoveAdministratorCommandHandler( + IAdministratorRepository administratorRepository, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(RemoveAdministratorCommand request, CancellationToken cancellationToken) + { + if (request.Cid == request.CurrentUserCid) + throw new InvalidOperationException("You cannot remove yourself"); + + var administrator = await administratorRepository.FindByCid(request.Cid, cancellationToken); + if (administrator is null) + throw new InvalidOperationException($"{request.Cid} is not an administrator"); + + var administrators = await administratorRepository.All(cancellationToken); + if (administrators.Length <= 1) + throw new InvalidOperationException("You cannot remove the last administrator"); + + await administratorRepository.Remove(administrator, cancellationToken); + + unitOfWork.AfterCommit(_ => + { + logger.Information("Administrator {Cid} removed by {CurrentUserCid}", request.Cid, request.CurrentUserCid); + return Task.CompletedTask; + }); + } +} diff --git a/source/CPDLCServer/Auth/Administrators/UpdateAdministratorNameCommand.cs b/source/CPDLCServer/Auth/Administrators/UpdateAdministratorNameCommand.cs new file mode 100644 index 0000000..5cf6cb4 --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/UpdateAdministratorNameCommand.cs @@ -0,0 +1,6 @@ +using MediatR; + +namespace CPDLCServer.Auth.Administrators; + +// Keeps the name of an administrator the same as the name in VATSIM. Does nothing if the user is not an administrator. +public record UpdateAdministratorNameCommand(string Cid, string Name) : IRequest; diff --git a/source/CPDLCServer/Auth/Administrators/UpdateAdministratorNameCommandHandler.cs b/source/CPDLCServer/Auth/Administrators/UpdateAdministratorNameCommandHandler.cs new file mode 100644 index 0000000..8d0dc98 --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/UpdateAdministratorNameCommandHandler.cs @@ -0,0 +1,16 @@ +using MediatR; + +namespace CPDLCServer.Auth.Administrators; + +public class UpdateAdministratorNameCommandHandler(IAdministratorRepository administratorRepository) + : IRequestHandler +{ + public async Task Handle(UpdateAdministratorNameCommand request, CancellationToken cancellationToken) + { + var administrator = await administratorRepository.FindByCid(request.Cid, cancellationToken); + if (administrator is null || administrator.Name == request.Name) + return; + + administrator.Name = request.Name; + } +} diff --git a/source/CPDLCServer/Auth/AuthServiceCollectionExtensions.cs b/source/CPDLCServer/Auth/AuthServiceCollectionExtensions.cs new file mode 100644 index 0000000..8c9db62 --- /dev/null +++ b/source/CPDLCServer/Auth/AuthServiceCollectionExtensions.cs @@ -0,0 +1,128 @@ +using System.Net.Http.Headers; +using System.Text.Json; +using CPDLCServer.Auth.Administrators; +using CPDLCServer.Auth.PluginTokens; +using CPDLCServer.Auth.VatsimConnect; +using CPDLCServer.Infrastructure; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.DataProtection; + +namespace CPDLCServer.Auth; + +public static class AuthServiceCollectionExtensions +{ + // The time without a request before the user must log in again. The privacy policy shows this value. + public static readonly TimeSpan SessionLifetime = TimeSpan.FromHours(8); + + public static IServiceCollection AddAuth( + this IServiceCollection services, + IConfiguration configuration, + IHostEnvironment environment) + { + var developmentLogin = new DevelopmentLogin( + environment.IsDevelopment() && configuration["VatsimConnect:DevCid"] is { Length: > 0 } devCid ? devCid : null); + if (developmentLogin.Cid is not null && !VatsimCid.IsValid(developmentLogin.Cid)) + throw new InvalidOperationException("VatsimConnect:DevCid must contain only digits"); + + services.AddSingleton(developmentLogin); + + services.AddScoped(); + services.AddScoped(); + services.AddSingleton(); + + // Keep the keys of the login cookies only in memory, so that no key is on the disk. + // After a restart, the user must log in again. + services.AddSingleton(); + + var authentication = services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) + .AddCookie(options => + { + options.LoginPath = "/login"; + options.LogoutPath = "/logout"; + options.AccessDeniedPath = "/access-denied"; + options.Cookie.Name = "cpdlc-session"; + options.Cookie.HttpOnly = true; + + // Lax, not Strict: after the login, VATSIM Connect redirects the browser back to this server. + // With Strict, the browser does not send the cookie in that redirect, and the user is not logged in. + options.Cookie.SameSite = SameSiteMode.Lax; + options.ExpireTimeSpan = SessionLifetime; + options.SlidingExpiration = true; + }) + .AddScheme( + PluginTokenAuthenticationHandler.AuthenticationScheme, + _ => { }); + + // With the development login, the server does not need a VATSIM Connect client + if (developmentLogin.Cid is null) + AddVatsimConnect(authentication, configuration); + + services.AddScoped(); + services.AddAuthorization(options => + { + options.AddPolicy( + AdministratorRequirement.PolicyName, + policy => policy.RequireAuthenticatedUser().AddRequirements(new AdministratorRequirement())); + + // The plugin uses its token, not the login cookie + options.AddPolicy( + PluginTokenAuthenticationHandler.PolicyName, + policy => policy + .AddAuthenticationSchemes(PluginTokenAuthenticationHandler.AuthenticationScheme) + .RequireAuthenticatedUser()); + }); + + return services; + } + + static void AddVatsimConnect(AuthenticationBuilder authentication, IConfiguration configuration) + { + var vatsimConnectOptions = new VatsimConnectOptions + { + ClientId = configuration.GetRequiredValue("VatsimConnect:ClientId"), + ClientSecret = configuration.GetRequiredValue("VatsimConnect:ClientSecret"), + Authority = configuration["VatsimConnect:Authority"] is { Length: > 0 } authority + ? new Uri(authority) + : new Uri("https://auth.vatsim.net") + }; + + authentication.AddOAuth(VatsimConnectOptions.AuthenticationScheme, "VATSIM", options => + { + options.ClientId = vatsimConnectOptions.ClientId; + options.ClientSecret = vatsimConnectOptions.ClientSecret; + options.CallbackPath = VatsimConnectOptions.CallbackPath; + options.AuthorizationEndpoint = new Uri(vatsimConnectOptions.Authority, "/oauth/authorize").ToString(); + options.TokenEndpoint = new Uri(vatsimConnectOptions.Authority, "/oauth/token").ToString(); + options.UserInformationEndpoint = new Uri(vatsimConnectOptions.Authority, "/api/user").ToString(); + options.UsePkce = true; + options.Scope.Add("full_name"); + options.Scope.Add("vatsim_details"); + + // The server uses the VATSIM token only to read the user. It does not keep the token. + options.SaveTokens = false; + + options.Events.OnCreatingTicket = async context => + { + using var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + using var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted); + response.EnsureSuccessStatusCode(); + + using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(context.HttpContext.RequestAborted)); + var user = VatsimUser.Parse(document.RootElement); + + context.Principal = new(CurrentUser.CreateIdentity(user.Cid, user.Name, VatsimConnectOptions.AuthenticationScheme)); + + var mediator = context.HttpContext.RequestServices.GetRequiredService(); + await mediator.Send(new UpdateAdministratorNameCommand(user.Cid, user.Name), context.HttpContext.RequestAborted); + + var logger = context.HttpContext.RequestServices.GetRequiredService(); + logger.Information("{Name} ({Cid}) logged in", user.Name, user.Cid); + }; + }); + } +} diff --git a/source/CPDLCServer/Auth/CurrentUser.cs b/source/CPDLCServer/Auth/CurrentUser.cs new file mode 100644 index 0000000..7ba2444 --- /dev/null +++ b/source/CPDLCServer/Auth/CurrentUser.cs @@ -0,0 +1,27 @@ +using System.Security.Claims; + +namespace CPDLCServer.Auth; + +// Reads the VATSIM user from the claims of a logged in user +public static class CurrentUser +{ + public static string? GetCid(this ClaimsPrincipal principal) + { + return principal.FindFirstValue(ClaimTypes.NameIdentifier); + } + + public static string GetName(this ClaimsPrincipal principal) + { + return principal.FindFirstValue(ClaimTypes.Name) ?? string.Empty; + } + + public static ClaimsIdentity CreateIdentity(string cid, string name, string authenticationType) + { + return new ClaimsIdentity( + [ + new Claim(ClaimTypes.NameIdentifier, cid), + new Claim(ClaimTypes.Name, name) + ], + authenticationType); + } +} diff --git a/source/CPDLCServer/Auth/PluginTokens/CreatePluginTokenCommand.cs b/source/CPDLCServer/Auth/PluginTokens/CreatePluginTokenCommand.cs new file mode 100644 index 0000000..24e470c --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/CreatePluginTokenCommand.cs @@ -0,0 +1,6 @@ +using CPDLCServer.Contracts; +using MediatR; + +namespace CPDLCServer.Auth.PluginTokens; + +public record CreatePluginTokenCommand(string Cid, string Name) : IRequest; diff --git a/source/CPDLCServer/Auth/PluginTokens/CreatePluginTokenCommandHandler.cs b/source/CPDLCServer/Auth/PluginTokens/CreatePluginTokenCommandHandler.cs new file mode 100644 index 0000000..44adb3a --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/CreatePluginTokenCommandHandler.cs @@ -0,0 +1,40 @@ +using CPDLCServer.Contracts; +using CPDLCServer.Infrastructure; +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.Auth.PluginTokens; + +public class CreatePluginTokenCommandHandler( + IPluginTokenRepository pluginTokenRepository, + IClock clock, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(CreatePluginTokenCommand request, CancellationToken cancellationToken) + { + var token = PluginTokenHash.NewToken(); + var now = clock.UtcNow(); + + var pluginToken = new PluginToken + { + Id = Guid.NewGuid(), + Cid = request.Cid, + Name = request.Name, + TokenHash = PluginTokenHash.Compute(token), + Created = now, + Expires = now + PluginToken.Lifetime + }; + + await pluginTokenRepository.Add(pluginToken, cancellationToken); + + unitOfWork.AfterCommit(_ => + { + logger.Information("Plugin token created for {Name} ({Cid})", request.Name, request.Cid); + return Task.CompletedTask; + }); + + return new PluginTokenResponse(token, pluginToken.Expires, request.Cid, request.Name); + } +} diff --git a/source/CPDLCServer/Auth/PluginTokens/IPluginTokenRepository.cs b/source/CPDLCServer/Auth/PluginTokens/IPluginTokenRepository.cs new file mode 100644 index 0000000..351beca --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/IPluginTokenRepository.cs @@ -0,0 +1,8 @@ +namespace CPDLCServer.Auth.PluginTokens; + +public interface IPluginTokenRepository +{ + Task Add(PluginToken token, CancellationToken cancellationToken); + Task Remove(PluginToken token, CancellationToken cancellationToken); + Task FindByHash(string tokenHash, CancellationToken cancellationToken); +} diff --git a/source/CPDLCServer/Auth/PluginTokens/PluginAuthorizationCodes.cs b/source/CPDLCServer/Auth/PluginTokens/PluginAuthorizationCodes.cs new file mode 100644 index 0000000..9227859 --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/PluginAuthorizationCodes.cs @@ -0,0 +1,73 @@ +using System.Collections.Concurrent; +using System.Security.Cryptography; +using System.Text; +using CPDLCServer.Infrastructure; + +namespace CPDLCServer.Auth.PluginTokens; + +/// +/// The one-use codes of the plugin login (OAuth authorization code with PKCE). +/// The browser gives the code to the plugin. The plugin changes the code for a token, with the verifier that only it has. +/// The codes are kept only in memory. They expire after one minute. +/// +public class PluginAuthorizationCodes(IClock clock) +{ + public static readonly TimeSpan CodeLifetime = TimeSpan.FromMinutes(1); + + readonly ConcurrentDictionary _codes = new(); + + public string Create(string cid, string name, string redirectUri, string codeChallenge) + { + RemoveExpired(); + + var code = PluginTokenHash.Base64Url(RandomNumberGenerator.GetBytes(32)); + _codes[code] = new PendingCode(cid, name, redirectUri, codeChallenge, clock.UtcNow() + CodeLifetime); + return code; + } + + // Returns null when the code does not exist, has expired, or does not match the redirect URI and the verifier. + // A code can be used one time only, also when the check fails. + public PluginUser? Redeem(string code, string redirectUri, string codeVerifier) + { + if (!_codes.TryRemove(code, out var pendingCode)) + return null; + + if (pendingCode.Expires <= clock.UtcNow()) + return null; + + if (pendingCode.RedirectUri != redirectUri) + return null; + + if (!IsValidVerifier(codeVerifier, pendingCode.CodeChallenge)) + return null; + + return new PluginUser(pendingCode.Cid, pendingCode.Name); + } + + // S256: the challenge is the Base64 URL of the SHA-256 of the verifier + public static string ComputeChallenge(string codeVerifier) + { + return PluginTokenHash.Base64Url(SHA256.HashData(Encoding.ASCII.GetBytes(codeVerifier))); + } + + static bool IsValidVerifier(string codeVerifier, string codeChallenge) + { + return CryptographicOperations.FixedTimeEquals( + Encoding.ASCII.GetBytes(ComputeChallenge(codeVerifier)), + Encoding.ASCII.GetBytes(codeChallenge)); + } + + void RemoveExpired() + { + var now = clock.UtcNow(); + foreach (var (code, pendingCode) in _codes) + { + if (pendingCode.Expires <= now) + _codes.TryRemove(code, out _); + } + } + + record PendingCode(string Cid, string Name, string RedirectUri, string CodeChallenge, DateTimeOffset Expires); +} + +public record PluginUser(string Cid, string Name); diff --git a/source/CPDLCServer/Auth/PluginTokens/PluginEndpoints.cs b/source/CPDLCServer/Auth/PluginTokens/PluginEndpoints.cs new file mode 100644 index 0000000..cd38b33 --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/PluginEndpoints.cs @@ -0,0 +1,62 @@ +using System.Security.Claims; +using CPDLCServer.Contracts; +using CPDLCServer.Infrastructure; + +namespace CPDLCServer.Auth.PluginTokens; + +// The plugin changes its code for a token here, and checks or revokes its token. +// The browser part of the login is the /plugin/authorize page. +public static class PluginEndpoints +{ + public static void MapPluginEndpoints(this IEndpointRouteBuilder endpoints) + { + endpoints.MapPost("/plugin/token", CreateToken); + endpoints.MapGet("/plugin/me", GetUser).RequireAuthorization(PluginTokenAuthenticationHandler.PolicyName); + endpoints.MapPost("/plugin/logout", Logout).RequireAuthorization(PluginTokenAuthenticationHandler.PolicyName); + } + + // The form is read directly, so that no antiforgery token is necessary. The plugin is not a browser. + // The PKCE verifier protects the code. + static async Task CreateToken( + HttpRequest request, + PluginAuthorizationCodes authorizationCodes, + IUnitOfWorkMediator mediator, + ILogger logger, + CancellationToken cancellationToken) + { + if (!request.HasFormContentType) + return Results.BadRequest(new { error = "invalid_request" }); + + var form = await request.ReadFormAsync(cancellationToken); + var code = form["code"].ToString(); + var codeVerifier = form["code_verifier"].ToString(); + var redirectUri = form["redirect_uri"].ToString(); + + if (string.IsNullOrEmpty(code) || string.IsNullOrEmpty(codeVerifier) || string.IsNullOrEmpty(redirectUri)) + return Results.BadRequest(new { error = "invalid_request" }); + + var user = authorizationCodes.Redeem(code, redirectUri, codeVerifier); + if (user is null) + { + logger.Warning("Plugin token request with a code that is not valid"); + return Results.BadRequest(new { error = "invalid_grant" }); + } + + var response = await mediator.Send(new CreatePluginTokenCommand(user.Cid, user.Name), cancellationToken); + return Results.Ok(response); + } + + static IResult GetUser(ClaimsPrincipal user) + { + var expires = DateTimeOffset.Parse(user.FindFirstValue(PluginTokenAuthenticationHandler.ExpiresClaimType)!); + return Results.Ok(new PluginUserDto(user.GetCid()!, user.GetName(), expires)); + } + + static async Task Logout(HttpRequest request, IUnitOfWorkMediator mediator, CancellationToken cancellationToken) + { + // The policy accepted the token, so the header has it + var token = request.Headers.Authorization.ToString()["Bearer ".Length..].Trim(); + await mediator.Send(new RevokePluginTokenCommand(token), cancellationToken); + return Results.NoContent(); + } +} diff --git a/source/CPDLCServer/Auth/PluginTokens/PluginRedirectUri.cs b/source/CPDLCServer/Auth/PluginTokens/PluginRedirectUri.cs new file mode 100644 index 0000000..40dfd71 --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/PluginRedirectUri.cs @@ -0,0 +1,19 @@ +namespace CPDLCServer.Auth.PluginTokens; + +// The plugin gets the code on a port of the computer that it runs on. Only these addresses are accepted, so that a +// link cannot send the code to a different computer. +public static class PluginRedirectUri +{ + public static bool IsValid(string? redirectUri) + { + if (!Uri.TryCreate(redirectUri, UriKind.Absolute, out var uri)) + return false; + + return uri.Scheme == Uri.UriSchemeHttp && + uri.Host is "127.0.0.1" or "localhost" && + !uri.IsDefaultPort && + string.IsNullOrEmpty(uri.Query) && + string.IsNullOrEmpty(uri.Fragment) && + string.IsNullOrEmpty(uri.UserInfo); + } +} diff --git a/source/CPDLCServer/Auth/PluginTokens/PluginToken.cs b/source/CPDLCServer/Auth/PluginTokens/PluginToken.cs new file mode 100644 index 0000000..6bd66b3 --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/PluginToken.cs @@ -0,0 +1,14 @@ +namespace CPDLCServer.Auth.PluginTokens; + +// Lets the plugin of one VATSIM user connect to the hub. The plain token is never stored, only its hash. +public class PluginToken +{ + public static readonly TimeSpan Lifetime = TimeSpan.FromDays(30); + + public Guid Id { get; init; } + public required string Cid { get; init; } + public string Name { get; init; } = string.Empty; + public string TokenHash { get; init; } = string.Empty; + public DateTimeOffset Created { get; init; } + public DateTimeOffset Expires { get; init; } +} diff --git a/source/CPDLCServer/Auth/PluginTokens/PluginTokenAuthenticationHandler.cs b/source/CPDLCServer/Auth/PluginTokens/PluginTokenAuthenticationHandler.cs new file mode 100644 index 0000000..081c9a8 --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/PluginTokenAuthenticationHandler.cs @@ -0,0 +1,57 @@ +using System.Security.Claims; +using System.Text.Encodings.Web; +using CPDLCServer.Infrastructure; +using Microsoft.AspNetCore.Authentication; +using Microsoft.Extensions.Options; + +namespace CPDLCServer.Auth.PluginTokens; + +/// +/// Authenticates the plugin with its token. The token is in the Authorization header ("Bearer ..."). +/// For the hub, the token can also be in the access_token query parameter, because a browser WebSocket cannot send headers. +/// +public class PluginTokenAuthenticationHandler( + IOptionsMonitor options, + ILoggerFactory loggerFactory, + UrlEncoder encoder, + IPluginTokenRepository pluginTokenRepository, + IClock clock) + : AuthenticationHandler(options, loggerFactory, encoder) +{ + public const string AuthenticationScheme = "PluginToken"; + + // The authorization policy of the hub and of the plugin endpoints + public const string PolicyName = "Plugin"; + public const string ExpiresClaimType = "plugin_token_expires"; + + protected override async Task HandleAuthenticateAsync() + { + var token = ReadToken(); + if (string.IsNullOrEmpty(token)) + return AuthenticateResult.NoResult(); + + var pluginToken = await pluginTokenRepository.FindByHash(PluginTokenHash.Compute(token), Context.RequestAborted); + if (pluginToken is null) + return AuthenticateResult.Fail("The token is not valid"); + + if (pluginToken.Expires <= clock.UtcNow()) + return AuthenticateResult.Fail("The token has expired"); + + var identity = CurrentUser.CreateIdentity(pluginToken.Cid, pluginToken.Name, AuthenticationScheme); + identity.AddClaim(new Claim(ExpiresClaimType, pluginToken.Expires.ToString("O"))); + + return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), AuthenticationScheme)); + } + + string? ReadToken() + { + var authorization = Request.Headers.Authorization.ToString(); + if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) + return authorization["Bearer ".Length..].Trim(); + + if (Request.Path.StartsWithSegments("/hubs")) + return Request.Query["access_token"].ToString(); + + return null; + } +} diff --git a/source/CPDLCServer/Auth/PluginTokens/PluginTokenConfiguration.cs b/source/CPDLCServer/Auth/PluginTokens/PluginTokenConfiguration.cs new file mode 100644 index 0000000..c0c8583 --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/PluginTokenConfiguration.cs @@ -0,0 +1,20 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.Auth.PluginTokens; + +public class PluginTokenConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("PluginTokens"); + + builder.HasKey(t => t.Id); + builder.Property(t => t.Id).ValueGeneratedNever(); + + builder.Property(t => t.Cid).HasMaxLength(VatsimCid.MaxLength); + + builder.HasIndex(t => t.TokenHash).IsUnique(); + builder.HasIndex(t => t.Cid); + } +} diff --git a/source/CPDLCServer/Auth/PluginTokens/PluginTokenHash.cs b/source/CPDLCServer/Auth/PluginTokens/PluginTokenHash.cs new file mode 100644 index 0000000..fc8987f --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/PluginTokenHash.cs @@ -0,0 +1,23 @@ +using System.Security.Cryptography; +using System.Text; + +namespace CPDLCServer.Auth.PluginTokens; + +public static class PluginTokenHash +{ + // The token is random and long, so a fast hash is safe. A slow hash, as for a password, is not necessary. + public static string Compute(string token) + { + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token))); + } + + public static string NewToken() + { + return Base64Url(RandomNumberGenerator.GetBytes(32)); + } + + public static string Base64Url(byte[] bytes) + { + return Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + } +} diff --git a/source/CPDLCServer/Auth/PluginTokens/PluginTokenRepository.cs b/source/CPDLCServer/Auth/PluginTokens/PluginTokenRepository.cs new file mode 100644 index 0000000..f86b1f6 --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/PluginTokenRepository.cs @@ -0,0 +1,25 @@ +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Auth.PluginTokens; + +// The changes are saved when the unit of work is committed +public class PluginTokenRepository(CpdlcDbContext dbContext) : IPluginTokenRepository +{ + public Task Add(PluginToken token, CancellationToken cancellationToken) + { + dbContext.PluginTokens.Add(token); + return Task.CompletedTask; + } + + public Task Remove(PluginToken token, CancellationToken cancellationToken) + { + dbContext.PluginTokens.Remove(token); + return Task.CompletedTask; + } + + public async Task FindByHash(string tokenHash, CancellationToken cancellationToken) + { + return await dbContext.PluginTokens.SingleOrDefaultAsync(t => t.TokenHash == tokenHash, cancellationToken); + } +} diff --git a/source/CPDLCServer/Auth/PluginTokens/RevokePluginTokenCommand.cs b/source/CPDLCServer/Auth/PluginTokens/RevokePluginTokenCommand.cs new file mode 100644 index 0000000..8961f6d --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/RevokePluginTokenCommand.cs @@ -0,0 +1,6 @@ +using MediatR; + +namespace CPDLCServer.Auth.PluginTokens; + +// Does nothing if the token does not exist +public record RevokePluginTokenCommand(string Token) : IRequest; diff --git a/source/CPDLCServer/Auth/PluginTokens/RevokePluginTokenCommandHandler.cs b/source/CPDLCServer/Auth/PluginTokens/RevokePluginTokenCommandHandler.cs new file mode 100644 index 0000000..6890747 --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/RevokePluginTokenCommandHandler.cs @@ -0,0 +1,26 @@ +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.Auth.PluginTokens; + +public class RevokePluginTokenCommandHandler( + IPluginTokenRepository pluginTokenRepository, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(RevokePluginTokenCommand request, CancellationToken cancellationToken) + { + var pluginToken = await pluginTokenRepository.FindByHash(PluginTokenHash.Compute(request.Token), cancellationToken); + if (pluginToken is null) + return; + + await pluginTokenRepository.Remove(pluginToken, cancellationToken); + + unitOfWork.AfterCommit(_ => + { + logger.Information("Plugin token revoked for {Name} ({Cid})", pluginToken.Name, pluginToken.Cid); + return Task.CompletedTask; + }); + } +} diff --git a/source/CPDLCServer/Auth/VatsimCid.cs b/source/CPDLCServer/Auth/VatsimCid.cs new file mode 100644 index 0000000..eb2f66f --- /dev/null +++ b/source/CPDLCServer/Auth/VatsimCid.cs @@ -0,0 +1,15 @@ +namespace CPDLCServer.Auth; + +// A VATSIM CID. The server keeps it as text, and accepts only digits. +public static class VatsimCid +{ + public const int MaxLength = 16; + + // For the RegularExpression attribute on the input fields + public const string Pattern = "^[0-9]+$"; + + public const string ErrorMessage = "Enter a CID that contains only digits."; + + public static bool IsValid(string? value) => + value is { Length: > 0 and <= MaxLength } && value.All(char.IsAsciiDigit); +} diff --git a/source/CPDLCServer/Auth/VatsimConnect/DevelopmentLogin.cs b/source/CPDLCServer/Auth/VatsimConnect/DevelopmentLogin.cs new file mode 100644 index 0000000..55efad9 --- /dev/null +++ b/source/CPDLCServer/Auth/VatsimConnect/DevelopmentLogin.cs @@ -0,0 +1,8 @@ +namespace CPDLCServer.Auth.VatsimConnect; + +// In development, the login page logs in each user with this CID and does not use VATSIM Connect. +// Set VatsimConnect__DevCid to use it. In other environments, the server ignores the value. +public record DevelopmentLogin(string? Cid) +{ + public const string Name = "Development User"; +} diff --git a/source/CPDLCServer/Auth/VatsimConnect/VatsimConnectOptions.cs b/source/CPDLCServer/Auth/VatsimConnect/VatsimConnectOptions.cs new file mode 100644 index 0000000..75ac2fa --- /dev/null +++ b/source/CPDLCServer/Auth/VatsimConnect/VatsimConnectOptions.cs @@ -0,0 +1,13 @@ +namespace CPDLCServer.Auth.VatsimConnect; + +// The OAuth client of this server on VATSIM Connect. Make the client at https://auth.vatsim.net (or https://auth-dev.vatsim.net). +// The redirect URL of the client is https:///signin-vatsim +public class VatsimConnectOptions +{ + public const string AuthenticationScheme = "VatsimConnect"; + public const string CallbackPath = "/signin-vatsim"; + + public required string ClientId { get; init; } + public required string ClientSecret { get; init; } + public Uri Authority { get; init; } = new("https://auth.vatsim.net"); +} diff --git a/source/CPDLCServer/Auth/VatsimConnect/VatsimUser.cs b/source/CPDLCServer/Auth/VatsimConnect/VatsimUser.cs new file mode 100644 index 0000000..58222ee --- /dev/null +++ b/source/CPDLCServer/Auth/VatsimConnect/VatsimUser.cs @@ -0,0 +1,30 @@ +using System.Text.Json; + +namespace CPDLCServer.Auth.VatsimConnect; + +// The user from the /api/user endpoint of VATSIM Connect +public record VatsimUser(string Cid, string Name) +{ + // The response is { "data": { "cid": "1234567", "personal": { "name_full": "..." } } }. + // The CID can be a string or a number. + public static VatsimUser Parse(JsonElement root) + { + var data = root.GetProperty("data"); + + var cidElement = data.GetProperty("cid"); + var cid = cidElement.ValueKind == JsonValueKind.Number + ? cidElement.GetRawText() + : cidElement.GetString() ?? string.Empty; + + if (!VatsimCid.IsValid(cid)) + throw new InvalidOperationException($"VATSIM Connect gave a CID that is not valid: {cid}"); + + // The name is empty if the user did not give the full_name scope + var name = data.TryGetProperty("personal", out var personal) && + personal.TryGetProperty("name_full", out var nameFull) + ? nameFull.GetString() ?? string.Empty + : string.Empty; + + return new VatsimUser(cid, string.IsNullOrWhiteSpace(name) ? cid : name); + } +} diff --git a/source/CPDLCServer/CPDLCServer.csproj b/source/CPDLCServer/CPDLCServer.csproj index b2f4533..2a5b15a 100644 --- a/source/CPDLCServer/CPDLCServer.csproj +++ b/source/CPDLCServer/CPDLCServer.csproj @@ -6,6 +6,8 @@ enable Linux false + + false @@ -13,19 +15,21 @@ - + + - - - - - - - + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive all - + @@ -39,14 +43,6 @@ - - - - - - - - <_ContentIncludedByDefault Remove="Pages\Dashboard\Connections\Index.cshtml" /> <_ContentIncludedByDefault Remove="Pages\Dashboard\Dialogue\Index.cshtml" /> diff --git a/source/CPDLCServer/Clients/ClientManager.cs b/source/CPDLCServer/Clients/ClientManager.cs deleted file mode 100644 index cf99337..0000000 --- a/source/CPDLCServer/Clients/ClientManager.cs +++ /dev/null @@ -1,353 +0,0 @@ -using CPDLCServer.Exceptions; -using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using MediatR; - -namespace CPDLCServer.Clients; - -public interface IClientManager -{ - Task GetAcarsClient(string acarsClientId, CancellationToken cancellationToken); - Task GetAcarsClientForStation(string stationId, CancellationToken cancellationToken); - Task GetConfigurationForStation(string stationId, CancellationToken cancellationToken); - Task FindAcarsClientId(string stationId, CancellationToken cancellationToken); -} - -public class ClientManager : BackgroundService, IClientManager -{ - readonly AcarsConfiguration[] _acarsConfigurations; - readonly SemaphoreSlim _semaphoreSlim = new(1, 1); - readonly Dictionary _clients = []; - readonly IClock _clock; - readonly IAdscMessageLogRepository _adscMessageLogRepository; - readonly ILogger _logger; - readonly IMediator _mediator; - - public ClientManager( - IConfiguration configuration, - IMediator mediator, - IClock clock, - IAdscMessageLogRepository adscMessageLogRepository, - ILogger logger) - { - var acarsConfigurationSection = configuration.GetSection("Acars"); - var configurationList = new List(); - - foreach (var section in acarsConfigurationSection.GetChildren()) - { - var type = section["Type"]; - var config = type switch - { - "Hoppie" => section.Get(), - _ => throw new NotSupportedException($"ACARS configuration type '{type}' is not supported") - }; - - if (config is not null) - { - if (TimeSpan.FromMinutes(config.DefaultAdscReportingInterval) < AdscContract.MinimumReportingInterval) - throw new Exception( - $"DefaultAdscReportingInterval for ACARS client '{config.ClientId}' must be {AdscContract.MinimumReportingInterval.TotalMinutes} minutes or more"); - - configurationList.Add(config); - } - } - - _acarsConfigurations = configurationList.ToArray(); - - _mediator = mediator; - _clock = clock; - _adscMessageLogRepository = adscMessageLogRepository; - _logger = logger.ForContext(); - } - - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - _logger.Information("Starting ACARS client manager with {Count} configurations", _acarsConfigurations.Length); - - foreach (var config in _acarsConfigurations) - { - await CreateClientWithRetry(config.ClientId, stoppingToken); - } - - _logger.Information("All ACARS clients initialized"); - - try - { - await Task.Delay(Timeout.Infinite, stoppingToken); - } - catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) - { - _logger.Information("Stopping ACARS client manager"); - } - } - - async Task CreateClientWithRetry(string acarsClientId, CancellationToken cancellationToken) - { - const int maxRetries = 5; - var retryDelay = TimeSpan.FromSeconds(1); - - for (var attempt = 0; attempt < maxRetries; attempt++) - { - try - { - var acarsClientHandle = await CreateAcarsClient(acarsClientId, cancellationToken); - _clients.Add(acarsClientId, acarsClientHandle); - - _logger.Information("Created ACARS client {ClientId}", acarsClientId); - - return; - } - catch (Exception ex) when (attempt < maxRetries - 1) - { - _logger.Warning( - ex, - "Failed to create ACARS client {ClientId} (attempt {Attempt}/{MaxRetries}). Retrying in {Delay}", - acarsClientId, - attempt + 1, - maxRetries, - retryDelay); - - await Task.Delay(retryDelay, cancellationToken); - retryDelay *= 2; - } - catch (Exception ex) - { - _logger.Error( - ex, - "Failed to create ACARS client {ClientId} after {MaxRetries} attempts. Client will not be available", - acarsClientId, - maxRetries); - break; - } - } - } - - public Task GetAcarsClient(string acarsClientId, CancellationToken cancellationToken) - { - if (!_clients.TryGetValue(acarsClientId, out var acarsClientHandle)) - { - throw new ConfigurationNotFoundException(acarsClientId); - } - - return Task.FromResult(acarsClientHandle.Client); - } - - public Task GetAcarsClientForStation(string stationId, CancellationToken cancellationToken) - { - var acarsClientHandle = _clients.Values.FirstOrDefault(h => h.Client.StationId == stationId); - if (acarsClientHandle is null) - { - throw new Exception($"No ACARS client found for station '{stationId}'"); - } - - return Task.FromResult(acarsClientHandle.Client); - } - - public Task GetConfigurationForStation(string stationId, CancellationToken cancellationToken) - { - var configuration = _acarsConfigurations.FirstOrDefault(c => c switch - { - HoppiesConfiguration hoppieConfig => hoppieConfig.StationIdentifier == stationId, - _ => throw new NotSupportedException($"ACARS configuration type {c.GetType().Name} is not supported") - }); - - if (configuration is null) - { - throw new Exception($"No ACARS configuration found for station '{stationId}'"); - } - - return Task.FromResult(configuration); - } - - public Task FindAcarsClientId(string stationId, CancellationToken cancellationToken) - { - var acarsClientId = _clients - .Where(c => string.Equals(c.Value.Client.StationId, stationId, StringComparison.OrdinalIgnoreCase)) - .Select(c => c.Key) - .FirstOrDefault(); - - return Task.FromResult(acarsClientId); - } - - async Task CreateAcarsClient(string acarsClientId, CancellationToken cancellationToken) - { - var configuration = _acarsConfigurations.FirstOrDefault(c => c.ClientId == acarsClientId); - if (configuration is null) - throw new ConfigurationNotFoundException(acarsClientId); - - IAcarsClient acarsClient = configuration switch - { - HoppiesConfiguration hoppieConfig => CreateHoppieClient(hoppieConfig), - _ => throw new NotSupportedException($"ACARS configuration type {configuration.GetType().Name} is not supported") - }; - - var stationId = configuration switch - { - HoppiesConfiguration hoppieConfig => hoppieConfig.StationIdentifier, - _ => throw new NotSupportedException($"ACARS configuration type {configuration.GetType().Name} is not supported") - }; - - var subscribeTaskCancellationSource = new CancellationTokenSource(); - var subscribeTask = Task.WhenAll( - Subscribe( - acarsClientId, - stationId, - acarsClient, - _mediator, - subscribeTaskCancellationSource.Token), - SubscribeAdsc( - acarsClientId, - stationId, - acarsClient, - _mediator, - subscribeTaskCancellationSource.Token)); - - var acarsClientHandle = new AcarsClientHandle(acarsClient, subscribeTask, subscribeTaskCancellationSource); - - await acarsClient.Connect(cancellationToken); - - _logger.Information("Connected to ACARS client {ClientId}", acarsClientId); - - return acarsClientHandle; - } - - HoppieAcarsClient CreateHoppieClient(HoppiesConfiguration configuration) - { - var httpClient = new HttpClient(); - httpClient.BaseAddress = configuration.Url; - - return new HoppieAcarsClient( - configuration, - httpClient, - _clock, - _adscMessageLogRepository, - _logger.ForContext()); - } - - async Task Subscribe(string acarsClientId, string stationId, IAcarsClient acarsClient, IMediator mediator, CancellationToken cancellationToken) - { - var subscriptionLogger = _logger.ForContext("AcarsClientId", acarsClientId); - - try - { - await foreach (var downlinkMessage in acarsClient.MessageReader.ReadAllAsync(cancellationToken)) - { - // TODO: Make this configurable - var publishTimeoutCancellationTokenSource = new CancellationTokenSource(); - publishTimeoutCancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(10)); - - try - { - await mediator.Publish( - new DownlinkReceivedNotification( - acarsClientId, - stationId, - downlinkMessage), - publishTimeoutCancellationTokenSource.Token); - } - catch (OperationCanceledException) when (publishTimeoutCancellationTokenSource.Token.IsCancellationRequested) - { - subscriptionLogger.Warning("Timeout handling downlink {Downlink}", downlinkMessage); - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - subscriptionLogger.Information("Subscription canceled"); - return; - } - catch (Exception ex) - { - subscriptionLogger.Error(ex, "Failed to relay {MessageType}", downlinkMessage.GetType()); - } - } - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - subscriptionLogger.Information("Subscription canceled"); - } - } - - async Task SubscribeAdsc(string acarsClientId, string stationId, IAcarsClient acarsClient, IMediator mediator, CancellationToken cancellationToken) - { - var subscriptionLogger = _logger.ForContext("AcarsClientId", acarsClientId); - - try - { - await foreach (var adscMessage in acarsClient.AdscMessageReader.ReadAllAsync(cancellationToken)) - { - // TODO: Make this configurable - using var publishTimeoutCancellationTokenSource = new CancellationTokenSource(); - publishTimeoutCancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(10)); - - try - { - await mediator.Publish( - new AdscMessageReceivedNotification( - acarsClientId, - stationId, - adscMessage), - publishTimeoutCancellationTokenSource.Token); - } - catch (OperationCanceledException) when (publishTimeoutCancellationTokenSource.Token.IsCancellationRequested) - { - subscriptionLogger.Warning("Timeout handling ADS-C message {AdscMessage}", adscMessage); - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - subscriptionLogger.Information("ADS-C subscription canceled"); - return; - } - catch (Exception ex) - { - subscriptionLogger.Error(ex, "Failed to relay {MessageType}", adscMessage.GetType()); - } - } - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - subscriptionLogger.Information("ADS-C subscription canceled"); - } - } - - record AcarsClientHandle( - IAcarsClient Client, - Task SubscribeTask, - CancellationTokenSource SubscribeCancellationTokenSource) : IAsyncDisposable - { - public async ValueTask DisposeAsync() - { - await Client.DisposeAsync(); - - await SubscribeCancellationTokenSource.CancelAsync(); - - try - { - await SubscribeTask; - } - catch (OperationCanceledException) - { - // Expected during shutdown - } - - SubscribeCancellationTokenSource.Dispose(); - SubscribeTask.Dispose(); - } - } - - - public override async Task StopAsync(CancellationToken cancellationToken) - { - _logger.Information("Stopping ACARS client manager and disposing all clients"); - - await base.StopAsync(cancellationToken); - - foreach (var (_, clientHandle) in _clients) - { - await clientHandle.DisposeAsync(); - } - - _clients.Clear(); - _semaphoreSlim.Dispose(); - } -} diff --git a/source/CPDLCServer/Clients/IAcarsClient.cs b/source/CPDLCServer/Clients/IAcarsClient.cs deleted file mode 100644 index 5cff89a..0000000 --- a/source/CPDLCServer/Clients/IAcarsClient.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.Threading.Channels; -using CPDLCServer.Contracts; -using CPDLCServer.Model; - -namespace CPDLCServer.Clients; - -public interface IAcarsClient : IAsyncDisposable -{ - ChannelReader MessageReader { get; } - ChannelReader AdscMessageReader { get; } - string StationId { get; } - Task Connect(CancellationToken cancellationToken); - Task Send(UplinkMessage message, CancellationToken cancellationToken); - Task RequestPeriodicAdscContract(string callsign, TimeSpan reportingInterval, CancellationToken cancellationToken); - Task RequestAdscDemandReport(string callsign, CancellationToken cancellationToken); - Task CancelAdscContract(string callsign, CancellationToken cancellationToken); - Task ListConnections(CancellationToken cancellationToken); - Task Disconnect(CancellationToken cancellationToken); -} diff --git a/source/CPDLCServer/Messages/ControllerConnectedNotification.cs b/source/CPDLCServer/Controllers/ControllerConnectedNotification.cs similarity index 78% rename from source/CPDLCServer/Messages/ControllerConnectedNotification.cs rename to source/CPDLCServer/Controllers/ControllerConnectedNotification.cs index a6275d4..a81405c 100644 --- a/source/CPDLCServer/Messages/ControllerConnectedNotification.cs +++ b/source/CPDLCServer/Controllers/ControllerConnectedNotification.cs @@ -1,5 +1,5 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Controllers; public record ControllerConnectedNotification(Guid UserId, string StationId, string Callsign) : INotification; diff --git a/source/CPDLCServer/Handlers/ControllerConnectedNotificationHandler.cs b/source/CPDLCServer/Controllers/ControllerConnectedNotificationHandler.cs similarity index 76% rename from source/CPDLCServer/Handlers/ControllerConnectedNotificationHandler.cs rename to source/CPDLCServer/Controllers/ControllerConnectedNotificationHandler.cs index 9425f1d..6b874ab 100644 --- a/source/CPDLCServer/Handlers/ControllerConnectedNotificationHandler.cs +++ b/source/CPDLCServer/Controllers/ControllerConnectedNotificationHandler.cs @@ -1,15 +1,15 @@ using CPDLCServer.Contracts; -using CPDLCServer.Hubs; -using CPDLCServer.Messages; using CPDLCServer.Persistence; +using CPDLCServer.Web; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Controllers; public class ControllerConnectedNotificationHandler( IControllerRepository controllerRepository, IHubContext hubContext, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { @@ -32,15 +32,11 @@ public async Task Handle(ControllerConnectedNotification notification, Cancellat } // Notify all other controllers that a peer controller has connected - await hubContext.Clients + var controllerDto = new ControllerConnectionDto(notification.StationId, notification.Callsign); + + unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(otherControllers.Select(c => c.ConnectionId)) - .SendAsync( - "ControllerConnectionUpdated", - new ControllerConnectionDto( - notification.StationId, - notification.Callsign, - controllers.First(c => c.UserId == notification.UserId).VatsimCid), - cancellationToken); + .SendAsync("ControllerConnectionUpdated", controllerDto, ct)); logger.Information( "Notified {ControllerCount} controller(s) about connected controller {Callsign}", diff --git a/source/CPDLCServer/Messages/ControllerDisconnectedNotification.cs b/source/CPDLCServer/Controllers/ControllerDisconnectedNotification.cs similarity index 76% rename from source/CPDLCServer/Messages/ControllerDisconnectedNotification.cs rename to source/CPDLCServer/Controllers/ControllerDisconnectedNotification.cs index d43a2e5..ac17f84 100644 --- a/source/CPDLCServer/Messages/ControllerDisconnectedNotification.cs +++ b/source/CPDLCServer/Controllers/ControllerDisconnectedNotification.cs @@ -1,5 +1,5 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Controllers; public record ControllerDisconnectedNotification(Guid UserId, string Callsign) : INotification; diff --git a/source/CPDLCServer/Handlers/ControllerDisconnectedNotificationHandler.cs b/source/CPDLCServer/Controllers/ControllerDisconnectedNotificationHandler.cs similarity index 89% rename from source/CPDLCServer/Handlers/ControllerDisconnectedNotificationHandler.cs rename to source/CPDLCServer/Controllers/ControllerDisconnectedNotificationHandler.cs index 3717865..c08d3eb 100644 --- a/source/CPDLCServer/Handlers/ControllerDisconnectedNotificationHandler.cs +++ b/source/CPDLCServer/Controllers/ControllerDisconnectedNotificationHandler.cs @@ -1,14 +1,14 @@ -using CPDLCServer.Hubs; -using CPDLCServer.Messages; using CPDLCServer.Persistence; +using CPDLCServer.Web; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Controllers; public class ControllerDisconnectedNotificationHandler( IControllerRepository controllerRepository, IHubContext hubContext, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { @@ -29,9 +29,9 @@ public async Task Handle(ControllerDisconnectedNotification notification, Cancel } // Notify all remaining controllers that a peer controller has disconnected - await hubContext.Clients + unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(controllers.Select(c => c.ConnectionId)) - .SendAsync("ControllerConnectionRemoved", notification.Callsign, cancellationToken); + .SendAsync("ControllerConnectionRemoved", notification.Callsign, ct)); logger.Information( "Notified {ControllerCount} controller(s) about disconnected controller {Callsign}", diff --git a/source/CPDLCServer/Model/ControllerInfo.cs b/source/CPDLCServer/Controllers/ControllerInfo.cs similarity index 50% rename from source/CPDLCServer/Model/ControllerInfo.cs rename to source/CPDLCServer/Controllers/ControllerInfo.cs index bafa2e7..ca7c68a 100644 --- a/source/CPDLCServer/Model/ControllerInfo.cs +++ b/source/CPDLCServer/Controllers/ControllerInfo.cs @@ -1,15 +1,19 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.Controllers; +// A controller that is connected to the hub with the plugin. +// The user ID identifies the hub connection. The CID and the name come from the plugin token. public class ControllerInfo( Guid userId, string connectionId, string stationId, string callsign, - string vatsimCid) + string cid, + string name) { public Guid UserId { get; } = userId; public string ConnectionId { get; } = connectionId; public string StationId { get; } = stationId; public string Callsign { get; } = callsign; - public string VatsimCid { get; } = vatsimCid; + public string Cid { get; } = cid; + public string Name { get; } = name; } diff --git a/source/CPDLCServer/Controllers/ControllersServiceCollectionExtensions.cs b/source/CPDLCServer/Controllers/ControllersServiceCollectionExtensions.cs new file mode 100644 index 0000000..4844390 --- /dev/null +++ b/source/CPDLCServer/Controllers/ControllersServiceCollectionExtensions.cs @@ -0,0 +1,12 @@ +namespace CPDLCServer.Controllers; + +public static class ControllersServiceCollectionExtensions +{ + // Not AddControllers, because ASP.NET Core MVC already has a method with that name + public static IServiceCollection AddAirTrafficControllers(this IServiceCollection services) + { + services.AddSingleton(); + + return services; + } +} diff --git a/source/CPDLCServer/Messages/GetConnectedControllersRequest.cs b/source/CPDLCServer/Controllers/GetConnectedControllersRequest.cs similarity index 86% rename from source/CPDLCServer/Messages/GetConnectedControllersRequest.cs rename to source/CPDLCServer/Controllers/GetConnectedControllersRequest.cs index 3be2841..e1466b9 100644 --- a/source/CPDLCServer/Messages/GetConnectedControllersRequest.cs +++ b/source/CPDLCServer/Controllers/GetConnectedControllersRequest.cs @@ -1,7 +1,7 @@ using CPDLCServer.Contracts; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Controllers; public record GetConnectedControllersRequest : IRequest; diff --git a/source/CPDLCServer/Handlers/GetConnectedControllersRequestHandler.cs b/source/CPDLCServer/Controllers/GetConnectedControllersRequestHandler.cs similarity index 84% rename from source/CPDLCServer/Handlers/GetConnectedControllersRequestHandler.cs rename to source/CPDLCServer/Controllers/GetConnectedControllersRequestHandler.cs index a186a5b..67674fa 100644 --- a/source/CPDLCServer/Handlers/GetConnectedControllersRequestHandler.cs +++ b/source/CPDLCServer/Controllers/GetConnectedControllersRequestHandler.cs @@ -1,9 +1,7 @@ using CPDLCServer.Contracts; -using CPDLCServer.Messages; -using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Controllers; public class GetConnectedControllersRequestHandler(IControllerRepository controllerRepository) : IRequestHandler @@ -15,7 +13,7 @@ public async Task Handle( var controllers = await controllerRepository.All(cancellationToken); var controllerInfo = controllers - .Select(c => new ControllerConnectionDto(c.StationId, c.Callsign, c.VatsimCid)) + .Select(c => new ControllerConnectionDto(c.StationId, c.Callsign)) .ToArray(); return new GetConnectedControllersResult(controllerInfo); diff --git a/source/CPDLCServer/Persistence/IControllerRepository.cs b/source/CPDLCServer/Controllers/IControllerRepository.cs similarity index 86% rename from source/CPDLCServer/Persistence/IControllerRepository.cs rename to source/CPDLCServer/Controllers/IControllerRepository.cs index fa31d1b..d4a09c1 100644 --- a/source/CPDLCServer/Persistence/IControllerRepository.cs +++ b/source/CPDLCServer/Controllers/IControllerRepository.cs @@ -1,6 +1,4 @@ -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; +namespace CPDLCServer.Controllers; public interface IControllerRepository { diff --git a/source/CPDLCServer/Persistence/InMemoryControllerRepository.cs b/source/CPDLCServer/Controllers/InMemoryControllerRepository.cs similarity index 93% rename from source/CPDLCServer/Persistence/InMemoryControllerRepository.cs rename to source/CPDLCServer/Controllers/InMemoryControllerRepository.cs index 711242d..4f5d4fc 100644 --- a/source/CPDLCServer/Persistence/InMemoryControllerRepository.cs +++ b/source/CPDLCServer/Controllers/InMemoryControllerRepository.cs @@ -1,7 +1,6 @@ -using CPDLCServer.Extensions; -using CPDLCServer.Model; +using CPDLCServer.Infrastructure; -namespace CPDLCServer.Persistence; +namespace CPDLCServer.Controllers; public class InMemoryControllerRepository : IControllerRepository { diff --git a/source/CPDLCServer/Model/AircraftConnection.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnection.cs similarity index 94% rename from source/CPDLCServer/Model/AircraftConnection.cs rename to source/CPDLCServer/Cpdlc/Connections/AircraftConnection.cs index 233e142..613e573 100644 --- a/source/CPDLCServer/Model/AircraftConnection.cs +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnection.cs @@ -1,15 +1,15 @@ using System.Diagnostics.CodeAnalysis; -namespace CPDLCServer.Model; +namespace CPDLCServer.Cpdlc.Connections; public class AircraftConnection( string callsign, - string acarsClientId, + string acarsConnectionId, string stationId, DataAuthorityState dataAuthorityState) { public string Callsign { get; } = callsign; - public string AcarsClientId { get; } = acarsClientId; + public string AcarsConnectionId { get; } = acarsConnectionId; public string StationId { get; } = stationId; public DataAuthorityState DataAuthorityState { get; private set; } = dataAuthorityState; diff --git a/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionConfiguration.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionConfiguration.cs new file mode 100644 index 0000000..02fa328 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionConfiguration.cs @@ -0,0 +1,34 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.Cpdlc.Connections; + +public class AircraftConnectionConfiguration : IEntityTypeConfiguration +{ + public const string IdProperty = "Id"; + + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("AircraftConnections"); + + // The domain model has no ID, so the key is a shadow property + builder.Property(IdProperty); + builder.HasKey(IdProperty); + + builder.Property(c => c.Callsign); + builder.Property(c => c.AcarsConnectionId); + builder.Property(c => c.StationId); + builder.Property(c => c.DataAuthorityState); + builder.Property(c => c.ConnectionState); + builder.Property(c => c.LogonRequested); + builder.Property(c => c.LogonAccepted); + builder.Property(c => c.LastSeen); + builder.Property(c => c.NextDataAuthority); + builder.Property(c => c.ExpectedTransferTime); + builder.Property(c => c.DidSentNextDataAuthorityMessage); + + // One connection for each aircraft on an ACARS connection. + // Two units of work that add the same connection at the same time cannot both commit. + builder.HasIndex(c => new { c.Callsign, c.AcarsConnectionId }).IsUnique(); + } +} diff --git a/source/CPDLCServer/Messages/AircraftConnectionEstablished.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionEstablished.cs similarity index 67% rename from source/CPDLCServer/Messages/AircraftConnectionEstablished.cs rename to source/CPDLCServer/Cpdlc/Connections/AircraftConnectionEstablished.cs index bf63fcc..33ed476 100644 --- a/source/CPDLCServer/Messages/AircraftConnectionEstablished.cs +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionEstablished.cs @@ -1,10 +1,9 @@ -using CPDLCServer.Model; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Connections; public record AircraftConnectionEstablished( - string AcarsClientId, + string AcarsConnectionId, string StationId, string Callsign, DataAuthorityState DataAuthorityState) diff --git a/source/CPDLCServer/Handlers/AircraftConnectionEstablishedNotificationHandler.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandler.cs similarity index 78% rename from source/CPDLCServer/Handlers/AircraftConnectionEstablishedNotificationHandler.cs rename to source/CPDLCServer/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandler.cs index 736849c..b67f4b3 100644 --- a/source/CPDLCServer/Handlers/AircraftConnectionEstablishedNotificationHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandler.cs @@ -1,31 +1,30 @@ -using CPDLCServer.Clients; -using CPDLCServer.Contracts; -using CPDLCServer.Hubs; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Dialogues; using CPDLCServer.Persistence; +using CPDLCServer.Web; +using CPDLCServer.Contracts; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Connections; public class AircraftConnectionEstablishedNotificationHandler( IControllerRepository controllerRepository, IHubContext hubContext, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { public async Task Handle(AircraftConnectionEstablished notification, CancellationToken cancellationToken) { logger.Information( - "Aircraft {Callsign} connected on {AcarsClientId} with data authority state {DataAuthorityState}", + "Aircraft {Callsign} connected on {AcarsConnectionId} with data authority state {DataAuthorityState}", notification.Callsign, - notification.AcarsClientId, + notification.AcarsConnectionId, notification.DataAuthorityState); // Find all controllers on the same network and station var controllers = await controllerRepository.All(cancellationToken); - if (!controllers.Any()) { logger.Information( @@ -35,12 +34,12 @@ public async Task Handle(AircraftConnectionEstablished notification, Cancellatio } // Notify all controllers that an aircraft has connected - await hubContext.Clients + unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(controllers.Select(c => c.ConnectionId)) .SendAsync( "AircraftConnectionUpdated", new AircraftConnectionDto(notification.Callsign, notification.StationId, DialogueConverter.ToDto(notification.DataAuthorityState)), - cancellationToken); + ct)); logger.Information( "Notified {ControllerCount} controller(s) about connected aircraft {Callsign}", diff --git a/source/CPDLCServer/Messages/AircraftConnectionLost.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLost.cs similarity index 57% rename from source/CPDLCServer/Messages/AircraftConnectionLost.cs rename to source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLost.cs index e9cecac..069c73b 100644 --- a/source/CPDLCServer/Messages/AircraftConnectionLost.cs +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLost.cs @@ -1,8 +1,8 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Connections; public record AircraftConnectionLost( - string AcarsClientId, + string AcarsConnectionId, string Callsign) : INotification; diff --git a/source/CPDLCServer/Handlers/AircraftConnectionLostNotificationHandler.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLostNotificationHandler.cs similarity index 63% rename from source/CPDLCServer/Handlers/AircraftConnectionLostNotificationHandler.cs rename to source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLostNotificationHandler.cs index c7f372c..8e74f8b 100644 --- a/source/CPDLCServer/Handlers/AircraftConnectionLostNotificationHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLostNotificationHandler.cs @@ -1,13 +1,14 @@ -using CPDLCServer.Hubs; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; using CPDLCServer.Persistence; -using CPDLCServer.Services; +using CPDLCServer.Web; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Connections; public class AircraftConnectionLostNotificationHandler( IAircraftRepository aircraftRepository, @@ -17,84 +18,51 @@ public class AircraftConnectionLostNotificationHandler( IMessageIdProvider messageIdProvider, IPublisher publisher, IClock clock, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { public async Task Handle(AircraftConnectionLost notification, CancellationToken cancellationToken) { var aircraft = await aircraftRepository.Find( - new(notification.Callsign, notification.AcarsClientId), + new(notification.Callsign, notification.AcarsConnectionId), cancellationToken); if (aircraft is null) { logger.Information( - "Aircraft {Callsign} already removed from tracking on {AcarsClientId}", + "Aircraft {Callsign} already removed from tracking on {AcarsConnectionId}", notification.Callsign, - notification.AcarsClientId); + notification.AcarsConnectionId); return; } // Remove aircraft from tracking await aircraftRepository.Remove( - new(notification.Callsign, notification.AcarsClientId), + new(notification.Callsign, notification.AcarsConnectionId), cancellationToken); logger.Information( - "Aircraft {Callsign} lost on {AcarsClientId}", + "Aircraft {Callsign} lost on {AcarsConnectionId}", notification.Callsign, - notification.AcarsClientId); + notification.AcarsConnectionId); - // Find all controllers on the same network and station - var controllers = await controllerRepository.All(cancellationToken); - - if (!controllers.Any()) - { - logger.Information( - "No controllers to notify about lost aircraft {Callsign}", - notification.Callsign); - return; - } - - var allDialogues = await dialogueRepository.All(cancellationToken); - var aircraftDialogues = allDialogues - .Where(d => d.AircraftCallsign == notification.Callsign && !d.IsArchived) - .ToArray(); - - var openDialogues = aircraftDialogues.Where(d => !d.IsClosed).ToArray(); + // Close the dialogues also when no controllers are online, so that no dialogue of the lost connection stays open + var openDialogues = await dialogueRepository.FindOpenForAircraft( + notification.Callsign, + aircraft.StationId, + cancellationToken); if (openDialogues.Any()) { - // Add error message to each open dialogue + // Add error message to each open dialogue, then close the remaining open messages, because no response can arrive foreach (var dialogue in openDialogues) { - // Find an open message to reference - var openMessage = dialogue.Messages.FirstOrDefault(m => !m.IsClosed); - - if (openMessage is null) - { - logger.Warning( - "Dialogue {DialogueId} is marked as open but has no open messages", - dialogue.Id); - continue; - } - var messageId = await messageIdProvider.GetNextMessageId( - notification.AcarsClientId, + notification.AcarsConnectionId, notification.Callsign, cancellationToken); - var now = clock.UtcNow(); - dialogue.AddDownlink( - messageId, - openMessage.MessageId, - notification.Callsign, - CpdlcDownlinkResponseType.NoResponse, - AlertType.Medium, - "ERROR CONNECTION TIMED OUT", - now); - - // No response can arrive, so close the remaining open messages - dialogue.Abort(now); + dialogue.AbortWithError(messageId, "ERROR CONNECTION TIMED OUT", clock.UtcNow()); // Publish DialogueChangedNotification await publisher.Publish(new DialogueChangedNotification(dialogue), cancellationToken); @@ -109,11 +77,11 @@ await aircraftRepository.Remove( { // No open dialogues, create a new one with the error message var messageId = await messageIdProvider.GetNextMessageId( - notification.AcarsClientId, + notification.AcarsConnectionId, notification.Callsign, cancellationToken); - var dialogue = new Dialogue(notification.Callsign); + var dialogue = new Dialogue(notification.Callsign, aircraft.StationId); dialogue.AddDownlink( messageId, null, @@ -134,11 +102,23 @@ await aircraftRepository.Remove( notification.Callsign); } + // After the error messages, because they use the message IDs of the connection + await messageIdProvider.Remove(notification.AcarsConnectionId, notification.Callsign, cancellationToken); + // Notify controllers that the aircraft has disconnected + var controllers = await controllerRepository.All(cancellationToken); + if (!controllers.Any()) + { + logger.Information( + "No controllers to notify about lost aircraft {Callsign}", + notification.Callsign); + return; + } + var controllerConnectionIds = controllers.Select(c => c.ConnectionId).ToArray(); - await hubContext.Clients + unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(controllerConnectionIds) - .SendAsync("AircraftConnectionRemoved", notification.Callsign, aircraft.StationId, cancellationToken); + .SendAsync("AircraftConnectionRemoved", notification.Callsign, aircraft.StationId, ct)); logger.Information( "Notified {ControllerCount} controller(s) about lost aircraft {Callsign}", diff --git a/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionReset.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionReset.cs new file mode 100644 index 0000000..a624a3c --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionReset.cs @@ -0,0 +1,10 @@ +using MediatR; + +namespace CPDLCServer.Cpdlc.Connections; + +// A new logon replaced the connection of an aircraft. The pilot can be a different pilot with the same callsign. +public record AircraftConnectionReset( + string AcarsConnectionId, + string StationId, + string Callsign) + : INotification; diff --git a/source/CPDLCServer/Messages/AircraftConnectionTerminated.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionTerminated.cs similarity index 63% rename from source/CPDLCServer/Messages/AircraftConnectionTerminated.cs rename to source/CPDLCServer/Cpdlc/Connections/AircraftConnectionTerminated.cs index ee76389..8f726f4 100644 --- a/source/CPDLCServer/Messages/AircraftConnectionTerminated.cs +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionTerminated.cs @@ -1,9 +1,9 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Connections; public record AircraftConnectionTerminated( - string AcarsClientId, + string AcarsConnectionId, string StationId, string Callsign) : INotification; diff --git a/source/CPDLCServer/Handlers/AircraftConnectionTerminatedNotificationHandler.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandler.cs similarity index 77% rename from source/CPDLCServer/Handlers/AircraftConnectionTerminatedNotificationHandler.cs rename to source/CPDLCServer/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandler.cs index ea08d38..5f7008c 100644 --- a/source/CPDLCServer/Handlers/AircraftConnectionTerminatedNotificationHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandler.cs @@ -1,23 +1,24 @@ -using CPDLCServer.Hubs; -using CPDLCServer.Messages; +using CPDLCServer.Controllers; using CPDLCServer.Persistence; +using CPDLCServer.Web; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Connections; public class AircraftConnectionTerminatedNotificationHandler( IControllerRepository controllerRepository, IHubContext hubContext, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { public async Task Handle(AircraftConnectionTerminated notification, CancellationToken cancellationToken) { logger.Information( - "Aircraft {Callsign} disconnected from {AcarsClientId}", + "Aircraft {Callsign} disconnected from {AcarsConnectionId}", notification.Callsign, - notification.AcarsClientId); + notification.AcarsConnectionId); var controllers = await controllerRepository.All(cancellationToken); if (!controllers.Any()) @@ -29,9 +30,9 @@ public async Task Handle(AircraftConnectionTerminated notification, Cancellation } // Notify all controllers that an aircraft has disconnected - await hubContext.Clients + unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(controllers.Select(c => c.ConnectionId)) - .SendAsync("AircraftConnectionRemoved", notification.Callsign, notification.StationId, cancellationToken); + .SendAsync("AircraftConnectionRemoved", notification.Callsign, notification.StationId, ct)); logger.Information( "Notified {ControllerCount} controller(s) about disconnected aircraft {Callsign}", diff --git a/source/CPDLCServer/Cpdlc/Connections/AircraftRepository.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftRepository.cs new file mode 100644 index 0000000..1c31ba6 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftRepository.cs @@ -0,0 +1,46 @@ +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Cpdlc.Connections; + +// The changes are saved when the unit of work is committed. +// Queries load the rows into the context, then read the local entities, so that the results include entities that are +// added in the unit of work and exclude entities that are removed in it. +public class AircraftRepository(CpdlcDbContext dbContext) : IAircraftRepository +{ + public async Task Add(AircraftKey aircraftKey, AircraftConnection connection, CancellationToken cancellationToken) + { + // A new connection replaces the connection with the same key + var existing = await Find(aircraftKey, cancellationToken); + if (existing is not null) + dbContext.AircraftConnections.Remove(existing); + + dbContext.AircraftConnections.Add(connection); + } + + public async Task Find(AircraftKey aircraftKey, CancellationToken cancellationToken) + { + await dbContext.AircraftConnections + .Where(c => c.Callsign == aircraftKey.Callsign && c.AcarsConnectionId == aircraftKey.AcarsConnectionId) + .LoadAsync(cancellationToken); + + return dbContext.AircraftConnections.Local + .FirstOrDefault(c => c.Callsign == aircraftKey.Callsign && c.AcarsConnectionId == aircraftKey.AcarsConnectionId); + } + + public async Task All(CancellationToken cancellationToken) + { + await dbContext.AircraftConnections.LoadAsync(cancellationToken); + return dbContext.AircraftConnections.Local.ToArray(); + } + + public async Task Remove(AircraftKey aircraftKey, CancellationToken cancellationToken) + { + var connection = await Find(aircraftKey, cancellationToken); + if (connection is null) + return false; + + dbContext.AircraftConnections.Remove(connection); + return true; + } +} diff --git a/source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequest.cs b/source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequest.cs new file mode 100644 index 0000000..7baf587 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequest.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.Cpdlc.Connections; + +public record CheckLostAircraftConnectionsRequest : IRequest; diff --git a/source/CPDLCServer/Handlers/CheckLostAircraftConnectionsRequestHandler.cs b/source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequestHandler.cs similarity index 55% rename from source/CPDLCServer/Handlers/CheckLostAircraftConnectionsRequestHandler.cs rename to source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequestHandler.cs index d67588b..290969d 100644 --- a/source/CPDLCServer/Handlers/CheckLostAircraftConnectionsRequestHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequestHandler.cs @@ -1,25 +1,36 @@ using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Persistence; +using CPDLCServer.Settings; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Connections; public class CheckLostAircraftConnectionsRequestHandler( IAircraftRepository aircraftRepository, + IServerSettingsProvider settingsProvider, IClock clock, + ServerStartTime serverStartTime, IMediator mediator, ILogger logger) : IRequestHandler { public async Task Handle(CheckLostAircraftConnectionsRequest request, CancellationToken cancellationToken) { - var connections = await aircraftRepository.All(cancellationToken); + var settings = await settingsProvider.Load(cancellationToken); + var connectionTimeout = TimeSpan.FromMinutes(settings.AircraftConnectionTimeoutMinutes); var now = clock.UtcNow(); + // The last seen times do not change while the server is stopped + if (now - serverStartTime.Started <= connectionTimeout) + { + logger.Debug("Server has not been online for longer than the connection timeout, not checking for lost connections"); + return; + } + + var connections = await aircraftRepository.All(cancellationToken); + foreach (var connection in connections) { var timeSinceLastSeen = now - connection.LastSeen; - if (timeSinceLastSeen <= request.ConnectionTimeout) + if (timeSinceLastSeen <= connectionTimeout) { continue; } @@ -30,7 +41,7 @@ public async Task Handle(CheckLostAircraftConnectionsRequest request, Cancellati timeSinceLastSeen); await mediator.Publish( - new AircraftConnectionLost(connection.AcarsClientId, connection.Callsign), + new AircraftConnectionLost(connection.AcarsConnectionId, connection.Callsign), cancellationToken); } } diff --git a/source/CPDLCServer/Model/ConnectionState.cs b/source/CPDLCServer/Cpdlc/Connections/ConnectionState.cs similarity index 59% rename from source/CPDLCServer/Model/ConnectionState.cs rename to source/CPDLCServer/Cpdlc/Connections/ConnectionState.cs index 5be73f8..76e010e 100644 --- a/source/CPDLCServer/Model/ConnectionState.cs +++ b/source/CPDLCServer/Cpdlc/Connections/ConnectionState.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.Cpdlc.Connections; public enum ConnectionState { diff --git a/source/CPDLCServer/Model/DataAuthorityState.cs b/source/CPDLCServer/Cpdlc/Connections/DataAuthorityState.cs similarity index 66% rename from source/CPDLCServer/Model/DataAuthorityState.cs rename to source/CPDLCServer/Cpdlc/Connections/DataAuthorityState.cs index 5676dab..5e9fef8 100644 --- a/source/CPDLCServer/Model/DataAuthorityState.cs +++ b/source/CPDLCServer/Cpdlc/Connections/DataAuthorityState.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.Cpdlc.Connections; public enum DataAuthorityState { diff --git a/source/CPDLCServer/Messages/GetConnectedAircraftRequest.cs b/source/CPDLCServer/Cpdlc/Connections/GetConnectedAircraftRequest.cs similarity index 83% rename from source/CPDLCServer/Messages/GetConnectedAircraftRequest.cs rename to source/CPDLCServer/Cpdlc/Connections/GetConnectedAircraftRequest.cs index 78cb56c..36529bf 100644 --- a/source/CPDLCServer/Messages/GetConnectedAircraftRequest.cs +++ b/source/CPDLCServer/Cpdlc/Connections/GetConnectedAircraftRequest.cs @@ -1,7 +1,7 @@ using CPDLCServer.Contracts; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Connections; public record GetConnectedAircraftRequest : IRequest; diff --git a/source/CPDLCServer/Handlers/GetConnectedAircraftRequestHandler.cs b/source/CPDLCServer/Cpdlc/Connections/GetConnectedAircraftRequestHandler.cs similarity index 86% rename from source/CPDLCServer/Handlers/GetConnectedAircraftRequestHandler.cs rename to source/CPDLCServer/Cpdlc/Connections/GetConnectedAircraftRequestHandler.cs index 481a5f9..2cbc945 100644 --- a/source/CPDLCServer/Handlers/GetConnectedAircraftRequestHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/GetConnectedAircraftRequestHandler.cs @@ -1,10 +1,8 @@ +using CPDLCServer.Cpdlc.Dialogues; using CPDLCServer.Contracts; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Connections; public class GetConnectedAircraftRequestHandler(IAircraftRepository aircraftRepository) : IRequestHandler diff --git a/source/CPDLCServer/Persistence/IAircraftRepository.cs b/source/CPDLCServer/Cpdlc/Connections/IAircraftRepository.cs similarity index 76% rename from source/CPDLCServer/Persistence/IAircraftRepository.cs rename to source/CPDLCServer/Cpdlc/Connections/IAircraftRepository.cs index b26c53f..0d2d28f 100644 --- a/source/CPDLCServer/Persistence/IAircraftRepository.cs +++ b/source/CPDLCServer/Cpdlc/Connections/IAircraftRepository.cs @@ -1,6 +1,4 @@ -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; +namespace CPDLCServer.Cpdlc.Connections; public interface IAircraftRepository { @@ -10,4 +8,4 @@ public interface IAircraftRepository Task Remove(AircraftKey aircraftKey, CancellationToken cancellationToken); } -public record AircraftKey(string Callsign, string AcarsClientId); +public record AircraftKey(string Callsign, string AcarsConnectionId); diff --git a/source/CPDLCServer/Messages/LogonCommand.cs b/source/CPDLCServer/Cpdlc/Connections/LogonCommand.cs similarity index 63% rename from source/CPDLCServer/Messages/LogonCommand.cs rename to source/CPDLCServer/Cpdlc/Connections/LogonCommand.cs index d3ea11a..9f68f36 100644 --- a/source/CPDLCServer/Messages/LogonCommand.cs +++ b/source/CPDLCServer/Cpdlc/Connections/LogonCommand.cs @@ -1,7 +1,8 @@ -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Connections; public record LogonCommand( int DownlinkId, @@ -11,4 +12,4 @@ public record LogonCommand( AlertType DownlinkAlertType, string DownlinkContent, DateTimeOffset DownlinkReceived, - string AcarsClientId) : IRequest; + string AcarsConnectionId) : IRequest; diff --git a/source/CPDLCServer/Cpdlc/Connections/LogonCommandHandler.cs b/source/CPDLCServer/Cpdlc/Connections/LogonCommandHandler.cs new file mode 100644 index 0000000..12b7f13 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Connections/LogonCommandHandler.cs @@ -0,0 +1,156 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Infrastructure; +using MediatR; + +namespace CPDLCServer.Cpdlc.Connections; + +public class LogonCommandHandler( + IAcarsConnectionManager acarsConnectionManager, + IAircraftRepository aircraftRepository, + IControllerRepository controllerRepository, + IDialogueRepository dialogueRepository, + IMessageIdProvider messageIdProvider, + IClock clock, + IMediator mediator, + IUplinkTransmitter uplinkTransmitter, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(LogonCommand request, CancellationToken cancellationToken) + { + var acarsConnection = await acarsConnectionManager.GetAcarsConnection(request.AcarsConnectionId, cancellationToken); + + // A new logon replaces the existing connection. + // Hoppie identifies an aircraft only by its callsign, so the new logon can be from a different pilot. + var existingAircraft = await aircraftRepository.Find( + new(request.Callsign, request.AcarsConnectionId), + cancellationToken); + + if (existingAircraft is not null) + { + await ResetConnection(existingAircraft, cancellationToken); + } + + var aircraft = new AircraftConnection( + request.Callsign, + request.AcarsConnectionId, + acarsConnection.StationId, + DataAuthorityState.NextDataAuthority); + + aircraft.RequestLogon(clock.UtcNow()); + + await aircraftRepository.Add( + new(request.Callsign, request.AcarsConnectionId), + aircraft, + cancellationToken); + + // Don't accept the logon if no controllers are connected + var activeControllers = await controllerRepository.All(cancellationToken); + if (activeControllers.Length == 0) + { + logger.Information("New connection request received from {Callsign} on {AcarsConnectionId}, but no ATS is online. Rejecting the request.", request.Callsign, request.AcarsConnectionId); + + await Reply(acarsConnection, request, "LOGON REJECTED. NO ATS AVBL.", cancellationToken); + + await aircraftRepository.Remove( + new AircraftKey(request.Callsign, request.AcarsConnectionId), + cancellationToken); + + return; + } + + logger.Information("New connection request received from {Callsign} on {AcarsConnectionId}. Accepting the request.", request.Callsign, request.AcarsConnectionId); + + // Immediately accept it for now + aircraft.AcceptLogon(clock.UtcNow()); + + await Reply(acarsConnection, request, "LOGON ACCEPTED", cancellationToken); + + await mediator.Publish( + new AircraftConnectionEstablished( + request.AcarsConnectionId, + aircraft.StationId, + request.Callsign, + aircraft.DataAuthorityState), + cancellationToken); + } + + // No response to the messages of the previous connection can arrive, so close its open dialogues + async Task ResetConnection(AircraftConnection existingAircraft, CancellationToken cancellationToken) + { + logger.Information( + "Connection request received from {Callsign} on {AcarsConnectionId}, which is already connected. Resetting the connection.", + existingAircraft.Callsign, + existingAircraft.AcarsConnectionId); + + var openDialogues = await dialogueRepository.FindOpenForAircraft( + existingAircraft.Callsign, + existingAircraft.StationId, + cancellationToken); + + foreach (var dialogue in openDialogues) + { + var messageId = await messageIdProvider.GetNextMessageId( + existingAircraft.AcarsConnectionId, + existingAircraft.Callsign, + cancellationToken); + + dialogue.AbortWithError(messageId, "CPDLC CONNECTION RESET", clock.UtcNow()); + await mediator.Publish(new DialogueChangedNotification(dialogue), cancellationToken); + + logger.Information( + "Closed dialogue {DialogueId} for reset connection with {Callsign}", + dialogue.Id, + existingAircraft.Callsign); + } + + await mediator.Publish( + new AircraftConnectionReset( + existingAircraft.AcarsConnectionId, + existingAircraft.StationId, + existingAircraft.Callsign), + cancellationToken); + } + + async Task Reply( + IAcarsConnection acarsConnection, + LogonCommand request, + string content, + CancellationToken cancellationToken) + { + var dialogue = new Dialogue(request.Callsign, acarsConnection.StationId); + dialogue.AddDownlink( + request.DownlinkId, + request.DownlinkMessageReference, + request.Callsign, + request.DownlinkResponseType, + request.DownlinkAlertType, + request.DownlinkContent, + request.DownlinkReceived); + + var messageId = await messageIdProvider.GetNextMessageId( + request.AcarsConnectionId, + request.Callsign, + cancellationToken); + + var uplinkMessage = dialogue.AddUplink( + messageId, + request.DownlinkId, + request.Callsign, + "SYSTEM", + CpdlcUplinkResponseType.NoResponse, + AlertType.None, + content, + clock.UtcNow()); + + await dialogueRepository.Add(dialogue, cancellationToken); + logger.Information("Dialogue {DialogueId} created for logon reply to {Callsign}", dialogue.Id, request.Callsign); + + await mediator.Publish(new DialogueChangedNotification(dialogue), cancellationToken); + + uplinkTransmitter.TransmitAfterCommit(acarsConnection, uplinkMessage); + } +} diff --git a/source/CPDLCServer/Services/LostConnectionService.cs b/source/CPDLCServer/Cpdlc/Connections/LostConnectionService.cs similarity index 59% rename from source/CPDLCServer/Services/LostConnectionService.cs rename to source/CPDLCServer/Cpdlc/Connections/LostConnectionService.cs index a03f95d..2b531b7 100644 --- a/source/CPDLCServer/Services/LostConnectionService.cs +++ b/source/CPDLCServer/Cpdlc/Connections/LostConnectionService.cs @@ -1,41 +1,16 @@ -using CPDLCServer.Messages; -using MediatR; +using CPDLCServer.Infrastructure; -namespace CPDLCServer.Services; +namespace CPDLCServer.Cpdlc.Connections; -public class LostConnectionService : IHostedService, IDisposable +public class LostConnectionService(IUnitOfWorkMediator mediator, ILogger logger) : IHostedService, IDisposable { readonly TimeSpan _checkInterval = TimeSpan.FromMinutes(1); - readonly TimeSpan _connectionTimeout; - readonly IMediator _mediator; - readonly ILogger _logger; + readonly ILogger _logger = logger.ForContext(); CancellationTokenSource? _cancellationTokenSource; Task? _task; - public LostConnectionService(IConfiguration configuration, IMediator mediator, ILogger logger) - { - _mediator = mediator; - _logger = logger.ForContext(); - - // The connectivity check updates the last seen time of each aircraft at this interval. - var refreshIntervalMinutes = configuration.GetValue("ConnectivityCheckIntervalMinutes", 15); - var refreshInterval = TimeSpan.FromMinutes(refreshIntervalMinutes); - - // The default timeout lets the connection continue if one refresh fails. - _connectionTimeout = configuration.GetValue("AircraftConnectionTimeout", refreshInterval * 3); - - // If one refresh fails, the time between two updates is two refresh intervals. - if (_connectionTimeout <= refreshInterval * 2) - { - _logger.Warning( - "AircraftConnectionTimeout ({ConnectionTimeout}) is not more than two times the connectivity check interval ({RefreshInterval}). One failed refresh will cause connections to time out.", - _connectionTimeout, - refreshInterval); - } - } - public Task StartAsync(CancellationToken cancellationToken) { if (_cancellationTokenSource is not null || _task is not null) @@ -74,9 +49,7 @@ async Task DoWork(CancellationToken stoppingToken) using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); timeoutCts.CancelAfter(TimeSpan.FromMinutes(1)); - await _mediator.Send( - new CheckLostAircraftConnectionsRequest(_connectionTimeout), - timeoutCts.Token); + await mediator.Send(new CheckLostAircraftConnectionsRequest(), timeoutCts.Token); await Task.Delay(_checkInterval, stoppingToken); } diff --git a/source/CPDLCServer/Services/NdaUplinkService.cs b/source/CPDLCServer/Cpdlc/Connections/NdaUplinkService.cs similarity index 90% rename from source/CPDLCServer/Services/NdaUplinkService.cs rename to source/CPDLCServer/Cpdlc/Connections/NdaUplinkService.cs index 1da6785..e672222 100644 --- a/source/CPDLCServer/Services/NdaUplinkService.cs +++ b/source/CPDLCServer/Cpdlc/Connections/NdaUplinkService.cs @@ -1,14 +1,13 @@ -using CPDLCServer.Exceptions; -using CPDLCServer.Messages; -using MediatR; +using CPDLCServer.AcarsConnections; +using CPDLCServer.Infrastructure; -namespace CPDLCServer.Services; +namespace CPDLCServer.Cpdlc.Connections; /// /// Periodically dispatches to ensure handoff messages are sent to aircraft /// within the configured lead time before their expected transfer. /// -public class NdaUplinkService(IMediator mediator, ILogger logger) : IHostedService, IDisposable +public class NdaUplinkService(IUnitOfWorkMediator mediator, ILogger logger) : IHostedService, IDisposable { readonly TimeSpan _interval = TimeSpan.FromMinutes(1); readonly TimeSpan _errorInterval = TimeSpan.FromSeconds(5); @@ -64,7 +63,7 @@ async Task DoWork(CancellationToken cancellationToken) } catch (ConfigurationNotFoundException) { - // Race condition: Client manager probably hasn't created the client yet + // Race condition: the connection manager probably has not created the connection yet await Task.Delay(_errorInterval, cancellationToken); } catch (Exception exception) diff --git a/source/CPDLCServer/Messages/SendConnectionRequestCommand.cs b/source/CPDLCServer/Cpdlc/Connections/SendConnectionRequestCommand.cs similarity index 74% rename from source/CPDLCServer/Messages/SendConnectionRequestCommand.cs rename to source/CPDLCServer/Cpdlc/Connections/SendConnectionRequestCommand.cs index 17e9a06..456dde3 100644 --- a/source/CPDLCServer/Messages/SendConnectionRequestCommand.cs +++ b/source/CPDLCServer/Cpdlc/Connections/SendConnectionRequestCommand.cs @@ -1,6 +1,6 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Connections; public record SendConnectionRequestCommand( string Callsign, diff --git a/source/CPDLCServer/Cpdlc/Connections/SendConnectionRequestCommandHandler.cs b/source/CPDLCServer/Cpdlc/Connections/SendConnectionRequestCommandHandler.cs new file mode 100644 index 0000000..b833593 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Connections/SendConnectionRequestCommandHandler.cs @@ -0,0 +1,49 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Infrastructure; +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.Cpdlc.Connections; + +public class SendConnectionRequestCommandHandler( + IAcarsConnectionManager acarsConnectionManager, + IMessageIdProvider messageIdProvider, + IClock clock, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(SendConnectionRequestCommand request, CancellationToken cancellationToken) + { + var acarsConnectionId = await acarsConnectionManager.FindAcarsConnectionId(request.StationId, cancellationToken); + if (acarsConnectionId is null) + throw new Exception($"No ACARS connection is configured for {request.StationId}"); + + var acarsConnection = await acarsConnectionManager.GetAcarsConnection(acarsConnectionId, cancellationToken); + + var messageId = await messageIdProvider.GetNextMessageId( + acarsConnectionId, + request.Callsign, + cancellationToken); + + // This is a system message. It does not start a dialogue. + var uplinkMessage = new UplinkMessage( + Guid.Empty, + messageId, + null, + request.Callsign, + "SYSTEM", + CpdlcUplinkResponseType.NoResponse, + AlertType.None, + $"CONNECTION REQUESTED @{request.StationId}@", + clock.UtcNow()); + + unitOfWork.AfterCommit(async ct => + { + await acarsConnection.Send(uplinkMessage, ct); + logger.Information("Sent connection request for {StationId} to {Callsign}", request.StationId, request.Callsign); + }); + } +} diff --git a/source/CPDLCServer/Handlers/TerminateConnectionHandler.cs b/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionHandler.cs similarity index 73% rename from source/CPDLCServer/Handlers/TerminateConnectionHandler.cs rename to source/CPDLCServer/Cpdlc/Connections/TerminateConnectionHandler.cs index 11dfb03..2a7c966 100644 --- a/source/CPDLCServer/Handlers/TerminateConnectionHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionHandler.cs @@ -1,13 +1,14 @@ +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Connections; public class TerminateConnectionHandler( IAircraftRepository aircraftRepository, IDialogueRepository dialogueRepository, + IMessageIdProvider messageIdProvider, IClock clock, IMediator mediator, ILogger logger) @@ -15,9 +16,9 @@ public class TerminateConnectionHandler( { public async Task Handle(TerminateConnectionRequest request, CancellationToken cancellationToken) { - logger.Information("Connection between {StationId} and {Callsign} terminating", request.AcarsClientId, request.Callsign); + logger.Information("Connection between {StationId} and {Callsign} terminating", request.AcarsConnectionId, request.Callsign); - var aircraftKey = new AircraftKey(request.Callsign, request.AcarsClientId); + var aircraftKey = new AircraftKey(request.Callsign, request.AcarsConnectionId); // Get the aircraft connection before removing it so we can get the StationId var aircraftConnection = await aircraftRepository.Find(aircraftKey, cancellationToken); @@ -29,10 +30,10 @@ public async Task Handle(TerminateConnectionRequest request, CancellationToken c return; // No response can arrive after the connection ends, so close the open dialogues - var allDialogues = await dialogueRepository.All(cancellationToken); - var openDialogues = allDialogues - .Where(d => d.AircraftCallsign == request.Callsign && !d.IsClosed && !d.IsArchived) - .ToArray(); + var openDialogues = await dialogueRepository.FindOpenForAircraft( + request.Callsign, + aircraftConnection.StationId, + cancellationToken); foreach (var dialogue in openDialogues) { @@ -45,9 +46,11 @@ public async Task Handle(TerminateConnectionRequest request, CancellationToken c request.Callsign); } + await messageIdProvider.Remove(request.AcarsConnectionId, request.Callsign, cancellationToken); + await mediator.Publish( new AircraftConnectionTerminated( - request.AcarsClientId, + request.AcarsConnectionId, aircraftConnection.StationId, request.Callsign), cancellationToken); diff --git a/source/CPDLCServer/Handlers/TerminateConnectionOnDialogueClosedHandler.cs b/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandler.cs similarity index 80% rename from source/CPDLCServer/Handlers/TerminateConnectionOnDialogueClosedHandler.cs rename to source/CPDLCServer/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandler.cs index 6ed7ebe..bf17135 100644 --- a/source/CPDLCServer/Handlers/TerminateConnectionOnDialogueClosedHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandler.cs @@ -1,9 +1,8 @@ -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Uplinks; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Connections; public class TerminateConnectionOnDialogueClosedHandler( IAircraftRepository aircraftRepository, @@ -20,15 +19,16 @@ public async Task Handle(DialogueChangedNotification notification, CancellationT // Check if any uplink in the dialogue contains END SERVICE var hasEndService = notification.Dialogue.Messages .OfType() - .Any(m => ControlMessages.IsEndServiceUplink(m)); + .Any(ControlMessages.IsEndServiceUplink); if (!hasEndService) return; - // Find the aircraft connection (CDA state) + // Find the aircraft connection (CDA state) with the ATSU of the dialogue var aircraftConnections = await aircraftRepository.All(cancellationToken); var aircraftConnection = aircraftConnections.FirstOrDefault(c => c.Callsign == notification.Dialogue.AircraftCallsign && + c.StationId == notification.Dialogue.StationId && c.DataAuthorityState == DataAuthorityState.CurrentDataAuthority); if (aircraftConnection is null) @@ -46,7 +46,7 @@ public async Task Handle(DialogueChangedNotification notification, CancellationT await mediator.Send( new TerminateConnectionRequest( aircraftConnection.Callsign, - aircraftConnection.AcarsClientId), + aircraftConnection.AcarsConnectionId), cancellationToken); } } diff --git a/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionRequest.cs b/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionRequest.cs new file mode 100644 index 0000000..f5fd2b6 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionRequest.cs @@ -0,0 +1,7 @@ +using MediatR; + +namespace CPDLCServer.Cpdlc.Connections; + +public record TerminateConnectionRequest( + string Callsign, + string AcarsConnectionId) : IRequest; diff --git a/source/CPDLCServer/Messages/TransmitPendingNdaUplinksCommand.cs b/source/CPDLCServer/Cpdlc/Connections/TransmitPendingNdaUplinksCommand.cs similarity index 64% rename from source/CPDLCServer/Messages/TransmitPendingNdaUplinksCommand.cs rename to source/CPDLCServer/Cpdlc/Connections/TransmitPendingNdaUplinksCommand.cs index a5ee6c5..d456bfd 100644 --- a/source/CPDLCServer/Messages/TransmitPendingNdaUplinksCommand.cs +++ b/source/CPDLCServer/Cpdlc/Connections/TransmitPendingNdaUplinksCommand.cs @@ -1,5 +1,5 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Connections; public record TransmitPendingNdaUplinksCommand : IRequest; diff --git a/source/CPDLCServer/Handlers/TransmitPendingNdaUplinksCommandHandler.cs b/source/CPDLCServer/Cpdlc/Connections/TransmitPendingNdaUplinksCommandHandler.cs similarity index 86% rename from source/CPDLCServer/Handlers/TransmitPendingNdaUplinksCommandHandler.cs rename to source/CPDLCServer/Cpdlc/Connections/TransmitPendingNdaUplinksCommandHandler.cs index 7dc8e2c..4faa248 100644 --- a/source/CPDLCServer/Handlers/TransmitPendingNdaUplinksCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/TransmitPendingNdaUplinksCommandHandler.cs @@ -1,10 +1,10 @@ +using CPDLCServer.AcarsConnections.Stations; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.Settings; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Connections; public class TransmitPendingNdaUplinksCommandHandler( IAircraftRepository aircraftRepository, @@ -12,14 +12,14 @@ public class TransmitPendingNdaUplinksCommandHandler( IMediator mediator, IClock clock, ILogger logger, - IConfiguration configuration) + IServerSettingsProvider settingsProvider) : IRequestHandler { - readonly TimeSpan _notificationLeadTime = TimeSpan.FromMinutes( - configuration["Handoff:NotificationLeadTime"] is { } value && int.TryParse(value, out var minutes) ? minutes : 20); - public async Task Handle(TransmitPendingNdaUplinksCommand request, CancellationToken cancellationToken) { + var settings = await settingsProvider.Load(cancellationToken); + var notificationLeadTime = TimeSpan.FromMinutes(settings.HandoffNotificationLeadTimeMinutes); + var trackedConnections = await aircraftRepository.All(cancellationToken); var onlineCallsigns = await acarsConnectedCallsignsRepository.All(cancellationToken); @@ -37,7 +37,7 @@ public async Task Handle(TransmitPendingNdaUplinksCommand request, CancellationT continue; } - var transmitTime = aircraftConnection.ExpectedTransferTime.Value.Subtract(_notificationLeadTime); + var transmitTime = aircraftConnection.ExpectedTransferTime.Value.Subtract(notificationLeadTime); if (clock.UtcNow() <= transmitTime) { logger.Debug("{Callsign}: transmit time {TransmitTime} not reached, skipping", aircraftConnection.Callsign, transmitTime); diff --git a/source/CPDLCServer/Messages/UpdateNextDataAuthorityCommand.cs b/source/CPDLCServer/Cpdlc/Connections/UpdateNextDataAuthorityCommand.cs similarity index 82% rename from source/CPDLCServer/Messages/UpdateNextDataAuthorityCommand.cs rename to source/CPDLCServer/Cpdlc/Connections/UpdateNextDataAuthorityCommand.cs index 7b3f86e..2ac680a 100644 --- a/source/CPDLCServer/Messages/UpdateNextDataAuthorityCommand.cs +++ b/source/CPDLCServer/Cpdlc/Connections/UpdateNextDataAuthorityCommand.cs @@ -1,6 +1,6 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Connections; public record UpdateNextDataAuthorityCommand( string StationId, diff --git a/source/CPDLCServer/Handlers/UpdateNextDataAuthorityCommandHandler.cs b/source/CPDLCServer/Cpdlc/Connections/UpdateNextDataAuthorityCommandHandler.cs similarity index 94% rename from source/CPDLCServer/Handlers/UpdateNextDataAuthorityCommandHandler.cs rename to source/CPDLCServer/Cpdlc/Connections/UpdateNextDataAuthorityCommandHandler.cs index 4add916..0afd28a 100644 --- a/source/CPDLCServer/Handlers/UpdateNextDataAuthorityCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/UpdateNextDataAuthorityCommandHandler.cs @@ -1,8 +1,6 @@ -using CPDLCServer.Messages; -using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Connections; public class UpdateNextDataAuthorityCommandHandler( IAircraftRepository aircraftRepository, diff --git a/source/CPDLCServer/Cpdlc/CpdlcServiceCollectionExtensions.cs b/source/CPDLCServer/Cpdlc/CpdlcServiceCollectionExtensions.cs new file mode 100644 index 0000000..cc30575 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/CpdlcServiceCollectionExtensions.cs @@ -0,0 +1,26 @@ +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Motd; +using CPDLCServer.Cpdlc.Uplinks; + +namespace CPDLCServer.Cpdlc; + +public static class CpdlcServiceCollectionExtensions +{ + public static IServiceCollection AddCpdlc(this IServiceCollection services) + { + services.AddScoped(); + services.AddHostedService(); + services.AddHostedService(); + + services.AddScoped(); + services.AddHostedService(); + + services.AddScoped(); + services.AddScoped(); + + services.AddSingleton(); + + return services; + } +} diff --git a/source/CPDLCServer/Model/AlertType.cs b/source/CPDLCServer/Cpdlc/Dialogues/AlertType.cs similarity index 62% rename from source/CPDLCServer/Model/AlertType.cs rename to source/CPDLCServer/Cpdlc/Dialogues/AlertType.cs index a944b0f..5b3fd71 100644 --- a/source/CPDLCServer/Model/AlertType.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/AlertType.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.Cpdlc.Dialogues; public enum AlertType { diff --git a/source/CPDLCServer/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequest.cs b/source/CPDLCServer/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequest.cs new file mode 100644 index 0000000..1d875b2 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequest.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public record ArchiveCompletedDialoguesRequest : IRequest; diff --git a/source/CPDLCServer/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequestHandler.cs b/source/CPDLCServer/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequestHandler.cs new file mode 100644 index 0000000..09ab081 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequestHandler.cs @@ -0,0 +1,46 @@ +using CPDLCServer.Infrastructure; +using MediatR; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public class ArchiveCompletedDialoguesRequestHandler( + IDialogueRepository dialogueRepository, + IClock clock, + IPublisher publisher, + ILogger logger) + : IRequestHandler +{ + readonly TimeSpan _archiveDelay = TimeSpan.FromSeconds(10); + + public async Task Handle(ArchiveCompletedDialoguesRequest request, CancellationToken cancellationToken) + { + var now = clock.UtcNow(); + var dialogues = await dialogueRepository.FindClosedAndNotArchived(cancellationToken); + + logger.Verbose("Checking for completed dialogues to archive"); + + foreach (var dialogue in dialogues) + { + // Ensure all messages are acknowledged before archiving + if (!dialogue.Messages.All(m => m.IsAcknowledged)) + continue; + + // Find the last acknowledged time across all messages + var lastAckTime = dialogue.Messages.Max(m => m.Acknowledged); + + // Take the later of the last acknowledgement time or dialogue closed time + var latest = lastAckTime.Value > dialogue.Closed + ? lastAckTime.Value + : dialogue.Closed; + + var archiveTime = latest.Value.Add(_archiveDelay); + if (now < archiveTime) + continue; + + logger.Verbose("Archiving dialogue for {Callsign}", dialogue.AircraftCallsign); + dialogue.Archive(now); + + await publisher.Publish(new DialogueChangedNotification(dialogue), cancellationToken); + } + } +} diff --git a/source/CPDLCServer/Messages/ArchiveDialogueCommand.cs b/source/CPDLCServer/Cpdlc/Dialogues/ArchiveDialogueCommand.cs similarity index 68% rename from source/CPDLCServer/Messages/ArchiveDialogueCommand.cs rename to source/CPDLCServer/Cpdlc/Dialogues/ArchiveDialogueCommand.cs index cdd46b4..687f5aa 100644 --- a/source/CPDLCServer/Messages/ArchiveDialogueCommand.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/ArchiveDialogueCommand.cs @@ -1,5 +1,5 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Dialogues; public record ArchiveDialogueCommand(Guid DialogueId) : IRequest; diff --git a/source/CPDLCServer/Handlers/ArchiveDialogueCommandHandler.cs b/source/CPDLCServer/Cpdlc/Dialogues/ArchiveDialogueCommandHandler.cs similarity index 91% rename from source/CPDLCServer/Handlers/ArchiveDialogueCommandHandler.cs rename to source/CPDLCServer/Cpdlc/Dialogues/ArchiveDialogueCommandHandler.cs index f644a87..2ff6213 100644 --- a/source/CPDLCServer/Handlers/ArchiveDialogueCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/ArchiveDialogueCommandHandler.cs @@ -1,51 +1,48 @@ -using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Persistence; -using MediatR; - -namespace CPDLCServer.Handlers; - -public class ArchiveDialogueCommandHandler( - IDialogueRepository dialogueRepository, - IClock clock, - IPublisher publisher, - ILogger logger) - : IRequestHandler -{ - public async Task Handle(ArchiveDialogueCommand request, CancellationToken cancellationToken) - { - var dialogue = await dialogueRepository.FindById(request.DialogueId, cancellationToken); - - if (dialogue is null) - { - logger.Warning("Dialogue not found for archival: {DialogueId}", request.DialogueId); - return; // Silently succeed - already archived or doesn't exist - } - - if (dialogue.IsArchived) - { - logger.Verbose("Dialogue {DialogueId} is already archived", request.DialogueId); - return; // Idempotent - already archived - } - - if (!dialogue.IsClosed) - { - logger.Warning( - "Attempted to archive an open dialogue {DialogueId} for {AircraftCallsign}", - request.DialogueId, - dialogue.AircraftCallsign); - return; - } - - dialogue.Archive(clock.UtcNow()); - - logger.Information( - "Manually archived dialogue {DialogueId} for {AircraftCallsign}", - request.DialogueId, - dialogue.AircraftCallsign); - - await publisher.Publish( - new DialogueChangedNotification(dialogue), - cancellationToken); - } -} +using CPDLCServer.Infrastructure; +using MediatR; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public class ArchiveDialogueCommandHandler( + IDialogueRepository dialogueRepository, + IClock clock, + IPublisher publisher, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(ArchiveDialogueCommand request, CancellationToken cancellationToken) + { + var dialogue = await dialogueRepository.FindById(request.DialogueId, cancellationToken); + if (dialogue is null) + { + logger.Warning("Dialogue not found for archival: {DialogueId}", request.DialogueId); + return; // Silently succeed - already archived or doesn't exist + } + + if (dialogue.IsArchived) + { + logger.Verbose("Dialogue {DialogueId} is already archived", request.DialogueId); + return; // Idempotent - already archived + } + + if (!dialogue.IsClosed) + { + logger.Warning( + "Attempted to archive an open dialogue {DialogueId} for {AircraftCallsign}", + request.DialogueId, + dialogue.AircraftCallsign); + return; + } + + dialogue.Archive(clock.UtcNow()); + + logger.Information( + "Manually archived dialogue {DialogueId} for {AircraftCallsign}", + request.DialogueId, + dialogue.AircraftCallsign); + + await publisher.Publish( + new DialogueChangedNotification(dialogue), + cancellationToken); + } +} diff --git a/source/CPDLCServer/Cpdlc/Dialogues/CheckMessageTimeoutsRequest.cs b/source/CPDLCServer/Cpdlc/Dialogues/CheckMessageTimeoutsRequest.cs new file mode 100644 index 0000000..46961e5 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/CheckMessageTimeoutsRequest.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public record CheckMessageTimeoutsRequest : IRequest; diff --git a/source/CPDLCServer/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandler.cs b/source/CPDLCServer/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandler.cs new file mode 100644 index 0000000..40f917b --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandler.cs @@ -0,0 +1,96 @@ +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Infrastructure; +using MediatR; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public class CheckMessageTimeoutsRequestHandler( + IDialogueRepository dialogueRepository, + IClock clock, + IPublisher publisher, + ILogger logger) + : IRequestHandler +{ + readonly TimeSpan _pilotLateTimeout = TimeSpan.FromMinutes(2); + readonly TimeSpan _controllerLateTimeout = TimeSpan.FromMinutes(2); + + public async Task Handle(CheckMessageTimeoutsRequest request, CancellationToken cancellationToken) + { + // TODO: Time out entire dialogues when they take too long + // TODO: Verify if this is supposed to apply to message closures or acknowledgements. + + var now = clock.UtcNow(); + var dialogues = await dialogueRepository.FindOpen(cancellationToken); + + logger.Verbose("Checking for timeouts in {DialogueCount} dialogues", dialogues.Length); + + foreach (var dialogue in dialogues) + { + var anyChanges = false; + foreach (var message in dialogue.Messages) + { + switch (message) + { + case UplinkMessage uplink: + if (CheckUplinkTimeout(uplink, now)) + { + anyChanges = true; + } + break; + + case DownlinkMessage downlink: + if (CheckDownlinkTimeout(downlink, now)) + { + anyChanges = true; + } + break; + } + } + + if (anyChanges) + { + await publisher.Publish(new DialogueChangedNotification(dialogue), cancellationToken); + } + } + } + + bool CheckUplinkTimeout(UplinkMessage uplink, DateTimeOffset now) + { + // Skip if already closed, in timeout/failed state, or doesn't require response + if (uplink.IsClosed || + uplink.IsPilotLate || + uplink.DidTransmissionFail || + uplink.ResponseType == CpdlcUplinkResponseType.NoResponse) + return false; + + // Check if timeout has been exceeded + var timeSinceSent = now - uplink.Sent; + if (timeSinceSent < _pilotLateTimeout) + return false; + + logger.Verbose("Uplink message {UplinkId} marked as pilot late (time since sent: {TimeSinceSent}s)", + uplink.MessageId, timeSinceSent.TotalSeconds); + uplink.IsPilotLate = true; + return true; + } + + bool CheckDownlinkTimeout(DownlinkMessage downlink, DateTimeOffset now) + { + // Skip if already closed, in timeout state, or doesn't require response + if (downlink.IsClosed || + downlink.IsControllerLate || + downlink.ResponseType == CpdlcDownlinkResponseType.NoResponse) + return false; + + // Check if timeout has been exceeded + var timeSinceReceived = now - downlink.Received; + if (timeSinceReceived < _controllerLateTimeout) + return false; + + logger.Verbose("Downlink message {DownlinkId} marked as controller late (time since received: {TimeSinceReceived}s)", + downlink.MessageId, timeSinceReceived.TotalSeconds); + downlink.IsControllerLate = true; + return true; + } +} diff --git a/source/CPDLCServer/Model/ControlMessages.cs b/source/CPDLCServer/Cpdlc/Dialogues/ControlMessages.cs similarity index 59% rename from source/CPDLCServer/Model/ControlMessages.cs rename to source/CPDLCServer/Cpdlc/Dialogues/ControlMessages.cs index 9b97271..f4f083c 100644 --- a/source/CPDLCServer/Model/ControlMessages.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/ControlMessages.cs @@ -1,15 +1,19 @@ -namespace CPDLCServer.Model; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +namespace CPDLCServer.Cpdlc.Dialogues; public static class ControlMessages { public static bool IsLogonRequest(ReceivedDownlink downlink) { - return downlink.Content.Contains("REQUEST LOGON"); + return downlink.Content.Contains("REQUEST LOGON") || + downlink.Content.Contains("REQUEST LOG ON"); } public static bool IsLogoffNotice(ReceivedDownlink downlink) { - return downlink.Content.Contains("LOGOFF"); + return downlink.Content.Contains("LOGOFF") || + downlink.Content.Contains("LOG OFF"); } public static bool IsEndServiceUplink(UplinkMessage uplink) diff --git a/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessage.cs b/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessage.cs new file mode 100644 index 0000000..8ae1b59 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessage.cs @@ -0,0 +1,32 @@ +using System.Diagnostics.CodeAnalysis; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public abstract class CpdlcMessage( + Guid dialogueId, + int messageId, + int? messageReference, + AlertType alertType) +{ + public Guid DialogueId { get; } = dialogueId; + public int MessageId { get; } = messageId; + public int? MessageReference { get; } = messageReference; + public AlertType AlertType { get; } = alertType; + + public abstract DateTimeOffset Time { get; } + + // The place of the message in its dialogue. The dialogue sets it. + public int Position { get; internal set; } + + public DateTimeOffset? Closed { get; protected set; } + + [MemberNotNullWhen(true, nameof(Closed))] + public bool IsClosed => Closed is not null; + + public DateTimeOffset? Acknowledged { get; protected set; } + + [MemberNotNullWhen(true, nameof(Acknowledged))] + public bool IsAcknowledged => Acknowledged is not null; + + public abstract void Close(DateTimeOffset time); +} diff --git a/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessageConfiguration.cs b/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessageConfiguration.cs new file mode 100644 index 0000000..665bb3f --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessageConfiguration.cs @@ -0,0 +1,61 @@ +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.Cpdlc.Dialogues; + +// Uplink and downlink messages are kept in one table +public class CpdlcMessageConfiguration : IEntityTypeConfiguration +{ + // The message ID comes from the aircraft or the server, so it is not unique. The key is a shadow property. + public const string IdProperty = "Id"; + + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("CpdlcMessages"); + + builder.Property(IdProperty); + builder.HasKey(IdProperty); + + builder.HasDiscriminator("Direction") + .HasValue("Uplink") + .HasValue("Downlink"); + + builder.Property(m => m.DialogueId); + builder.Property(m => m.MessageId); + builder.Property(m => m.MessageReference); + builder.Property(m => m.Position); + builder.Property(m => m.AlertType); + builder.Property(m => m.Closed); + builder.Property(m => m.Acknowledged); + builder.Ignore(m => m.Time); + } +} + +public class UplinkMessageConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.Property(m => m.Recipient); + builder.Property(m => m.SenderCallsign); + builder.Property(m => m.ResponseType).HasColumnName("UplinkResponseType"); + builder.Property(m => m.Content).HasColumnName("Content"); + builder.Property(m => m.Sent); + builder.Property(m => m.ClosedManually); + builder.Property(m => m.IsPilotLate); + builder.Property(m => m.DidTransmissionFail); + } +} + +public class DownlinkMessageConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.Property(m => m.Sender); + builder.Property(m => m.ResponseType).HasColumnName("DownlinkResponseType"); + builder.Property(m => m.Content).HasColumnName("Content"); + builder.Property(m => m.Received); + builder.Property(m => m.IsControllerLate); + } +} diff --git a/source/CPDLCServer/Model/Dialogue.cs b/source/CPDLCServer/Cpdlc/Dialogues/Dialogue.cs similarity index 73% rename from source/CPDLCServer/Model/Dialogue.cs rename to source/CPDLCServer/Cpdlc/Dialogues/Dialogue.cs index 5633c96..6dddc32 100644 --- a/source/CPDLCServer/Model/Dialogue.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/Dialogue.cs @@ -1,7 +1,9 @@ using System.Diagnostics.CodeAnalysis; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; using Serilog; -namespace CPDLCServer.Model; +namespace CPDLCServer.Cpdlc.Dialogues; // Messages that are related (e.g. a CPDLC downlink request, the corresponding CPDLC uplink clearance and the subsequent // pilot response) constitute a CPDLC dialogue. @@ -16,17 +18,21 @@ namespace CPDLCServer.Model; public class Dialogue { - readonly List _messages = []; + readonly List _messages = []; - public Dialogue(string aircraftCallsign) + public Dialogue(string aircraftCallsign, string stationId) { AircraftCallsign = aircraftCallsign; + StationId = stationId; } public Guid Id { get; } = Guid.NewGuid(); public string AircraftCallsign { get; } - public IReadOnlyList Messages => _messages.AsReadOnly(); + + // The ATSU of the dialogue + public string StationId { get; } + public IReadOnlyList Messages => _messages.AsReadOnly(); public DateTimeOffset Opened { get; private set; } public DateTimeOffset? Closed { get; private set; } @@ -67,17 +73,45 @@ public DownlinkMessage AddDownlink( return message; } - void AddMessage(ICpdlcMessage message) + void AddMessage(CpdlcMessage message) { if (_messages.Count == 0) Opened = message.Time; - _messages.Add(message); + Insert(message); // Apply closure rules then check if dialogue closes ProcessMessage(message); } + // The messages are in the order of their times. A message always comes after the message that its message + // reference number (MRN) refers to, also when its time is earlier. + void Insert(CpdlcMessage message) + { + var index = _messages.FindLastIndex(m => m.Time <= message.Time) + 1; + + var referencedMessage = FindReferencedMessage(message); + if (referencedMessage is not null) + index = Math.Max(index, _messages.IndexOf(referencedMessage) + 1); + + _messages.Insert(index, message); + + for (var position = 0; position < _messages.Count; position++) + _messages[position].Position = position; + } + + CpdlcMessage? FindReferencedMessage(CpdlcMessage message) + { + return message switch + { + UplinkMessage { MessageReference: { } reference } => + _messages.OfType().FirstOrDefault(d => d.MessageId == reference), + DownlinkMessage { MessageReference: { } reference } => + _messages.OfType().FirstOrDefault(u => u.MessageId == reference), + _ => null + }; + } + public void Archive(DateTimeOffset now) { foreach (var downlink in _messages.OfType().Where(d => !d.IsAcknowledged)) @@ -99,6 +133,24 @@ public void Abort(DateTimeOffset now) TryClose(now); } + // Adds an error message from the aircraft, then closes all open messages, because no response can arrive. + // The error message refers to the first open message. + public void AbortWithError(int messageId, string content, DateTimeOffset now) + { + var openMessage = _messages.FirstOrDefault(m => !m.IsClosed); + + AddDownlink( + messageId, + openMessage?.MessageId, + AircraftCallsign, + CpdlcDownlinkResponseType.NoResponse, + AlertType.Medium, + content, + now); + + Abort(now); + } + public void AcknowledgeDownlink(int downlinkMessageId, DateTimeOffset now) { var downlink = _messages.OfType() @@ -112,7 +164,18 @@ public void AcknowledgeDownlink(int downlinkMessageId, DateTimeOffset now) downlink.Acknowledge(now); } - void ProcessMessage(ICpdlcMessage message) + public void MarkTransmissionFailed(int uplinkMessageId) + { + var uplink = _messages.OfType() + .FirstOrDefault(ul => ul.MessageId == uplinkMessageId); + + if (uplink is null) + throw new InvalidOperationException($"Uplink message {uplinkMessageId} not found in dialogue"); + + uplink.DidTransmissionFail = true; + } + + void ProcessMessage(CpdlcMessage message) { switch (message) { @@ -173,7 +236,7 @@ public void TryClose(DateTimeOffset now) } } - void TryArchive(ICpdlcMessage message) + void TryArchive(CpdlcMessage message) { // Immediately archive when certain uplinks are added if (message is UplinkMessage uplink && ShouldAutoArchive(uplink)) diff --git a/source/CPDLCServer/Messages/DialogueChangedNotification.cs b/source/CPDLCServer/Cpdlc/Dialogues/DialogueChangedNotification.cs similarity index 62% rename from source/CPDLCServer/Messages/DialogueChangedNotification.cs rename to source/CPDLCServer/Cpdlc/Dialogues/DialogueChangedNotification.cs index 992833d..1ae1ad1 100644 --- a/source/CPDLCServer/Messages/DialogueChangedNotification.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/DialogueChangedNotification.cs @@ -1,6 +1,5 @@ -using CPDLCServer.Model; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Dialogues; public record DialogueChangedNotification(Dialogue Dialogue) : INotification; \ No newline at end of file diff --git a/source/CPDLCServer/Handlers/DialogueChangedNotificationHandler.cs b/source/CPDLCServer/Cpdlc/Dialogues/DialogueChangedNotificationHandler.cs similarity index 90% rename from source/CPDLCServer/Handlers/DialogueChangedNotificationHandler.cs rename to source/CPDLCServer/Cpdlc/Dialogues/DialogueChangedNotificationHandler.cs index ced4c9d..ded5769 100644 --- a/source/CPDLCServer/Handlers/DialogueChangedNotificationHandler.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/DialogueChangedNotificationHandler.cs @@ -1,50 +1,50 @@ -using CPDLCServer.Hubs; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using MediatR; -using Microsoft.AspNetCore.SignalR; - -namespace CPDLCServer.Handlers; - -public class DialogueChangedNotificationHandler( - IControllerRepository controllerRepository, - IHubContext hubContext, - ILogger logger) - : INotificationHandler -{ - public async Task Handle(DialogueChangedNotification notification, CancellationToken cancellationToken) - { - var dialogue = notification.Dialogue; - - logger.Verbose( - "Dialogue {DialogueId} changed for {Callsign} - Closed: {Closed}, Archived: {Archived}", - dialogue.Id, - dialogue.AircraftCallsign, - dialogue.IsClosed, - dialogue.IsArchived); - - // Find all controllers on the same network and station - var controllers = await controllerRepository.All(cancellationToken); - if (controllers.Length == 0) - { - logger.Verbose( - "No controllers to notify about dialogue change for {Callsign}", - dialogue.AircraftCallsign); - return; - } - - // Convert to DTO and broadcast - var dialogueDto = DialogueConverter.ToDto(dialogue); - - await hubContext.Clients - .Clients(controllers.Select(c => c.ConnectionId)) - .SendAsync("DialogueChanged", dialogueDto, cancellationToken); - - logger.Information( - "Notified {ControllerCount} controller(s) about dialogue {DialogueId} change for {Callsign}", - controllers.Length, - dialogue.Id, - dialogue.AircraftCallsign); - } -} +using CPDLCServer.Controllers; +using CPDLCServer.Persistence; +using CPDLCServer.Web; +using MediatR; +using Microsoft.AspNetCore.SignalR; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public class DialogueChangedNotificationHandler( + IControllerRepository controllerRepository, + IHubContext hubContext, + IUnitOfWork unitOfWork, + ILogger logger) + : INotificationHandler +{ + public async Task Handle(DialogueChangedNotification notification, CancellationToken cancellationToken) + { + var dialogue = notification.Dialogue; + + logger.Verbose( + "Dialogue {DialogueId} changed for {Callsign} - Closed: {Closed}, Archived: {Archived}", + dialogue.Id, + dialogue.AircraftCallsign, + dialogue.IsClosed, + dialogue.IsArchived); + + // Find all controllers on the same network and station + var controllers = await controllerRepository.All(cancellationToken); + if (controllers.Length == 0) + { + logger.Verbose( + "No controllers to notify about dialogue change for {Callsign}", + dialogue.AircraftCallsign); + return; + } + + // Convert to DTO and broadcast + var dialogueDto = DialogueConverter.ToDto(dialogue); + + await hubContext.Clients + .Clients(controllers.Select(c => c.ConnectionId)) + .SendAsync("DialogueChanged", dialogueDto, cancellationToken); + + logger.Information( + "Notified {ControllerCount} controller(s) about dialogue {DialogueId} change for {Callsign}", + controllers.Length, + dialogue.Id, + dialogue.AircraftCallsign); + } +} diff --git a/source/CPDLCServer/Cpdlc/Dialogues/DialogueConfiguration.cs b/source/CPDLCServer/Cpdlc/Dialogues/DialogueConfiguration.cs new file mode 100644 index 0000000..6bccd48 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/DialogueConfiguration.cs @@ -0,0 +1,35 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public class DialogueConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("Dialogues"); + + builder.HasKey(d => d.Id); + builder.Property(d => d.Id).ValueGeneratedNever(); + + builder.Property(d => d.AircraftCallsign); + builder.Property(d => d.StationId); + builder.Property(d => d.Opened); + builder.Property(d => d.Closed); + builder.Property(d => d.Archived); + + builder.HasMany(d => d.Messages) + .WithOne() + .HasForeignKey(m => m.DialogueId) + .OnDelete(DeleteBehavior.Cascade); + + builder.Navigation(d => d.Messages) + .HasField("_messages") + .UsePropertyAccessMode(PropertyAccessMode.Field); + + builder.HasIndex(d => new { d.AircraftCallsign, d.StationId }); + + // The purge finds the old dialogues by the time that they opened + builder.HasIndex(d => d.Opened); + } +} diff --git a/source/CPDLCServer/Model/DialogueConverter.cs b/source/CPDLCServer/Cpdlc/Dialogues/DialogueConverter.cs similarity index 67% rename from source/CPDLCServer/Model/DialogueConverter.cs rename to source/CPDLCServer/Cpdlc/Dialogues/DialogueConverter.cs index e1bac55..cc6b8f2 100644 --- a/source/CPDLCServer/Model/DialogueConverter.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/DialogueConverter.cs @@ -1,6 +1,8 @@ using CPDLCServer.Contracts; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; -namespace CPDLCServer.Model; +namespace CPDLCServer.Cpdlc.Dialogues; public static class DialogueConverter { @@ -15,7 +17,7 @@ public static DialogueDto ToDto(Dialogue dialogue) dialogue.Archived); } - public static CpdlcMessageDto ToMessageDto(ICpdlcMessage message) + public static CpdlcMessageDto ToMessageDto(CpdlcMessage message) { return message switch { @@ -25,24 +27,24 @@ public static CpdlcMessageDto ToMessageDto(ICpdlcMessage message) }; } - public static Contracts.CpdlcUplinkResponseType ToDto(CpdlcUplinkResponseType uplinkResponseType) + public static Contracts.CpdlcUplinkResponseType ToDto(Uplinks.CpdlcUplinkResponseType uplinkResponseType) { return uplinkResponseType switch { - CpdlcUplinkResponseType.NoResponse => Contracts.CpdlcUplinkResponseType.NoResponse, - CpdlcUplinkResponseType.WilcoUnable => Contracts.CpdlcUplinkResponseType.WilcoUnable, - CpdlcUplinkResponseType.AffirmativeNegative => Contracts.CpdlcUplinkResponseType.AffirmativeNegative, - CpdlcUplinkResponseType.Roger => Contracts.CpdlcUplinkResponseType.Roger, + Uplinks.CpdlcUplinkResponseType.NoResponse => Contracts.CpdlcUplinkResponseType.NoResponse, + Uplinks.CpdlcUplinkResponseType.WilcoUnable => Contracts.CpdlcUplinkResponseType.WilcoUnable, + Uplinks.CpdlcUplinkResponseType.AffirmativeNegative => Contracts.CpdlcUplinkResponseType.AffirmativeNegative, + Uplinks.CpdlcUplinkResponseType.Roger => Contracts.CpdlcUplinkResponseType.Roger, _ => throw new ArgumentException($"Unknown uplink response type: {uplinkResponseType}") }; } - public static Contracts.CpdlcDownlinkResponseType ToDto(CpdlcDownlinkResponseType downlinkResponseType) + public static Contracts.CpdlcDownlinkResponseType ToDto(Downlinks.CpdlcDownlinkResponseType downlinkResponseType) { return downlinkResponseType switch { - CpdlcDownlinkResponseType.NoResponse => Contracts.CpdlcDownlinkResponseType.NoResponse, - CpdlcDownlinkResponseType.ResponseRequired => Contracts.CpdlcDownlinkResponseType.ResponseRequired, + Downlinks.CpdlcDownlinkResponseType.NoResponse => Contracts.CpdlcDownlinkResponseType.NoResponse, + Downlinks.CpdlcDownlinkResponseType.ResponseRequired => Contracts.CpdlcDownlinkResponseType.ResponseRequired, _ => throw new ArgumentException($"Unknown downlink response type: {downlinkResponseType}") }; } @@ -76,7 +78,7 @@ public static UplinkMessageDto ToDto(UplinkMessage uplink) Content = uplink.Content, Sent = uplink.Sent, IsPilotLate = uplink.IsPilotLate, - IsTransmissionFailed = uplink.IsTransmissionFailed + IsTransmissionFailed = uplink.DidTransmissionFail }; } @@ -98,12 +100,12 @@ public static DownlinkMessageDto ToDto(DownlinkMessage downlink) }; } - public static Contracts.DataAuthorityState ToDto(DataAuthorityState dataAuthorityState) + public static Contracts.DataAuthorityState ToDto(Connections.DataAuthorityState dataAuthorityState) { return dataAuthorityState switch { - DataAuthorityState.NextDataAuthority => Contracts.DataAuthorityState.NextDataAuthority, - DataAuthorityState.CurrentDataAuthority => Contracts.DataAuthorityState.CurrentDataAuthority, + Connections.DataAuthorityState.NextDataAuthority => Contracts.DataAuthorityState.NextDataAuthority, + Connections.DataAuthorityState.CurrentDataAuthority => Contracts.DataAuthorityState.CurrentDataAuthority, _ => throw new ArgumentException($"Unknown data authority state: {dataAuthorityState}") }; } diff --git a/source/CPDLCServer/Cpdlc/Dialogues/DialogueRepository.cs b/source/CPDLCServer/Cpdlc/Dialogues/DialogueRepository.cs new file mode 100644 index 0000000..90fa38a --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/DialogueRepository.cs @@ -0,0 +1,112 @@ +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Cpdlc.Dialogues; + +// The changes are saved when the unit of work is committed. +// Queries load the rows into the context, then read the local entities, so that the results include entities that are +// added in the unit of work and exclude entities that are removed in it. +public class DialogueRepository(CpdlcDbContext dbContext) : IDialogueRepository +{ + public Task Add(Dialogue dialogue, CancellationToken cancellationToken) + { + dbContext.Dialogues.Add(dialogue); + return Task.CompletedTask; + } + + public async Task FindOpenDialogueByUplink( + string aircraftCallsign, + string stationId, + int uplinkMessageId, + CancellationToken cancellationToken) + { + await DialoguesWithMessages() + .Where(d => d.AircraftCallsign == aircraftCallsign && d.StationId == stationId && d.Closed == null) + .LoadAsync(cancellationToken); + + // BUG: It's possible to have messageId collisions, since the server generates incrementing ids, and some + // aircraft have their own incrementing ids ticking along too. + // We need to remove this method, and re-factor how messages are correlated to Dialogues. + // Idea: + // Split into multiple streams: + // 1. ReplyToDownlink (DialogueId, MessageId) + // 2. CreateDialogueFromUplink (No params) + // 3. AddReplyToUplink (UplinkId), Hoppie doesn't track Dialogue IDs, so we need to look through open dialogues for an uplink with that ID. + // 4. CreateDialogueFromDownlink (DownlinkId) + return dbContext.Dialogues.Local + .FirstOrDefault(d => + d.AircraftCallsign == aircraftCallsign && + d.StationId == stationId && + !d.IsClosed && + d.Messages.OfType().Any(m => m.MessageId == uplinkMessageId)); + } + + public async Task FindById(Guid id, CancellationToken cancellationToken) + { + await DialoguesWithMessages() + .Where(d => d.Id == id) + .LoadAsync(cancellationToken); + + return dbContext.Dialogues.Local.FirstOrDefault(d => d.Id == id); + } + + public async Task FindOpen(CancellationToken cancellationToken) + { + await DialoguesWithMessages() + .Where(d => d.Closed == null) + .LoadAsync(cancellationToken); + + return dbContext.Dialogues.Local.Where(d => !d.IsClosed).ToArray(); + } + + public async Task FindClosedAndNotArchived(CancellationToken cancellationToken) + { + await DialoguesWithMessages() + .Where(d => d.Closed != null && d.Archived == null) + .LoadAsync(cancellationToken); + + return dbContext.Dialogues.Local.Where(d => d.IsClosed && !d.IsArchived).ToArray(); + } + + public async Task FindOpenForAircraft(string aircraftCallsign, string stationId, CancellationToken cancellationToken) + { + await DialoguesWithMessages() + .Where(d => d.AircraftCallsign == aircraftCallsign && d.StationId == stationId && d.Closed == null && d.Archived == null) + .LoadAsync(cancellationToken); + + return dbContext.Dialogues.Local + .Where(d => d.AircraftCallsign == aircraftCallsign && d.StationId == stationId && !d.IsClosed && !d.IsArchived) + .ToArray(); + } + + public async Task RemoveOpenedBefore(DateTimeOffset cutoff, CancellationToken cancellationToken) + { + // The messages are not loaded. The database deletes them with their dialogue (cascade delete). + var dialogues = await dbContext.Dialogues + .Where(d => d.Opened < cutoff) + .ToArrayAsync(cancellationToken); + + dbContext.Dialogues.RemoveRange(dialogues); + return dialogues.Length; + } + + public async Task All(CancellationToken cancellationToken) + { + await DialoguesWithMessages().LoadAsync(cancellationToken); + return dbContext.Dialogues.Local.ToArray(); + } + + public Task Remove(Dialogue dialogue, CancellationToken cancellationToken) + { + dbContext.Dialogues.Remove(dialogue); + return Task.CompletedTask; + } + + IQueryable DialoguesWithMessages() + { + // Load the messages in their order in the dialogue + return dbContext.Dialogues + .Include(d => d.Messages.OrderBy(m => m.Position)); + } +} diff --git a/source/CPDLCServer/Cpdlc/Dialogues/IDialogueRepository.cs b/source/CPDLCServer/Cpdlc/Dialogues/IDialogueRepository.cs new file mode 100644 index 0000000..c6592f0 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/IDialogueRepository.cs @@ -0,0 +1,30 @@ +using System.Collections; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public interface IDialogueRepository +{ + Task Add(Dialogue dialogue, CancellationToken cancellationToken); + + Task FindOpenDialogueByUplink( + string aircraftCallsign, + string stationId, + int uplinkMessageId, + CancellationToken cancellationToken); + + Task FindById(Guid id, CancellationToken cancellationToken); + + Task FindOpen(CancellationToken cancellationToken); + + Task FindClosedAndNotArchived(CancellationToken cancellationToken); + + // The open dialogues of an aircraft with an ATSU + Task FindOpenForAircraft(string aircraftCallsign, string stationId, CancellationToken cancellationToken); + + // Removes the dialogues that opened before the cutoff, and returns the number of dialogues that were removed + Task RemoveOpenedBefore(DateTimeOffset cutoff, CancellationToken cancellationToken); + + Task All(CancellationToken cancellationToken); + + Task Remove(Dialogue dialogue, CancellationToken cancellationToken); +} diff --git a/source/CPDLCServer/Cpdlc/Dialogues/MessageMonitorService.cs b/source/CPDLCServer/Cpdlc/Dialogues/MessageMonitorService.cs new file mode 100644 index 0000000..303daa0 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/MessageMonitorService.cs @@ -0,0 +1,62 @@ +using CPDLCServer.Infrastructure; +using MediatR; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public class MessageMonitorService( + IUnitOfWorkMediator mediator, + IClock clock, + ILogger logger) + : BackgroundService +{ + readonly TimeSpan _timeoutCheckInterval = TimeSpan.FromSeconds(5); + + // The retention period is in hours, so the purge does not need to run often + readonly TimeSpan _purgeInterval = TimeSpan.FromMinutes(5); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + logger.Information("Starting message monitor service"); + DateTimeOffset? lastPurge = null; + try + { + while (!stoppingToken.IsCancellationRequested) + { + logger.Verbose("Running message monitor iteration"); + + // Each request is a separate unit of work, so that a failure in one does not stop the others + var now = clock.UtcNow(); + if (lastPurge is null || now - lastPurge >= _purgeInterval) + { + await Send(new PurgeExpiredCpdlcDataRequest(), stoppingToken); + lastPurge = now; + } + + await Send(new CheckMessageTimeoutsRequest(), stoppingToken); + await Send(new ArchiveCompletedDialoguesRequest(), stoppingToken); + + await Task.Delay(_timeoutCheckInterval, stoppingToken); + } + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + logger.Information("Message monitor task stopped"); + } + catch (Exception ex) + { + logger.Error(ex, "Fatal error in message monitor task"); + } + } + + async Task Send(IRequest request, CancellationToken stoppingToken) + { + try + { + await mediator.Send(request, stoppingToken); + } + catch (Exception ex) when (!stoppingToken.IsCancellationRequested) + { + logger.Error(ex, "Error during message monitoring ({RequestType})", request.GetType().Name); + } + } +} diff --git a/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequest.cs b/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequest.cs new file mode 100644 index 0000000..9af5327 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequest.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public record PurgeExpiredCpdlcDataRequest : IRequest; diff --git a/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandler.cs b/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandler.cs new file mode 100644 index 0000000..cbaca88 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandler.cs @@ -0,0 +1,25 @@ +using CPDLCServer.Infrastructure; +using CPDLCServer.Settings; +using MediatR; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public class PurgeExpiredCpdlcDataRequestHandler( + IDialogueRepository dialogueRepository, + IServerSettingsProvider settingsProvider, + IClock clock, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(PurgeExpiredCpdlcDataRequest request, CancellationToken cancellationToken) + { + var settings = await settingsProvider.Load(cancellationToken); + var retention = TimeSpan.FromHours(settings.DialogueRetentionHours); + var now = clock.UtcNow(); + + // The dialogue is purged when the retention period ends, also when it is open or the aircraft is connected + var purgedCount = await dialogueRepository.RemoveOpenedBefore(now - retention, cancellationToken); + if (purgedCount > 0) + logger.Information("Purging {DialogueCount} dialogue(s) older than {Retention}", purgedCount, retention); + } +} diff --git a/source/CPDLCServer/Messages/AcknowledgeDownlinkCommand.cs b/source/CPDLCServer/Cpdlc/Downlinks/AcknowledgeDownlinkCommand.cs similarity index 73% rename from source/CPDLCServer/Messages/AcknowledgeDownlinkCommand.cs rename to source/CPDLCServer/Cpdlc/Downlinks/AcknowledgeDownlinkCommand.cs index 4c9eff0..fa80030 100644 --- a/source/CPDLCServer/Messages/AcknowledgeDownlinkCommand.cs +++ b/source/CPDLCServer/Cpdlc/Downlinks/AcknowledgeDownlinkCommand.cs @@ -1,5 +1,5 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Downlinks; public record AcknowledgeDownlinkCommand(Guid DialogueId, int DownlinkMessageId) : IRequest; \ No newline at end of file diff --git a/source/CPDLCServer/Handlers/AcknowledgeDownlinkCommandHandler.cs b/source/CPDLCServer/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandler.cs similarity index 89% rename from source/CPDLCServer/Handlers/AcknowledgeDownlinkCommandHandler.cs rename to source/CPDLCServer/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandler.cs index d235d2d..47082e7 100644 --- a/source/CPDLCServer/Handlers/AcknowledgeDownlinkCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandler.cs @@ -1,37 +1,34 @@ -using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Persistence; -using MediatR; - -namespace CPDLCServer.Handlers; - -public class AcknowledgeDownlinkCommandHandler( - IDialogueRepository dialogueRepository, - IClock clock, - IPublisher publisher, - ILogger logger) - : IRequestHandler -{ - public async Task Handle(AcknowledgeDownlinkCommand request, CancellationToken cancellationToken) - { - var dialogue = await dialogueRepository.FindById(request.DialogueId, cancellationToken); - - if (dialogue is null) - { - logger.Warning("Dialogue not found for downlink acknowledgment: {DialogueId}", request.DialogueId); - throw new InvalidOperationException($"Dialogue not found: {request.DialogueId}"); - } - - dialogue.AcknowledgeDownlink(request.DownlinkMessageId, clock.UtcNow()); - - logger.Information( - "Acknowledged downlink {MessageId} in dialogue {DialogueId} for {AircraftCallsign}", - request.DownlinkMessageId, - request.DialogueId, - dialogue.AircraftCallsign); - - await publisher.Publish( - new DialogueChangedNotification(dialogue), - cancellationToken); - } -} +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Infrastructure; +using MediatR; + +namespace CPDLCServer.Cpdlc.Downlinks; + +public class AcknowledgeDownlinkCommandHandler( + IDialogueRepository dialogueRepository, + IClock clock, + IPublisher publisher, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(AcknowledgeDownlinkCommand request, CancellationToken cancellationToken) + { + var dialogue = await dialogueRepository.FindById(request.DialogueId, cancellationToken); + if (dialogue is null) + { + logger.Warning("Dialogue not found for downlink acknowledgment: {DialogueId}", request.DialogueId); + throw new InvalidOperationException($"Dialogue not found: {request.DialogueId}"); + } + + dialogue.AcknowledgeDownlink(request.DownlinkMessageId, clock.UtcNow()); + logger.Information( + "Acknowledged downlink {MessageId} in dialogue {DialogueId} for {AircraftCallsign}", + request.DownlinkMessageId, + request.DialogueId, + dialogue.AircraftCallsign); + + await publisher.Publish( + new DialogueChangedNotification(dialogue), + cancellationToken); + } +} diff --git a/source/CPDLCServer/Model/CpdlcDownlinkResponseType.cs b/source/CPDLCServer/Cpdlc/Downlinks/CpdlcDownlinkResponseType.cs similarity index 66% rename from source/CPDLCServer/Model/CpdlcDownlinkResponseType.cs rename to source/CPDLCServer/Cpdlc/Downlinks/CpdlcDownlinkResponseType.cs index 92074e6..58acfd2 100644 --- a/source/CPDLCServer/Model/CpdlcDownlinkResponseType.cs +++ b/source/CPDLCServer/Cpdlc/Downlinks/CpdlcDownlinkResponseType.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.Cpdlc.Downlinks; public enum CpdlcDownlinkResponseType { diff --git a/source/CPDLCServer/Cpdlc/Downlinks/DownlinkMessage.cs b/source/CPDLCServer/Cpdlc/Downlinks/DownlinkMessage.cs new file mode 100644 index 0000000..7aebc3c --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Downlinks/DownlinkMessage.cs @@ -0,0 +1,45 @@ +using CPDLCServer.Cpdlc.Dialogues; +namespace CPDLCServer.Cpdlc.Downlinks; + +public class DownlinkMessage : CpdlcMessage +{ + public DownlinkMessage( + Guid dialogueId, + int messageId, + int? messageReference, + string sender, + CpdlcDownlinkResponseType responseType, + AlertType alertType, + string content, + DateTimeOffset received) + : base(dialogueId, messageId, messageReference, alertType) + { + Sender = sender; + ResponseType = responseType; + Content = content; + Received = received; + + // Downlink messages requiring no response are self-closing + Closed = responseType == CpdlcDownlinkResponseType.NoResponse ? received : null; + } + + public string Sender { get; } + public CpdlcDownlinkResponseType ResponseType { get; } + public string Content { get; } + public DateTimeOffset Received { get; } + + public bool IsControllerLate { get; set; } + + public override DateTimeOffset Time => Received; + + public override void Close(DateTimeOffset time) + { + Closed = time; + IsControllerLate = false; + } + + public void Acknowledge(DateTimeOffset now) + { + Acknowledged = now; + } +} diff --git a/source/CPDLCServer/Messages/DownlinkReceivedNotification.cs b/source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotification.cs similarity index 61% rename from source/CPDLCServer/Messages/DownlinkReceivedNotification.cs rename to source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotification.cs index 6d9167c..ea9b4b2 100644 --- a/source/CPDLCServer/Messages/DownlinkReceivedNotification.cs +++ b/source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotification.cs @@ -1,10 +1,9 @@ -using CPDLCServer.Model; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Downlinks; public record DownlinkReceivedNotification( - string AcarsClientId, + string AcarsConnectionId, string StationId, ReceivedDownlink Downlink) : INotification; diff --git a/source/CPDLCServer/Handlers/DownlinkReceivedNotificationHandler.cs b/source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotificationHandler.cs similarity index 83% rename from source/CPDLCServer/Handlers/DownlinkReceivedNotificationHandler.cs rename to source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotificationHandler.cs index 6774d93..69a123f 100644 --- a/source/CPDLCServer/Handlers/DownlinkReceivedNotificationHandler.cs +++ b/source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotificationHandler.cs @@ -1,12 +1,13 @@ -using CPDLCServer.Hubs; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; using CPDLCServer.Persistence; +using CPDLCServer.Web; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Downlinks; public class DownlinkReceivedNotificationHandler( IAircraftRepository aircraftRepository, @@ -15,6 +16,7 @@ public class DownlinkReceivedNotificationHandler( IControllerRepository controllerRepository, IDialogueRepository dialogueRepository, IHubContext hubContext, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { @@ -24,6 +26,7 @@ public async Task Handle(DownlinkReceivedNotification notification, Cancellation logger.Information("Downlink message received from {Callsign}", downlink.Sender); // Scenario 1: Logon request + // TODO: Handle this in hoppies if (ControlMessages.IsLogonRequest(downlink)) { await mediator.Send( @@ -35,13 +38,13 @@ await mediator.Send( downlink.AlertType, downlink.Content, downlink.Received, - notification.AcarsClientId), + notification.AcarsConnectionId), cancellationToken); return; } var aircraftConnection = await aircraftRepository.Find( - new(downlink.Sender, notification.AcarsClientId), + new(downlink.Sender, notification.AcarsConnectionId), cancellationToken); // Scenario 2: Unknown aircraft @@ -54,9 +57,10 @@ await mediator.Send( // Scenario 3: Logoff notice // Show the logoff to the controller, then terminate the connection. // Return early so that the terminated connection is not promoted to CurrentDataAuthority. + // TODO: Handle this in hoppies if (ControlMessages.IsLogoffNotice(downlink)) { - var logoffDialogue = new Dialogue(downlink.Sender); + var logoffDialogue = new Dialogue(downlink.Sender, notification.StationId); logoffDialogue.AddDownlink( downlink.MessageId, downlink.MessageReference, @@ -71,7 +75,7 @@ await mediator.Send( await mediator.Publish(new DialogueChangedNotification(logoffDialogue), cancellationToken); - await mediator.Send(new TerminateConnectionRequest(downlink.Sender, notification.AcarsClientId), cancellationToken); + await mediator.Send(new TerminateConnectionRequest(downlink.Sender, notification.AcarsConnectionId), cancellationToken); return; } @@ -86,15 +90,14 @@ await mediator.Send( var controllers = await controllerRepository.All(cancellationToken); if (controllers.Any()) { - await hubContext.Clients + var aircraftConnectionDto = new Contracts.AircraftConnectionDto( + aircraftConnection.Callsign, + notification.StationId, + DialogueConverter.ToDto(aircraftConnection.DataAuthorityState)); + + unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(controllers.Select(c => c.ConnectionId)) - .SendAsync( - "AircraftConnectionUpdated", - new Contracts.AircraftConnectionDto( - aircraftConnection.Callsign, - notification.StationId, - DialogueConverter.ToDto(aircraftConnection.DataAuthorityState)), - cancellationToken); + .SendAsync("AircraftConnectionUpdated", aircraftConnectionDto, ct)); logger.Information( "Notified {ControllerCount} controller(s) that aircraft {Callsign} was promoted to CurrentDataAuthority", @@ -110,6 +113,7 @@ await hubContext.Clients { var dialogue = await dialogueRepository.FindOpenDialogueByUplink( downlink.Sender, + notification.StationId, downlink.MessageReference.Value, cancellationToken); if (dialogue is not null) @@ -122,7 +126,7 @@ await hubContext.Clients // TODO: This could lead to a bug if the Aircraft thinks we're still in the original message chain. // Consider returning an error here instead. logger.Warning("No open dialogue found for uplink reference {MessageReference} from {Callsign} - starting new dialogue", downlink.MessageReference.Value, downlink.Sender); - dialogue = new Dialogue(downlink.Sender); + dialogue = new Dialogue(downlink.Sender, notification.StationId); dialogue.AddDownlink( downlink.MessageId, downlink.MessageReference, @@ -139,7 +143,7 @@ await hubContext.Clients } else // Scenario 5: Aircraft initiates a new dialogue { - var dialogue = new Dialogue(downlink.Sender); + var dialogue = new Dialogue(downlink.Sender, notification.StationId); dialogue.AddDownlink( downlink.MessageId, downlink.MessageReference, diff --git a/source/CPDLCServer/Model/ReceivedDownlink.cs b/source/CPDLCServer/Cpdlc/Downlinks/ReceivedDownlink.cs similarity index 80% rename from source/CPDLCServer/Model/ReceivedDownlink.cs rename to source/CPDLCServer/Cpdlc/Downlinks/ReceivedDownlink.cs index 405691a..c414171 100644 --- a/source/CPDLCServer/Model/ReceivedDownlink.cs +++ b/source/CPDLCServer/Cpdlc/Downlinks/ReceivedDownlink.cs @@ -1,4 +1,5 @@ -namespace CPDLCServer.Model; +using CPDLCServer.Cpdlc.Dialogues; +namespace CPDLCServer.Cpdlc.Downlinks; // Raw downlink data as parsed from an ACARS packet, before being assigned to a dialogue. public record ReceivedDownlink( diff --git a/source/CPDLCServer/Cpdlc/Motd/MotdScheduler.cs b/source/CPDLCServer/Cpdlc/Motd/MotdScheduler.cs new file mode 100644 index 0000000..cd9fabf --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Motd/MotdScheduler.cs @@ -0,0 +1,35 @@ +using CPDLCServer.Infrastructure; + +namespace CPDLCServer.Cpdlc.Motd; + +/// +/// Sends the message of the day of an ACARS connection to an aircraft after a delay. +/// The delay runs in the background, so that the logon does not wait for it. +/// +public class MotdScheduler( + IUnitOfWorkMediator mediator, + IHostApplicationLifetime lifetime, + ILogger logger) +{ + public void Schedule(string acarsConnectionId, string callsign, TimeSpan delay) + { + _ = Task.Run(async () => + { + var cancellationToken = lifetime.ApplicationStopping; + + try + { + await Task.Delay(delay, cancellationToken); + await mediator.Send(new SendMotdCommand(acarsConnectionId, callsign), cancellationToken); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // The server is stopping + } + catch (Exception ex) + { + logger.Error(ex, "Failed to send the message of the day to {Callsign} on {AcarsConnectionId}", callsign, acarsConnectionId); + } + }); + } +} diff --git a/source/CPDLCServer/Cpdlc/Motd/SendMotdCommand.cs b/source/CPDLCServer/Cpdlc/Motd/SendMotdCommand.cs new file mode 100644 index 0000000..43d5349 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Motd/SendMotdCommand.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.Cpdlc.Motd; + +public record SendMotdCommand(string AcarsConnectionId, string Callsign) : IRequest; diff --git a/source/CPDLCServer/Cpdlc/Motd/SendMotdCommandHandler.cs b/source/CPDLCServer/Cpdlc/Motd/SendMotdCommandHandler.cs new file mode 100644 index 0000000..8a24f78 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Motd/SendMotdCommandHandler.cs @@ -0,0 +1,42 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Uplinks; +using MediatR; + +namespace CPDLCServer.Cpdlc.Motd; + +// Sends the message of the day as a CPDLC free text message with no response. +// The message is not sent if the aircraft disconnected during the delay, or if the message was removed. +public class SendMotdCommandHandler( + IAircraftRepository aircraftRepository, + IAcarsConnectionManager acarsConnectionManager, + IMediator mediator, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(SendMotdCommand request, CancellationToken cancellationToken) + { + var aircraftConnection = await aircraftRepository.Find( + new AircraftKey(request.Callsign, request.AcarsConnectionId), + cancellationToken); + if (aircraftConnection is not { DataAuthorityState: DataAuthorityState.CurrentDataAuthority }) + { + logger.Information("Message of the day not sent to {Callsign}: the aircraft is not connected", request.Callsign); + return; + } + + var configuration = await acarsConnectionManager.GetConfigurationForStation(aircraftConnection.StationId, cancellationToken); + if (string.IsNullOrWhiteSpace(configuration.Motd)) + return; + + logger.Information("Sending the message of the day to {Callsign}", request.Callsign); + + await mediator.Send( + new BeginDialogueCommand( + aircraftConnection.StationId, + request.Callsign, + CpdlcUplinkResponseType.NoResponse, + configuration.Motd), + cancellationToken); + } +} diff --git a/source/CPDLCServer/Cpdlc/Motd/SendMotdOnConnectionEstablishedHandler.cs b/source/CPDLCServer/Cpdlc/Motd/SendMotdOnConnectionEstablishedHandler.cs new file mode 100644 index 0000000..1f255c8 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Motd/SendMotdOnConnectionEstablishedHandler.cs @@ -0,0 +1,31 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.Cpdlc.Motd; + +// When an aircraft logs on, the message of the day of the ACARS connection is sent after its delay. +// It is sent only to the current data authority, so that the next data authority does not send it a second time. +public class SendMotdOnConnectionEstablishedHandler( + IAcarsConnectionManager acarsConnectionManager, + MotdScheduler motdScheduler, + IUnitOfWork unitOfWork) + : INotificationHandler +{ + public async Task Handle(AircraftConnectionEstablished notification, CancellationToken cancellationToken) + { + if (notification.DataAuthorityState != DataAuthorityState.CurrentDataAuthority) + return; + + var configuration = await acarsConnectionManager.GetConfigurationForStation(notification.StationId, cancellationToken); + if (string.IsNullOrWhiteSpace(configuration.Motd)) + return; + + unitOfWork.AfterCommit(_ => + { + motdScheduler.Schedule(notification.AcarsConnectionId, notification.Callsign, configuration.MotdDelay); + return Task.CompletedTask; + }); + } +} diff --git a/source/CPDLCServer/Messages/AcknowledgeUplinkCommand.cs b/source/CPDLCServer/Cpdlc/Uplinks/AcknowledgeUplinkCommand.cs similarity index 73% rename from source/CPDLCServer/Messages/AcknowledgeUplinkCommand.cs rename to source/CPDLCServer/Cpdlc/Uplinks/AcknowledgeUplinkCommand.cs index 00039ac..418e7a7 100644 --- a/source/CPDLCServer/Messages/AcknowledgeUplinkCommand.cs +++ b/source/CPDLCServer/Cpdlc/Uplinks/AcknowledgeUplinkCommand.cs @@ -1,5 +1,5 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Uplinks; public record AcknowledgeUplinkCommand(Guid DialogueId, int UplinkMessageId) : IRequest; \ No newline at end of file diff --git a/source/CPDLCServer/Handlers/AcknowledgeUplinkCommandHandler.cs b/source/CPDLCServer/Cpdlc/Uplinks/AcknowledgeUplinkCommandHandler.cs similarity index 93% rename from source/CPDLCServer/Handlers/AcknowledgeUplinkCommandHandler.cs rename to source/CPDLCServer/Cpdlc/Uplinks/AcknowledgeUplinkCommandHandler.cs index 81686bd..b6b213e 100644 --- a/source/CPDLCServer/Handlers/AcknowledgeUplinkCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Uplinks/AcknowledgeUplinkCommandHandler.cs @@ -1,10 +1,8 @@ +using CPDLCServer.Cpdlc.Dialogues; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Uplinks; // TODO: Tests diff --git a/source/CPDLCServer/Messages/BeginDialogueCommand.cs b/source/CPDLCServer/Cpdlc/Uplinks/BeginDialogueCommand.cs similarity index 75% rename from source/CPDLCServer/Messages/BeginDialogueCommand.cs rename to source/CPDLCServer/Cpdlc/Uplinks/BeginDialogueCommand.cs index dcf6264..ddcf46b 100644 --- a/source/CPDLCServer/Messages/BeginDialogueCommand.cs +++ b/source/CPDLCServer/Cpdlc/Uplinks/BeginDialogueCommand.cs @@ -1,7 +1,6 @@ -using CPDLCServer.Model; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Uplinks; public record BeginDialogueCommand( string Sender, diff --git a/source/CPDLCServer/Handlers/BeginDialogueCommandHandler.cs b/source/CPDLCServer/Cpdlc/Uplinks/BeginDialogueCommandHandler.cs similarity index 75% rename from source/CPDLCServer/Handlers/BeginDialogueCommandHandler.cs rename to source/CPDLCServer/Cpdlc/Uplinks/BeginDialogueCommandHandler.cs index e172077..d14fbda 100644 --- a/source/CPDLCServer/Handlers/BeginDialogueCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Uplinks/BeginDialogueCommandHandler.cs @@ -1,20 +1,19 @@ -using CPDLCServer.Clients; +using CPDLCServer.AcarsConnections; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using CPDLCServer.Services; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Uplinks; public class BeginDialogueCommandHandler( IAircraftRepository aircraftRepository, - IClientManager clientManager, + IAcarsConnectionManager acarsConnectionManager, IMessageIdProvider messageIdProvider, IDialogueRepository dialogueRepository, IMediator mediator, IClock clock, + IUplinkTransmitter uplinkTransmitter, ILogger logger) : IRequestHandler { @@ -30,14 +29,14 @@ public async Task Handle(BeginDialogueCommand request, CancellationToken cancell if (aircraftConnection is null) throw new Exception($"{request.Recipient} is not connected"); - var client = await clientManager.GetAcarsClient(aircraftConnection.AcarsClientId, cancellationToken); + var acarsConnection = await acarsConnectionManager.GetAcarsConnection(aircraftConnection.AcarsConnectionId, cancellationToken); var messageId = await messageIdProvider.GetNextMessageId( - aircraftConnection.AcarsClientId, + aircraftConnection.AcarsConnectionId, request.Recipient, cancellationToken); - var dialogue = new Dialogue(request.Recipient); + var dialogue = new Dialogue(request.Recipient, aircraftConnection.StationId); var uplinkMessage = dialogue.AddUplink( messageId, null, @@ -54,7 +53,6 @@ public async Task Handle(BeginDialogueCommand request, CancellationToken cancell await mediator.Publish(new DialogueChangedNotification(dialogue), cancellationToken); - await client.Send(uplinkMessage, cancellationToken); - logger.Information("Sent CPDLC message from {Sender} to {Recipient}", request.Sender, request.Recipient); + uplinkTransmitter.TransmitAfterCommit(acarsConnection, uplinkMessage); } } diff --git a/source/CPDLCServer/Model/CpdlcUplinkResponseType.cs b/source/CPDLCServer/Cpdlc/Uplinks/CpdlcUplinkResponseType.cs similarity index 74% rename from source/CPDLCServer/Model/CpdlcUplinkResponseType.cs rename to source/CPDLCServer/Cpdlc/Uplinks/CpdlcUplinkResponseType.cs index 3f9e43b..dce267e 100644 --- a/source/CPDLCServer/Model/CpdlcUplinkResponseType.cs +++ b/source/CPDLCServer/Cpdlc/Uplinks/CpdlcUplinkResponseType.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.Cpdlc.Uplinks; public enum CpdlcUplinkResponseType { diff --git a/source/CPDLCServer/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommand.cs b/source/CPDLCServer/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommand.cs new file mode 100644 index 0000000..396419d --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommand.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.Cpdlc.Uplinks; + +public record MarkUplinkTransmissionFailedCommand(Guid DialogueId, int UplinkMessageId) : IRequest; diff --git a/source/CPDLCServer/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommandHandler.cs b/source/CPDLCServer/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommandHandler.cs new file mode 100644 index 0000000..6e1680a --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommandHandler.cs @@ -0,0 +1,33 @@ +using CPDLCServer.Cpdlc.Dialogues; +using MediatR; + +namespace CPDLCServer.Cpdlc.Uplinks; + +public class MarkUplinkTransmissionFailedCommandHandler( + IDialogueRepository dialogueRepository, + IPublisher publisher, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(MarkUplinkTransmissionFailedCommand request, CancellationToken cancellationToken) + { + var dialogue = await dialogueRepository.FindById(request.DialogueId, cancellationToken); + if (dialogue is null) + { + logger.Warning( + "Cannot mark uplink {MessageId} as failed: dialogue {DialogueId} not found", + request.UplinkMessageId, + request.DialogueId); + return; + } + + dialogue.MarkTransmissionFailed(request.UplinkMessageId); + + logger.Information( + "Marked uplink {MessageId} in dialogue {DialogueId} as failed", + request.UplinkMessageId, + request.DialogueId); + + await publisher.Publish(new DialogueChangedNotification(dialogue), cancellationToken); + } +} diff --git a/source/CPDLCServer/Cpdlc/Uplinks/MessageIdProvider.cs b/source/CPDLCServer/Cpdlc/Uplinks/MessageIdProvider.cs new file mode 100644 index 0000000..799dd71 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Uplinks/MessageIdProvider.cs @@ -0,0 +1,46 @@ +using CPDLCServer.Persistence; + +namespace CPDLCServer.Cpdlc.Uplinks; + +public interface IMessageIdProvider +{ + Task GetNextMessageId( + string acarsConnectionId, + string callsign, + CancellationToken cancellationToken); + + // Removes the message IDs of an aircraft when its connection ends. The next connection starts at the first ID. + Task Remove( + string acarsConnectionId, + string callsign, + CancellationToken cancellationToken); +} + +// The last message ID is saved with the unit of work, so that the IDs continue after a restart +public class MessageIdProvider(CpdlcDbContext dbContext) : IMessageIdProvider +{ + public async Task GetNextMessageId( + string acarsConnectionId, + string callsign, + CancellationToken cancellationToken) + { + var sequence = await dbContext.MessageIdSequences.FindAsync([acarsConnectionId, callsign], cancellationToken); + if (sequence is null) + { + sequence = new MessageIdSequence(acarsConnectionId, callsign); + dbContext.MessageIdSequences.Add(sequence); + } + + return sequence.Next(); + } + + public async Task Remove( + string acarsConnectionId, + string callsign, + CancellationToken cancellationToken) + { + var sequence = await dbContext.MessageIdSequences.FindAsync([acarsConnectionId, callsign], cancellationToken); + if (sequence is not null) + dbContext.MessageIdSequences.Remove(sequence); + } +} diff --git a/source/CPDLCServer/Cpdlc/Uplinks/MessageIdSequence.cs b/source/CPDLCServer/Cpdlc/Uplinks/MessageIdSequence.cs new file mode 100644 index 0000000..332d66b --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Uplinks/MessageIdSequence.cs @@ -0,0 +1,15 @@ +namespace CPDLCServer.Cpdlc.Uplinks; + +// The last CPDLC message ID that the server sent to an aircraft on an ACARS connection +public class MessageIdSequence(string acarsConnectionId, string callsign) +{ + public string AcarsConnectionId { get; } = acarsConnectionId; + public string Callsign { get; } = callsign; + public int LastMessageId { get; private set; } + + public int Next() + { + LastMessageId++; + return LastMessageId; + } +} diff --git a/source/CPDLCServer/Cpdlc/Uplinks/MessageIdSequenceConfiguration.cs b/source/CPDLCServer/Cpdlc/Uplinks/MessageIdSequenceConfiguration.cs new file mode 100644 index 0000000..127575b --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Uplinks/MessageIdSequenceConfiguration.cs @@ -0,0 +1,18 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.Cpdlc.Uplinks; + +public class MessageIdSequenceConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("MessageIdSequences"); + + builder.HasKey(s => new { s.AcarsConnectionId, s.Callsign }); + + builder.Property(s => s.AcarsConnectionId); + builder.Property(s => s.Callsign); + builder.Property(s => s.LastMessageId); + } +} diff --git a/source/CPDLCServer/Messages/ReplyToDownlinkCommand.cs b/source/CPDLCServer/Cpdlc/Uplinks/ReplyToDownlinkCommand.cs similarity index 77% rename from source/CPDLCServer/Messages/ReplyToDownlinkCommand.cs rename to source/CPDLCServer/Cpdlc/Uplinks/ReplyToDownlinkCommand.cs index b7dd5bb..00c577f 100644 --- a/source/CPDLCServer/Messages/ReplyToDownlinkCommand.cs +++ b/source/CPDLCServer/Cpdlc/Uplinks/ReplyToDownlinkCommand.cs @@ -1,7 +1,6 @@ -using CPDLCServer.Model; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Uplinks; public record ReplyToDownlinkCommand( string Sender, diff --git a/source/CPDLCServer/Handlers/ReplyToDownlinkCommandHandler.cs b/source/CPDLCServer/Cpdlc/Uplinks/ReplyToDownlinkCommandHandler.cs similarity index 67% rename from source/CPDLCServer/Handlers/ReplyToDownlinkCommandHandler.cs rename to source/CPDLCServer/Cpdlc/Uplinks/ReplyToDownlinkCommandHandler.cs index 8dfc823..ad9899e 100644 --- a/source/CPDLCServer/Handlers/ReplyToDownlinkCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Uplinks/ReplyToDownlinkCommandHandler.cs @@ -1,20 +1,19 @@ -using CPDLCServer.Clients; +using CPDLCServer.AcarsConnections; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using CPDLCServer.Services; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Uplinks; public class ReplyToDownlinkCommandHandler( IAircraftRepository aircraftRepository, - IClientManager clientManager, + IAcarsConnectionManager acarsConnectionManager, IMessageIdProvider messageIdProvider, IDialogueRepository dialogueRepository, IMediator mediator, IClock clock, + IUplinkTransmitter uplinkTransmitter, ILogger logger) : IRequestHandler { @@ -28,17 +27,16 @@ public async Task Handle(ReplyToDownlinkCommand request, CancellationToken cance logger.Information("Replying to downlink {DownlinkMessageId} in dialogue {DialogueId} for {Callsign}", request.DownlinkMessageId, request.DialogueId, callsign); + // The reply goes through the connection of the ATSU of the dialogue var allAircraft = await aircraftRepository.All(cancellationToken); - var aircraftConnection = - allAircraft.FirstOrDefault(a => a.Callsign == callsign && a.DataAuthorityState == DataAuthorityState.CurrentDataAuthority) - ?? allAircraft.FirstOrDefault(a => a.Callsign == callsign && a.DataAuthorityState == DataAuthorityState.NextDataAuthority); + var aircraftConnection = allAircraft.FirstOrDefault(a => a.Callsign == callsign && a.StationId == dialogue.StationId); if (aircraftConnection is null) throw new Exception($"{callsign} is not connected"); - var client = await clientManager.GetAcarsClient(aircraftConnection.AcarsClientId, cancellationToken); + var acarsConnection = await acarsConnectionManager.GetAcarsConnection(aircraftConnection.AcarsConnectionId, cancellationToken); var messageId = await messageIdProvider.GetNextMessageId( - aircraftConnection.AcarsClientId, + aircraftConnection.AcarsConnectionId, callsign, cancellationToken); @@ -57,7 +55,6 @@ public async Task Handle(ReplyToDownlinkCommand request, CancellationToken cance await mediator.Publish(new DialogueChangedNotification(dialogue), cancellationToken); - await client.Send(uplinkMessage, cancellationToken); - logger.Information("Sent CPDLC message from {Sender} to {Callsign}", request.Sender, callsign); + uplinkTransmitter.TransmitAfterCommit(acarsConnection, uplinkMessage); } } diff --git a/source/CPDLCServer/Cpdlc/Uplinks/UplinkMessage.cs b/source/CPDLCServer/Cpdlc/Uplinks/UplinkMessage.cs new file mode 100644 index 0000000..bc05507 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Uplinks/UplinkMessage.cs @@ -0,0 +1,55 @@ +using CPDLCServer.Cpdlc.Dialogues; +namespace CPDLCServer.Cpdlc.Uplinks; + +// TODO: Separate formatted and plaintext contents. + +public class UplinkMessage : CpdlcMessage +{ + public UplinkMessage( + Guid dialogueId, + int messageId, + int? messageReference, + string recipient, + string senderCallsign, + CpdlcUplinkResponseType responseType, + AlertType alertType, + string content, + DateTimeOffset sent) + : base(dialogueId, messageId, messageReference, alertType) + { + Recipient = recipient; + SenderCallsign = senderCallsign; + ResponseType = responseType; + Content = content; + Sent = sent; + + // Uplink messages requiring no response are self-closing + Closed = responseType == CpdlcUplinkResponseType.NoResponse ? sent : null; + + // Uplinks are automatically acknowledged + Acknowledged = sent; + } + + public string Recipient { get; } + public string SenderCallsign { get; } + public CpdlcUplinkResponseType ResponseType { get; } + public string Content { get; } + public DateTimeOffset Sent { get; } + public bool ClosedManually { get; private set; } + + // public bool CanAction { get; set; } + // public bool Actioned { get; set; } + public bool IsPilotLate { get; set; } + public bool DidTransmissionFail { get; set; } + + public override DateTimeOffset Time => Sent; + + public override void Close(DateTimeOffset time) => Close(time, false); + + public void Close(DateTimeOffset time, bool manual) + { + Closed = time; + ClosedManually = manual; + IsPilotLate = false; + } +} diff --git a/source/CPDLCServer/Cpdlc/Uplinks/UplinkTransmitter.cs b/source/CPDLCServer/Cpdlc/Uplinks/UplinkTransmitter.cs new file mode 100644 index 0000000..5ff5a5d --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Uplinks/UplinkTransmitter.cs @@ -0,0 +1,44 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.Infrastructure; +using CPDLCServer.Persistence; + +namespace CPDLCServer.Cpdlc.Uplinks; + +public interface IUplinkTransmitter +{ + /// + /// Sends the uplink after the unit of work is committed. + /// If the ACARS network does not accept the uplink, the uplink is marked as failed in a new unit of work. + /// + void TransmitAfterCommit(IAcarsConnection acarsConnection, UplinkMessage uplink); +} + +public class UplinkTransmitter( + IUnitOfWork unitOfWork, + IUnitOfWorkMediator unitOfWorkMediator, + ILogger logger) + : IUplinkTransmitter +{ + public void TransmitAfterCommit(IAcarsConnection acarsConnection, UplinkMessage uplink) + { + unitOfWork.AfterCommit(async ct => + { + try + { + await acarsConnection.Send(uplink, ct); + logger.Information("Sent CPDLC message from {Sender} to {Recipient}", uplink.SenderCallsign, uplink.Recipient); + } + catch (Exception ex) + { + logger.Error(ex, "Failed to send uplink {MessageId} to {Recipient}", uplink.MessageId, uplink.Recipient); + + // The unit of work of the uplink is already committed, so a new unit of work changes the uplink + await unitOfWorkMediator.Send( + new MarkUplinkTransmissionFailedCommand(uplink.DialogueId, uplink.MessageId), + ct); + + throw; + } + }); + } +} diff --git a/source/CPDLCServer/Dockerfile b/source/CPDLCServer/Dockerfile index 05ab5a0..f2baa4c 100644 --- a/source/CPDLCServer/Dockerfile +++ b/source/CPDLCServer/Dockerfile @@ -1,4 +1,7 @@ FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base +# The data directory: the SQLite database +RUN mkdir -p /data && chown $APP_UID /data +VOLUME /data USER $APP_UID WORKDIR /app EXPOSE 8080 diff --git a/source/CPDLCServer/Exceptions/ConfigurationNotFoundException.cs b/source/CPDLCServer/Exceptions/ConfigurationNotFoundException.cs deleted file mode 100644 index 9d80547..0000000 --- a/source/CPDLCServer/Exceptions/ConfigurationNotFoundException.cs +++ /dev/null @@ -1,4 +0,0 @@ -namespace CPDLCServer.Exceptions; - -public sealed class ConfigurationNotFoundException(string acarsClientId) - : Exception($"No ACARS configuration found for client ID '{acarsClientId}'"); \ No newline at end of file diff --git a/source/CPDLCServer/Handlers/CancelAdscContractOnConnectionEndedHandler.cs b/source/CPDLCServer/Handlers/CancelAdscContractOnConnectionEndedHandler.cs deleted file mode 100644 index b05be1c..0000000 --- a/source/CPDLCServer/Handlers/CancelAdscContractOnConnectionEndedHandler.cs +++ /dev/null @@ -1,46 +0,0 @@ -using CPDLCServer.Clients; -using CPDLCServer.Messages; -using CPDLCServer.Persistence; -using MediatR; - -namespace CPDLCServer.Handlers; - -public class CancelAdscContractOnConnectionEndedHandler( - IClientManager clientManager, - IAdscContractRepository adscContractRepository, - IMediator mediator, - ILogger logger) - : INotificationHandler, INotificationHandler -{ - public async Task Handle(AircraftConnectionTerminated notification, CancellationToken cancellationToken) - { - await CancelContract(notification.Callsign, notification.StationId, cancellationToken); - } - - public async Task Handle(AircraftConnectionLost notification, CancellationToken cancellationToken) - { - var client = await clientManager.GetAcarsClient(notification.AcarsClientId, cancellationToken); - await CancelContract(notification.Callsign, client.StationId, cancellationToken); - } - - async Task CancelContract(string callsign, string stationId, CancellationToken cancellationToken) - { - // A failure here must not stop the other handlers for the ended CPDLC connection - try - { - var contract = await adscContractRepository.Find(new AdscContractKey(callsign, stationId), cancellationToken); - if (contract is null) - return; - - await mediator.Send(new CancelAdscContractCommand(stationId, callsign), cancellationToken); - } - catch (Exception ex) when (!cancellationToken.IsCancellationRequested) - { - logger.Error( - ex, - "Failed to cancel ADS-C contract with {Callsign} for {StationId}", - callsign, - stationId); - } - } -} diff --git a/source/CPDLCServer/Handlers/EndExpiredAdscContractsRequestHandler.cs b/source/CPDLCServer/Handlers/EndExpiredAdscContractsRequestHandler.cs deleted file mode 100644 index dc8f76c..0000000 --- a/source/CPDLCServer/Handlers/EndExpiredAdscContractsRequestHandler.cs +++ /dev/null @@ -1,100 +0,0 @@ -using CPDLCServer.Clients; -using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using MediatR; - -namespace CPDLCServer.Handlers; - -public class EndExpiredAdscContractsRequestHandler( - IClientManager clientManager, - IAdscContractRepository adscContractRepository, - IClock clock, - IMediator mediator, - ILogger logger) - : IRequestHandler -{ - public async Task Handle(EndExpiredAdscContractsRequest request, CancellationToken cancellationToken) - { - var contracts = await adscContractRepository.All(cancellationToken); - var now = clock.UtcNow(); - - foreach (var contract in contracts) - { - if (now - contract.LastActivity > request.ContractTimeout) - { - // A failure for one aircraft must not stop the other aircraft - try - { - await CancelInactiveContract(contract, cancellationToken); - } - catch (Exception ex) when (!cancellationToken.IsCancellationRequested) - { - logger.Error( - ex, - "Failed to remove inactive ADS-C contract with {Callsign} for {StationId}", - contract.Callsign, - contract.StationId); - } - - continue; - } - - if (contract.SelectedContractEnds is null || contract.SelectedContractEnds > now) - continue; - - logger.Information( - "Selected ADS-C contract with {Callsign} from {StationId} has ended", - contract.Callsign, - contract.StationId); - - // A failure for one aircraft must not stop the other aircraft - try - { - await mediator.Send( - new RequestDefaultAdscContractCommand(contract.StationId, contract.Callsign), - cancellationToken); - } - catch (Exception ex) when (!cancellationToken.IsCancellationRequested) - { - logger.Error( - ex, - "Failed to request default ADS-C contract with {Callsign} for {StationId}", - contract.Callsign, - contract.StationId); - } - } - } - - async Task CancelInactiveContract(AdscContract contract, CancellationToken cancellationToken) - { - logger.Information( - "ADS-C contract with {Callsign} from {StationId} has no activity since {LastActivity}, cancelling", - contract.Callsign, - contract.StationId, - contract.LastActivity); - - // The aircraft is possibly not on the ACARS network any more. - // Remove the contract, even if the ACARS network cannot cancel it. - try - { - var client = await clientManager.GetAcarsClientForStation(contract.StationId, cancellationToken); - await client.CancelAdscContract(contract.Callsign, cancellationToken); - } - catch (Exception ex) when (!cancellationToken.IsCancellationRequested) - { - logger.Warning( - ex, - "Failed to cancel ADS-C contract with {Callsign} for {StationId} on the ACARS network", - contract.Callsign, - contract.StationId); - } - - await adscContractRepository.Remove(new AdscContractKey(contract.Callsign, contract.StationId), cancellationToken); - - await mediator.Publish( - new AdscContractRemovedNotification(contract.Callsign, contract.StationId), - cancellationToken); - } -} diff --git a/source/CPDLCServer/Handlers/GetAtsuSettingsRequestHandler.cs b/source/CPDLCServer/Handlers/GetAtsuSettingsRequestHandler.cs deleted file mode 100644 index 12f0f6d..0000000 --- a/source/CPDLCServer/Handlers/GetAtsuSettingsRequestHandler.cs +++ /dev/null @@ -1,19 +0,0 @@ -using CPDLCServer.Clients; -using CPDLCServer.Contracts; -using CPDLCServer.Messages; -using MediatR; - -namespace CPDLCServer.Handlers; - -public class GetAtsuSettingsRequestHandler(IClientManager clientManager) - : IRequestHandler -{ - public async Task Handle(GetAtsuSettingsRequest request, CancellationToken cancellationToken) - { - var configuration = await clientManager.GetConfigurationForStation(request.StationId, cancellationToken); - - return new AtsuSettingsDto( - request.StationId, - TimeSpan.FromMinutes(configuration.DefaultAdscReportingInterval)); - } -} diff --git a/source/CPDLCServer/Handlers/LogonCommandHandler.cs b/source/CPDLCServer/Handlers/LogonCommandHandler.cs deleted file mode 100644 index 7e83caa..0000000 --- a/source/CPDLCServer/Handlers/LogonCommandHandler.cs +++ /dev/null @@ -1,124 +0,0 @@ -using CPDLCServer.Clients; -using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using CPDLCServer.Services; -using MediatR; - -namespace CPDLCServer.Handlers; - -public class LogonCommandHandler( - IClientManager clientManager, - IAircraftRepository aircraftRepository, - IControllerRepository controllerRepository, - IDialogueRepository dialogueRepository, - IMessageIdProvider messageIdProvider, - IClock clock, - IMediator mediator, - ILogger logger) - : IRequestHandler -{ - public async Task Handle(LogonCommand request, CancellationToken cancellationToken) - { - var client = await clientManager.GetAcarsClient(request.AcarsClientId, cancellationToken); - - // If the aircraft already exists, simply accept the connection again - // Likely an issue with the aircraft requiring a reconnect - var aircraft = await aircraftRepository.Find( - new(request.AcarsClientId, request.Callsign), - cancellationToken); - - if (aircraft is not null) - { - logger.Verbose("Duplicate connection request received from {Callsign} on {ClientId}. Accepting the request.", request.Callsign, request.AcarsClientId); - - await Reply(client, request, "LOGON ACCEPTED", cancellationToken); - - return; - } - - aircraft = new AircraftConnection( - request.Callsign, - request.AcarsClientId, - client.StationId, - DataAuthorityState.NextDataAuthority); - - aircraft.RequestLogon(clock.UtcNow()); - - await aircraftRepository.Add( - new(request.Callsign, request.AcarsClientId), - aircraft, - cancellationToken); - - // Don't accept the logon if no controllers are connected - var activeControllers = await controllerRepository.All(cancellationToken); - if (activeControllers.Length == 0) - { - logger.Information("New connection request received from {Callsign} on {ClientId}, but no ATS is online. Rejecting the request.", request.Callsign, request.AcarsClientId); - - await Reply(client, request, "LOGON REJECTED. NO ATS AVBL.", cancellationToken); - - await aircraftRepository.Remove( - new AircraftKey(request.Callsign, request.AcarsClientId), - cancellationToken); - - return; - } - - logger.Information("New connection request received from {Callsign} on {ClientId}. Accepting the request.", request.Callsign, request.AcarsClientId); - - // Immediately accept it for now - aircraft.AcceptLogon(clock.UtcNow()); - - await Reply(client, request, "LOGON ACCEPTED", cancellationToken); - - await mediator.Publish( - new AircraftConnectionEstablished( - request.AcarsClientId, - aircraft.StationId, - request.Callsign, - aircraft.DataAuthorityState), - cancellationToken); - } - - async Task Reply( - IAcarsClient client, - LogonCommand request, - string content, - CancellationToken cancellationToken) - { - var dialogue = new Dialogue(request.Callsign); - dialogue.AddDownlink( - request.DownlinkId, - request.DownlinkMessageReference, - request.Callsign, - request.DownlinkResponseType, - request.DownlinkAlertType, - request.DownlinkContent, - request.DownlinkReceived); - - var messageId = await messageIdProvider.GetNextMessageId( - request.AcarsClientId, - request.Callsign, - cancellationToken); - - var uplinkMessage = dialogue.AddUplink( - messageId, - request.DownlinkId, - request.Callsign, - "SYSTEM", - CpdlcUplinkResponseType.NoResponse, - AlertType.None, - content, - clock.UtcNow()); - - await dialogueRepository.Add(dialogue, cancellationToken); - logger.Information("Dialogue {DialogueId} created for logon reply to {Callsign}", dialogue.Id, request.Callsign); - - await mediator.Publish(new DialogueChangedNotification(dialogue), cancellationToken); - - await client.Send(uplinkMessage, cancellationToken); - logger.Information("Sent CPDLC message from SYSTEM to {Callsign}", request.Callsign); - } -} diff --git a/source/CPDLCServer/Handlers/RequestDefaultAdscContractCommandHandler.cs b/source/CPDLCServer/Handlers/RequestDefaultAdscContractCommandHandler.cs deleted file mode 100644 index ecc4f8f..0000000 --- a/source/CPDLCServer/Handlers/RequestDefaultAdscContractCommandHandler.cs +++ /dev/null @@ -1,45 +0,0 @@ -using CPDLCServer.Clients; -using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using MediatR; - -namespace CPDLCServer.Handlers; - -public class RequestDefaultAdscContractCommandHandler( - IClientManager clientManager, - IAdscContractRepository adscContractRepository, - IMediator mediator, - IClock clock, - ILogger logger) - : IRequestHandler -{ - public async Task Handle(RequestDefaultAdscContractCommand request, CancellationToken cancellationToken) - { - var configuration = await clientManager.GetConfigurationForStation(request.StationId, cancellationToken); - var reportingInterval = TimeSpan.FromMinutes(configuration.DefaultAdscReportingInterval); - - logger.Information( - "Requesting default ADS-C contract with {Callsign} from {StationId} (Interval: {ReportingInterval})", - request.Callsign, - request.StationId, - reportingInterval); - - var client = await clientManager.GetAcarsClientForStation(request.StationId, cancellationToken); - await client.RequestPeriodicAdscContract(request.Callsign, reportingInterval, cancellationToken); - - var contractKey = new AdscContractKey(request.Callsign, request.StationId); - var contract = await adscContractRepository.Find(contractKey, cancellationToken); - if (contract is null) - { - contract = new AdscContract(request.Callsign, request.StationId); - await adscContractRepository.Add(contractKey, contract, cancellationToken); - } - - contract.RequestDefaultContract(reportingInterval); - contract.LogActivity(clock.UtcNow()); - - await mediator.Publish(new AdscContractChangedNotification(contract), cancellationToken); - } -} diff --git a/source/CPDLCServer/Handlers/RequestSelectedAdscContractCommandHandler.cs b/source/CPDLCServer/Handlers/RequestSelectedAdscContractCommandHandler.cs deleted file mode 100644 index 94ce6c4..0000000 --- a/source/CPDLCServer/Handlers/RequestSelectedAdscContractCommandHandler.cs +++ /dev/null @@ -1,52 +0,0 @@ -using CPDLCServer.Clients; -using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using MediatR; - -namespace CPDLCServer.Handlers; - -public class RequestSelectedAdscContractCommandHandler( - IClientManager clientManager, - IAdscContractRepository adscContractRepository, - IMediator mediator, - IClock clock, - ILogger logger) - : IRequestHandler -{ - public async Task Handle(RequestSelectedAdscContractCommand request, CancellationToken cancellationToken) - { - if (request.ReportingInterval < AdscContract.MinimumReportingInterval) - throw new ArgumentOutOfRangeException( - nameof(request.ReportingInterval), - request.ReportingInterval, - $"Reporting interval must be {AdscContract.MinimumReportingInterval.TotalSeconds} seconds or more"); - - logger.Information( - "Requesting selected ADS-C contract with {Callsign} from {StationId} (Interval: {ReportingInterval})", - request.Callsign, - request.StationId, - request.ReportingInterval); - - var client = await clientManager.GetAcarsClientForStation(request.StationId, cancellationToken); - await client.RequestPeriodicAdscContract(request.Callsign, request.ReportingInterval, cancellationToken); - - // The selected contract ends at a fixed time after the request is sent - var configuration = await clientManager.GetConfigurationForStation(request.StationId, cancellationToken); - var ends = clock.UtcNow() + TimeSpan.FromMinutes(configuration.SelectedAdscContractDuration); - - var contractKey = new AdscContractKey(request.Callsign, request.StationId); - var contract = await adscContractRepository.Find(contractKey, cancellationToken); - if (contract is null) - { - contract = new AdscContract(request.Callsign, request.StationId); - await adscContractRepository.Add(contractKey, contract, cancellationToken); - } - - contract.RequestSelectedContract(request.ReportingInterval, ends); - contract.LogActivity(clock.UtcNow()); - - await mediator.Publish(new AdscContractChangedNotification(contract), cancellationToken); - } -} diff --git a/source/CPDLCServer/Handlers/SendConnectionRequestCommandHandler.cs b/source/CPDLCServer/Handlers/SendConnectionRequestCommandHandler.cs deleted file mode 100644 index 340681d..0000000 --- a/source/CPDLCServer/Handlers/SendConnectionRequestCommandHandler.cs +++ /dev/null @@ -1,45 +0,0 @@ -using CPDLCServer.Clients; -using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Services; -using MediatR; - -namespace CPDLCServer.Handlers; - -public class SendConnectionRequestCommandHandler( - IClientManager clientManager, - IMessageIdProvider messageIdProvider, - IClock clock, - ILogger logger) - : IRequestHandler -{ - public async Task Handle(SendConnectionRequestCommand request, CancellationToken cancellationToken) - { - var acarsClientId = await clientManager.FindAcarsClientId(request.StationId, cancellationToken); - if (acarsClientId is null) - throw new Exception($"No ACARS client is configured for {request.StationId}"); - - var client = await clientManager.GetAcarsClient(acarsClientId, cancellationToken); - - var messageId = await messageIdProvider.GetNextMessageId( - acarsClientId, - request.Callsign, - cancellationToken); - - // This is a system message. It does not start a dialogue. - var uplinkMessage = new UplinkMessage( - Guid.Empty, - messageId, - null, - request.Callsign, - "SYSTEM", - CpdlcUplinkResponseType.NoResponse, - AlertType.None, - $"CONNECTION REQUESTED @{request.StationId}@", - clock.UtcNow()); - - await client.Send(uplinkMessage, cancellationToken); - logger.Information("Sent connection request for {StationId} to {Callsign}", request.StationId, request.Callsign); - } -} diff --git a/source/CPDLCServer/Infrastructure/ApiKeyHasher.cs b/source/CPDLCServer/Infrastructure/ApiKeyHasher.cs deleted file mode 100644 index 505f219..0000000 --- a/source/CPDLCServer/Infrastructure/ApiKeyHasher.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Security.Cryptography; -using System.Text; - -namespace CPDLCServer.Infrastructure; - -public static class ApiKeyHasher -{ - public static string HashApiKey(string apiKey) - { - var hashBytes = SHA256.HashData(Encoding.UTF8.GetBytes(apiKey)); - return Convert.ToBase64String(hashBytes); - } -} diff --git a/source/CPDLCServer/Infrastructure/ConfigurationExtensionMethods.cs b/source/CPDLCServer/Infrastructure/ConfigurationExtensionMethods.cs new file mode 100644 index 0000000..2766b5b --- /dev/null +++ b/source/CPDLCServer/Infrastructure/ConfigurationExtensionMethods.cs @@ -0,0 +1,9 @@ +namespace CPDLCServer.Infrastructure; + +public static class ConfigurationExtensionMethods +{ + public static string GetRequiredValue(this IConfiguration configuration, string key) + { + return configuration[key] ?? throw new Exception($"{key} is required but was not configured."); + } +} diff --git a/source/CPDLCServer/Infrastructure/InfrastructureServiceCollectionExtensions.cs b/source/CPDLCServer/Infrastructure/InfrastructureServiceCollectionExtensions.cs new file mode 100644 index 0000000..0fc584b --- /dev/null +++ b/source/CPDLCServer/Infrastructure/InfrastructureServiceCollectionExtensions.cs @@ -0,0 +1,17 @@ +namespace CPDLCServer.Infrastructure; + +public static class InfrastructureServiceCollectionExtensions +{ + public static IServiceCollection AddInfrastructure(this IServiceCollection services) + { + // The start time is recorded now, when the server starts, and not when the service is first used + var clock = new SystemClock(); + services.AddSingleton(clock); + services.AddSingleton(new ServerStartTime(clock.UtcNow())); + + services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(Program).Assembly)); + services.AddSingleton(); + + return services; + } +} diff --git a/source/CPDLCServer/Extensions/SemaphoreSlimExtensionMethods.cs b/source/CPDLCServer/Infrastructure/SemaphoreSlimExtensionMethods.cs similarity index 92% rename from source/CPDLCServer/Extensions/SemaphoreSlimExtensionMethods.cs rename to source/CPDLCServer/Infrastructure/SemaphoreSlimExtensionMethods.cs index e880504..069b964 100644 --- a/source/CPDLCServer/Extensions/SemaphoreSlimExtensionMethods.cs +++ b/source/CPDLCServer/Infrastructure/SemaphoreSlimExtensionMethods.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Extensions; +namespace CPDLCServer.Infrastructure; public static class SemaphoreSlimExtensionMethods { diff --git a/source/CPDLCServer/Infrastructure/ServerStartTime.cs b/source/CPDLCServer/Infrastructure/ServerStartTime.cs new file mode 100644 index 0000000..26365f5 --- /dev/null +++ b/source/CPDLCServer/Infrastructure/ServerStartTime.cs @@ -0,0 +1,12 @@ +namespace CPDLCServer.Infrastructure; + +/// +/// The time that the server started. +/// The server does not update the saved data while it is stopped, so a timeout applies only when the server has been +/// online for longer than the timeout. +/// +/// +public class ServerStartTime(DateTimeOffset started) +{ + public DateTimeOffset Started { get; } = started; +} diff --git a/source/CPDLCServer/Infrastructure/UnitOfWorkMediator.cs b/source/CPDLCServer/Infrastructure/UnitOfWorkMediator.cs new file mode 100644 index 0000000..3367e49 --- /dev/null +++ b/source/CPDLCServer/Infrastructure/UnitOfWorkMediator.cs @@ -0,0 +1,88 @@ +using CPDLCServer.Logging; +using CPDLCServer.Persistence; +using MediatR; +using Microsoft.EntityFrameworkCore; +using Serilog.Context; + +namespace CPDLCServer.Infrastructure; + +// The entry point for work that does not come from a handler: the hub, the ACARS connections and the background services. +// Each call runs in a new service scope, and commits the unit of work of that scope. +// Handlers use the IMediator of their own scope, so that nested requests and notifications are in the same unit of work. +public interface IUnitOfWorkMediator +{ + Task Send(IRequest request, CancellationToken cancellationToken = default); + Task Send(IRequest request, CancellationToken cancellationToken = default); + Task Publish(INotification notification, CancellationToken cancellationToken = default); +} + +// The units of work run at the same time. The database prevents conflicts: +// - Each changed entity has a version (concurrency token). If a different unit of work changed the entity after it was +// read, the commit fails. +// - Unique indexes prevent two units of work from adding the same entity. +// When the commit fails, the unit of work runs again in a new scope, so that it reads the new data. +// The messages to controllers and aircraft are sent only after a successful commit, so a failed attempt sends nothing. +public class UnitOfWorkMediator(IServiceScopeFactory serviceScopeFactory, ILogger logger) : IUnitOfWorkMediator +{ + const int MaxAttempts = 3; + + public async Task Send(IRequest request, CancellationToken cancellationToken = default) + { + await Run( + request.GetType(), + async mediator => + { + await mediator.Send(request, cancellationToken); + return true; + }, + cancellationToken); + } + + public async Task Send(IRequest request, CancellationToken cancellationToken = default) + { + return await Run(request.GetType(), mediator => mediator.Send(request, cancellationToken), cancellationToken); + } + + public async Task Publish(INotification notification, CancellationToken cancellationToken = default) + { + await Run( + notification.GetType(), + async mediator => + { + await mediator.Publish(notification, cancellationToken); + return true; + }, + cancellationToken); + } + + // The log entries of the unit of work get the area of the message. The nested messages are in the same area. + async Task Run(Type messageType, Func> action, CancellationToken cancellationToken) + { + using var _ = LogContext.PushProperty(LogArea.PropertyName, LogArea.ForType(messageType)); + + for (var attempt = 1; ; attempt++) + { + await using var scope = serviceScopeFactory.CreateAsyncScope(); + var mediator = scope.ServiceProvider.GetRequiredService(); + var unitOfWork = scope.ServiceProvider.GetRequiredService(); + + try + { + var result = await action(mediator); + await unitOfWork.Commit(cancellationToken); + + return result; + } + // DbUpdateConcurrencyException: a different unit of work changed or removed an entity. + // DbUpdateException: a different unit of work added an entity with the same unique key. + catch (DbUpdateException ex) when (attempt < MaxAttempts) + { + logger.Warning( + ex, + "Unit of work conflicted with a different unit of work (attempt {Attempt} of {MaxAttempts}), retrying", + attempt, + MaxAttempts); + } + } + } +} diff --git a/source/CPDLCServer/Logging/InMemoryLogBufferSink.cs b/source/CPDLCServer/Logging/InMemoryLogBufferSink.cs new file mode 100644 index 0000000..42fc05e --- /dev/null +++ b/source/CPDLCServer/Logging/InMemoryLogBufferSink.cs @@ -0,0 +1,52 @@ +using Serilog.Core; +using Serilog.Events; +using Serilog.Formatting.Display; + +namespace CPDLCServer.Logging; + +/// +/// A log sink that stores log events in-memory. +/// +public class InMemoryLogBufferSink(LogBuffer logBuffer) : ILogEventSink +{ + // The same text as the console output, without the timestamp, the level and the exception + readonly MessageTemplateTextFormatter _messageFormatter = new("{Message:lj}"); + + public void Emit(LogEvent logEvent) + { + using var writer = new StringWriter(); + _messageFormatter.Format(logEvent, writer); + + logBuffer.Add(new LogEntry( + Sequence: 0, // The LogBuffer sets the sequence number + Time: logEvent.Timestamp.ToString("HH:mm:ss"), + Level: logEvent.Level.ToString(), + LevelCode: LevelCode(logEvent.Level), + Area: StringProperty(logEvent, LogArea.PropertyName) ?? LogArea.System, + AcarsConnectionId: StringProperty(logEvent, LogArea.AcarsConnectionIdPropertyName), + Message: writer.ToString(), + Exception: logEvent.Exception?.ToString())); + } + + static string? StringProperty(LogEvent logEvent, string name) + { + return logEvent.Properties.TryGetValue(name, out var value) && value is ScalarValue { Value: string text } + ? text + : null; + } + + // The same codes as {Level:u3} in the console output + static string LevelCode(LogEventLevel level) + { + return level switch + { + LogEventLevel.Verbose => "VRB", + LogEventLevel.Debug => "DBG", + LogEventLevel.Information => "INF", + LogEventLevel.Warning => "WRN", + LogEventLevel.Error => "ERR", + LogEventLevel.Fatal => "FTL", + _ => level.ToString().ToUpperInvariant() + }; + } +} diff --git a/source/CPDLCServer/Logging/LogArea.cs b/source/CPDLCServer/Logging/LogArea.cs new file mode 100644 index 0000000..9775697 --- /dev/null +++ b/source/CPDLCServer/Logging/LogArea.cs @@ -0,0 +1,40 @@ +namespace CPDLCServer.Logging; + +/// +/// The part of the server that wrote a log entry. The Logs page can show only the entries of one area. +/// +public static class LogArea +{ + // The names of the log event properties + public const string PropertyName = "Area"; + public const string AcarsConnectionIdPropertyName = "AcarsConnectionId"; + + public const string Cpdlc = "CPDLC"; + public const string Adsc = "ADS-C"; + public const string Acars = "ACARS"; + public const string System = "System"; + + public static readonly string[] All = [Cpdlc, Adsc, Acars, System]; + + // The area of a request or a notification comes from its namespace + public static string ForType(Type type) + { + var typeNamespace = type.Namespace ?? string.Empty; + + if (IsIn(typeNamespace, "CPDLCServer.Cpdlc")) + return Cpdlc; + + if (IsIn(typeNamespace, "CPDLCServer.AdscContracts") || IsIn(typeNamespace, "CPDLCServer.VatsimStatus")) + return Adsc; + + if (IsIn(typeNamespace, "CPDLCServer.AcarsConnections")) + return Acars; + + return System; + } + + static bool IsIn(string typeNamespace, string areaNamespace) + { + return typeNamespace == areaNamespace || typeNamespace.StartsWith(areaNamespace + ".", StringComparison.Ordinal); + } +} diff --git a/source/CPDLCServer/Logging/LogBuffer.cs b/source/CPDLCServer/Logging/LogBuffer.cs new file mode 100644 index 0000000..e0410f2 --- /dev/null +++ b/source/CPDLCServer/Logging/LogBuffer.cs @@ -0,0 +1,70 @@ +using System.Threading.Channels; + +namespace CPDLCServer.Logging; + +/// +/// Keeps the most recent log entries in memory, and sends each new entry to the subscribers +/// +public class LogBuffer(int capacity = 1000) +{ + public int Capacity { get; } = capacity; + + readonly object _lock = new(); + readonly Queue _entries = new(); + readonly List> _subscribers = []; + long _nextSequence = 1; + + public void Add(LogEntry entry) + { + lock (_lock) + { + var sequencedEntry = entry with { Sequence = _nextSequence++ }; + + _entries.Enqueue(sequencedEntry); + if (_entries.Count > Capacity) + _entries.Dequeue(); + + foreach (var subscriber in _subscribers) + subscriber.Writer.TryWrite(sequencedEntry); + } + } + + /// + /// The subscription gets the recent entries, then each new entry. + /// A slow subscriber loses its oldest entries, so that it cannot use too much memory. + /// + public LogSubscription Subscribe() + { + lock (_lock) + { + var channel = Channel.CreateBounded(new BoundedChannelOptions(Capacity) + { + FullMode = BoundedChannelFullMode.DropOldest, + SingleReader = true + }); + + _subscribers.Add(channel); + + return new LogSubscription(_entries.ToArray(), channel.Reader, () => Unsubscribe(channel)); + } + } + + void Unsubscribe(Channel channel) + { + lock (_lock) + { + _subscribers.Remove(channel); + } + + channel.Writer.TryComplete(); + } +} + +public sealed class LogSubscription(LogEntry[] recentEntries, ChannelReader newEntries, Action unsubscribe) + : IDisposable +{ + public LogEntry[] RecentEntries { get; } = recentEntries; + public ChannelReader NewEntries { get; } = newEntries; + + public void Dispose() => unsubscribe(); +} diff --git a/source/CPDLCServer/Logging/LogEntry.cs b/source/CPDLCServer/Logging/LogEntry.cs new file mode 100644 index 0000000..01a52c6 --- /dev/null +++ b/source/CPDLCServer/Logging/LogEntry.cs @@ -0,0 +1,13 @@ +namespace CPDLCServer.Logging; + +// A log event, as the Logs page shows it. +// The sequence number increases by one for each entry, so that a client can ignore the entries that it already has. +public record LogEntry( + long Sequence, + string Time, + string Level, + string LevelCode, + string Area, + string? AcarsConnectionId, + string Message, + string? Exception); diff --git a/source/CPDLCServer/Logging/LogStreamEndpoint.cs b/source/CPDLCServer/Logging/LogStreamEndpoint.cs new file mode 100644 index 0000000..7fe7efc --- /dev/null +++ b/source/CPDLCServer/Logging/LogStreamEndpoint.cs @@ -0,0 +1,53 @@ +using System.Text.Json; +using Microsoft.AspNetCore.Http.Features; + +namespace CPDLCServer.Logging; + +// Sends the log entries to the Logs page as Server-Sent Events. +// First it sends the recent entries, then each new entry until the browser disconnects. +public static class LogStreamEndpoint +{ + static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); + + public static async Task Handle(HttpContext context, LogBuffer logBuffer, IHostApplicationLifetime lifetime) + { + // Stop the stream when the server stops, so that the shutdown does not wait for the browser + using var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource( + context.RequestAborted, + lifetime.ApplicationStopping); + var cancellationToken = cancellationTokenSource.Token; + + context.Response.ContentType = "text/event-stream"; + context.Response.Headers.CacheControl = "no-cache"; + context.Features.Get()?.DisableBuffering(); + + using var subscription = logBuffer.Subscribe(); + + try + { + foreach (var entry in subscription.RecentEntries) + { + await WriteEvent(context.Response, entry, cancellationToken); + } + + await context.Response.Body.FlushAsync(cancellationToken); + + await foreach (var entry in subscription.NewEntries.ReadAllAsync(cancellationToken)) + { + await WriteEvent(context.Response, entry, cancellationToken); + await context.Response.Body.FlushAsync(cancellationToken); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // The browser disconnected, or the server is stopping + } + } + + static async Task WriteEvent(HttpResponse response, LogEntry entry, CancellationToken cancellationToken) + { + // The JSON has no line breaks, so one data line holds the entry + var json = JsonSerializer.Serialize(entry, JsonOptions); + await response.WriteAsync($"id: {entry.Sequence}\ndata: {json}\n\n", cancellationToken); + } +} diff --git a/source/CPDLCServer/Messages/CheckLostAircraftConnectionsRequest.cs b/source/CPDLCServer/Messages/CheckLostAircraftConnectionsRequest.cs deleted file mode 100644 index d6ec935..0000000 --- a/source/CPDLCServer/Messages/CheckLostAircraftConnectionsRequest.cs +++ /dev/null @@ -1,5 +0,0 @@ -using MediatR; - -namespace CPDLCServer.Messages; - -public record CheckLostAircraftConnectionsRequest(TimeSpan ConnectionTimeout) : IRequest; diff --git a/source/CPDLCServer/Messages/EndExpiredAdscContractsRequest.cs b/source/CPDLCServer/Messages/EndExpiredAdscContractsRequest.cs deleted file mode 100644 index 4f4eada..0000000 --- a/source/CPDLCServer/Messages/EndExpiredAdscContractsRequest.cs +++ /dev/null @@ -1,5 +0,0 @@ -using MediatR; - -namespace CPDLCServer.Messages; - -public record EndExpiredAdscContractsRequest(TimeSpan ContractTimeout) : IRequest; diff --git a/source/CPDLCServer/Messages/GetAtsuSettingsRequest.cs b/source/CPDLCServer/Messages/GetAtsuSettingsRequest.cs deleted file mode 100644 index 2165019..0000000 --- a/source/CPDLCServer/Messages/GetAtsuSettingsRequest.cs +++ /dev/null @@ -1,6 +0,0 @@ -using CPDLCServer.Contracts; -using MediatR; - -namespace CPDLCServer.Messages; - -public record GetAtsuSettingsRequest(string StationId) : IRequest; diff --git a/source/CPDLCServer/Messages/ProduceVatsimAdscReportsRequest.cs b/source/CPDLCServer/Messages/ProduceVatsimAdscReportsRequest.cs deleted file mode 100644 index 7236c67..0000000 --- a/source/CPDLCServer/Messages/ProduceVatsimAdscReportsRequest.cs +++ /dev/null @@ -1,6 +0,0 @@ -using MediatR; - -namespace CPDLCServer.Messages; - -// Makes the ADS-C reports that are due from the latest VATSIM status data -public record ProduceVatsimAdscReportsRequest : IRequest; diff --git a/source/CPDLCServer/Messages/RefreshAcarsCallsignsRequest.cs b/source/CPDLCServer/Messages/RefreshAcarsCallsignsRequest.cs deleted file mode 100644 index ec7a3dd..0000000 --- a/source/CPDLCServer/Messages/RefreshAcarsCallsignsRequest.cs +++ /dev/null @@ -1,5 +0,0 @@ -using MediatR; - -namespace CPDLCServer.Messages; - -public record RefreshAcarsCallsignsRequest(string AcarsClientId) : IRequest; diff --git a/source/CPDLCServer/Messages/RequestDefaultAdscContractCommand.cs b/source/CPDLCServer/Messages/RequestDefaultAdscContractCommand.cs deleted file mode 100644 index e6fe1ff..0000000 --- a/source/CPDLCServer/Messages/RequestDefaultAdscContractCommand.cs +++ /dev/null @@ -1,8 +0,0 @@ -using MediatR; - -namespace CPDLCServer.Messages; - -public record RequestDefaultAdscContractCommand( - string StationId, - string Callsign) - : IRequest; diff --git a/source/CPDLCServer/Messages/RequestSelectedAdscContractCommand.cs b/source/CPDLCServer/Messages/RequestSelectedAdscContractCommand.cs deleted file mode 100644 index 02f6a47..0000000 --- a/source/CPDLCServer/Messages/RequestSelectedAdscContractCommand.cs +++ /dev/null @@ -1,9 +0,0 @@ -using MediatR; - -namespace CPDLCServer.Messages; - -public record RequestSelectedAdscContractCommand( - string StationId, - string Callsign, - TimeSpan ReportingInterval) - : IRequest; diff --git a/source/CPDLCServer/Messages/TerminateConnectionRequest.cs b/source/CPDLCServer/Messages/TerminateConnectionRequest.cs deleted file mode 100644 index a41aacb..0000000 --- a/source/CPDLCServer/Messages/TerminateConnectionRequest.cs +++ /dev/null @@ -1,7 +0,0 @@ -using MediatR; - -namespace CPDLCServer.Messages; - -public record TerminateConnectionRequest( - string Callsign, - string AcarsClientId) : IRequest; diff --git a/source/CPDLCServer/Model/AircraftAdscReport.cs b/source/CPDLCServer/Model/AircraftAdscReport.cs deleted file mode 100644 index 25a8688..0000000 --- a/source/CPDLCServer/Model/AircraftAdscReport.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace CPDLCServer.Model; - -// An ADS-C report from an aircraft, and the ATSU that received it -public record AircraftAdscReport( - string Callsign, - string StationId, - AdscReport Report, - DateTimeOffset Received); diff --git a/source/CPDLCServer/Model/DownlinkMessage.cs b/source/CPDLCServer/Model/DownlinkMessage.cs deleted file mode 100644 index b7c80f9..0000000 --- a/source/CPDLCServer/Model/DownlinkMessage.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace CPDLCServer.Model; - -public class DownlinkMessage( - Guid dialogueId, - int messageId, - int? messageReference, - string sender, - CpdlcDownlinkResponseType responseType, - AlertType alertType, - string content, - DateTimeOffset received) - : ICpdlcMessage -{ - public Guid DialogueId { get; } = dialogueId; - public int MessageId { get; } = messageId; - public int? MessageReference { get; } = messageReference; - public string Sender { get; } = sender; - public CpdlcDownlinkResponseType ResponseType { get; } = responseType; - public AlertType AlertType { get; } = alertType; - public string Content { get; } = content; - public DateTimeOffset Received { get; } = received; - - public DateTimeOffset? Closed { get; private set; } = responseType == CpdlcDownlinkResponseType.NoResponse ? received : null; // Downlink messages requiring no response are self-closing - public bool IsClosed => Closed is not null; - - public DateTimeOffset? Acknowledged { get; private set; } - public bool IsAcknowledged => Acknowledged is not null; - - public bool IsControllerLate { get; set; } - - DateTimeOffset ICpdlcMessage.Time => Received; - - public void Close(DateTimeOffset time) - { - Closed = time; - IsControllerLate = false; - } - - public void Acknowledge(DateTimeOffset now) - { - Acknowledged = now; - } -} diff --git a/source/CPDLCServer/Model/ICpdlcMessage.cs b/source/CPDLCServer/Model/ICpdlcMessage.cs deleted file mode 100644 index 03603a7..0000000 --- a/source/CPDLCServer/Model/ICpdlcMessage.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace CPDLCServer.Model; - -public interface ICpdlcMessage -{ - public Guid DialogueId { get; } - public int MessageId { get; } - public int? MessageReference { get; } - AlertType AlertType { get; } - DateTimeOffset Time { get; } - - DateTimeOffset? Closed { get; } - bool IsClosed { get; } - - DateTimeOffset? Acknowledged { get; } - bool IsAcknowledged { get; } - - void Close(DateTimeOffset time); -} \ No newline at end of file diff --git a/source/CPDLCServer/Model/UplinkMessage.cs b/source/CPDLCServer/Model/UplinkMessage.cs deleted file mode 100644 index c58f0a9..0000000 --- a/source/CPDLCServer/Model/UplinkMessage.cs +++ /dev/null @@ -1,49 +0,0 @@ -namespace CPDLCServer.Model; - -// TODO: Separate formatted and plaintext contents. - -public class UplinkMessage( - Guid dialogueId, - int messageId, - int? messageReference, - string recipient, - string senderCallsign, - CpdlcUplinkResponseType responseType, - AlertType alertType, - string content, - DateTimeOffset sent) - : ICpdlcMessage -{ - public Guid DialogueId { get; } = dialogueId; - public int MessageId { get; } = messageId; - public int? MessageReference { get; } = messageReference; - public string Recipient { get; } = recipient; - public string SenderCallsign { get; } = senderCallsign; - public CpdlcUplinkResponseType ResponseType { get; } = responseType; - public AlertType AlertType { get; } = alertType; - public string Content { get; } = content; - public DateTimeOffset Sent { get; } = sent; - public DateTimeOffset? Closed { get; private set; } = responseType == CpdlcUplinkResponseType.NoResponse ? sent : null; // Uplink messages requiring no response are self-closing - public bool IsClosed => Closed is not null; - public bool ClosedManually { get; private set; } - - // Uplinks are automatically acknowledged - DateTimeOffset? ICpdlcMessage.Acknowledged => Sent; - public bool IsAcknowledged => true; - - // public bool CanAction { get; set; } - // public bool Actioned { get; set; } - public bool IsPilotLate { get; set; } - public bool IsTransmissionFailed { get; set; } - - DateTimeOffset ICpdlcMessage.Time => Sent; - - public void Close(DateTimeOffset time, bool manual = false) - { - Closed = time; - ClosedManually = manual; - IsPilotLate = false; - } - - void ICpdlcMessage.Close(DateTimeOffset time) => Close(time, false); -} \ No newline at end of file diff --git a/source/CPDLCServer/Pages/Adsc/Index.cshtml b/source/CPDLCServer/Pages/Adsc/Index.cshtml deleted file mode 100644 index c56ffa0..0000000 --- a/source/CPDLCServer/Pages/Adsc/Index.cshtml +++ /dev/null @@ -1,168 +0,0 @@ -@page "/adsc" -@using CPDLCServer.Model -@model CPDLCServer.Pages.Dashboard.Adsc.IndexModel -@{ - ViewData["Title"] = "ADS-C"; - - string FormatInterval(TimeSpan? interval) => interval is null ? "-" : $"{interval.Value.TotalMinutes:0.#} min"; - - string GetStateBadgeClass(AdscContractState? state) => state switch - { - AdscContractState.Sent => "bg-info", - AdscContractState.Accepted => "bg-success", - AdscContractState.Rejected => "bg-danger", - _ => "bg-light text-dark" - }; -} - - - -

ADS-C

- -
-
-
Contracts
-
-
- @if (Model.Contracts.Length == 0) - { -

No ADS-C contracts.

- } - else - { -
- - - - - - - - - - - - - - - - @foreach (var contract in Model.Contracts) - { - - - - - - - - - - - - } - -
CallsignATSU CodeCurrent IntervalDefaultSelected IntervalSelectedSelected EndsDemandReport Source
@contract.Callsign@contract.StationId@FormatInterval(contract.ReportingInterval)@(contract.DefaultContractState?.ToString() ?? "-")@FormatInterval(contract.SelectedReportingInterval)@(contract.SelectedContractState?.ToString() ?? "-")@(contract.SelectedContractEnds?.ToString("yyyy-MM-dd HH:mm:ss") ?? "-")@(contract.DemandContractState?.ToString() ?? "-")@(Model.ReportSources.TryGetValue(contract.Callsign, out var source) ? source.ToString() : "-")
-
- } -
-
- -
-
-
Message Log
-
-
- @if (Model.LogEntries.Length == 0) - { -

No ADS-C messages.

- } - else - { -
- - - - - - - - - - - - - @foreach (var entry in Model.LogEntries) - { - - - - - - - - - } - -
TimestampNetworkDirATSU CodeCallsignPacket
@entry.Time.ToString("yyyy-MM-dd HH:mm:ss")@entry.AcarsClientId@(entry.Direction == AdscMessageDirection.Uplink ? "↑" : "↓")@entry.StationId@entry.Callsign@entry.Packet
-
- } -
-
- -@if (Model.TotalPages > 1) -{ - -} diff --git a/source/CPDLCServer/Pages/Atsu/Index.cshtml b/source/CPDLCServer/Pages/Atsu/Index.cshtml deleted file mode 100644 index 75d8142..0000000 --- a/source/CPDLCServer/Pages/Atsu/Index.cshtml +++ /dev/null @@ -1,55 +0,0 @@ -@page "/atsu/{stationId}" -@model CPDLCServer.Pages.Dashboard.Atsu.IndexModel -@{ - ViewData["Title"] = $"ATSU {Model.StationId}"; -} - - - -

ATSU: @Model.StationId

- -@if (Model.Controllers.Length > 0) -{ -
-
-
Active Controllers
-
-
-
- - - - - - - - - @foreach (var controller in Model.Controllers) - { - - - - - } - -
CallsignConnection ID
@controller.Callsign@controller.ConnectionId
-
-
-
-} -else -{ -
No active controllers at this ATSU.
-} - -

Messages

- -
- -
diff --git a/source/CPDLCServer/Pages/Connections/Index.cshtml b/source/CPDLCServer/Pages/Connections/Index.cshtml deleted file mode 100644 index 782efa2..0000000 --- a/source/CPDLCServer/Pages/Connections/Index.cshtml +++ /dev/null @@ -1,96 +0,0 @@ -@page "/connections" -@model CPDLCServer.Pages.Dashboard.Connections.IndexModel -@{ - ViewData["Title"] = "Connections"; -} - - - -

Connections

- -
-
-
-
-
ATC Connections
-
-
- @if (Model.Controllers.Length == 0) - { -

No ATC connections.

- } - else - { -
- - - - - - - - - - @foreach (var controller in Model.Controllers) - { - - - - - - } - -
CallsignATSU CodeConnection ID
@controller.Callsign@controller.StationId@controller.ConnectionId
-
- } -
-
-
- -
-
-
-
Pilot Connections
-
-
- @if (Model.Aircraft.Length == 0) - { -

No pilot connections.

- } - else - { -
- - - - - - - - - - - - @foreach (var aircraft in Model.Aircraft) - { - - - - - - - - } - -
CallsignATSU CodeData AuthorityACARS NetworkLast Seen
@aircraft.Callsign@aircraft.StationId@aircraft.DataAuthorityState@aircraft.AcarsClientId@aircraft.LastSeen.ToString("yyyy-MM-dd HH:mm:ss")
-
- } -
-
-
-
diff --git a/source/CPDLCServer/Pages/Connections/Index.cshtml.cs b/source/CPDLCServer/Pages/Connections/Index.cshtml.cs deleted file mode 100644 index 5fc4575..0000000 --- a/source/CPDLCServer/Pages/Connections/Index.cshtml.cs +++ /dev/null @@ -1,28 +0,0 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using Microsoft.AspNetCore.Mvc.RazorPages; - -namespace CPDLCServer.Pages.Dashboard.Connections; - -public class IndexModel : PageModel -{ - private readonly IControllerRepository _controllerRepository; - private readonly IAircraftRepository _aircraftRepository; - - public IndexModel( - IControllerRepository controllerRepository, - IAircraftRepository aircraftRepository) - { - _controllerRepository = controllerRepository; - _aircraftRepository = aircraftRepository; - } - - public ControllerInfo[] Controllers { get; private set; } = []; - public AircraftConnection[] Aircraft { get; private set; } = []; - - public async Task OnGetAsync(CancellationToken cancellationToken) - { - Controllers = await _controllerRepository.All(cancellationToken); - Aircraft = await _aircraftRepository.All(cancellationToken); - } -} diff --git a/source/CPDLCServer/Pages/Dialogue/Index.cshtml b/source/CPDLCServer/Pages/Dialogue/Index.cshtml deleted file mode 100644 index 97701af..0000000 --- a/source/CPDLCServer/Pages/Dialogue/Index.cshtml +++ /dev/null @@ -1,53 +0,0 @@ -@page "/dialogue/{id:guid}" -@model CPDLCServer.Pages.Dashboard.Dialogue.IndexModel -@{ - ViewData["Title"] = $"Dialogue {Model.Dialogue?.Id.ToString()[..8]}..."; -} - - - -
-

Dialogue

- - @(Model.Dialogue?.IsClosed == true ? "Closed" : "Open") - -
- -
-
-
-
Dialogue ID
-
@Model.Dialogue?.Id
- -
Aircraft
-
@Model.Dialogue?.AircraftCallsign
- -
ATSU
-
@Model.StationId
- -
ACARS Network
-
@Model.AcarsNetwork
- -
Opened
-
@Model.Dialogue?.Opened.ToString("yyyy-MM-dd HH:mm:ss")
- - @if (Model.Dialogue?.IsClosed == true) - { -
Closed
-
@Model.Dialogue?.Closed?.ToString("yyyy-MM-dd HH:mm:ss")
- } -
-
-
- -

Messages

- -
- -
diff --git a/source/CPDLCServer/Pages/Index.cshtml b/source/CPDLCServer/Pages/Index.cshtml deleted file mode 100644 index 3e76e7d..0000000 --- a/source/CPDLCServer/Pages/Index.cshtml +++ /dev/null @@ -1,53 +0,0 @@ -@page "/" -@model CPDLCServer.Pages.Dashboard.IndexModel -@{ - ViewData["Title"] = "CPDLC Server"; -} - -

Dashboard

- - diff --git a/source/CPDLCServer/Pages/Index.cshtml.cs b/source/CPDLCServer/Pages/Index.cshtml.cs deleted file mode 100644 index c4458eb..0000000 --- a/source/CPDLCServer/Pages/Index.cshtml.cs +++ /dev/null @@ -1,38 +0,0 @@ -using CPDLCServer.Persistence; -using Microsoft.AspNetCore.Mvc.RazorPages; - -namespace CPDLCServer.Pages.Dashboard; - -public class IndexModel : PageModel -{ - private readonly IControllerRepository _controllerRepository; - private readonly IAircraftRepository _aircraftRepository; - private readonly IDialogueRepository _dialogueRepository; - - public IndexModel( - IControllerRepository controllerRepository, - IAircraftRepository aircraftRepository, - IDialogueRepository dialogueRepository) - { - _controllerRepository = controllerRepository; - _aircraftRepository = aircraftRepository; - _dialogueRepository = dialogueRepository; - } - - public int AtcConnectionCount { get; private set; } - public int PilotConnectionCount { get; private set; } - public int TotalMessageCount { get; private set; } - public int OpenDialogueCount { get; private set; } - - public async Task OnGetAsync(CancellationToken cancellationToken) - { - var controllers = await _controllerRepository.All(cancellationToken); - var aircraft = await _aircraftRepository.All(cancellationToken); - var dialogues = await _dialogueRepository.All(cancellationToken); - - AtcConnectionCount = controllers.Length; - PilotConnectionCount = aircraft.Length; - TotalMessageCount = dialogues.Sum(d => d.Messages.Count); - OpenDialogueCount = dialogues.Count(d => !d.IsClosed); - } -} diff --git a/source/CPDLCServer/Pages/Messages/Index.cshtml b/source/CPDLCServer/Pages/Messages/Index.cshtml deleted file mode 100644 index dc6584b..0000000 --- a/source/CPDLCServer/Pages/Messages/Index.cshtml +++ /dev/null @@ -1,71 +0,0 @@ -@page "/messages" -@model CPDLCServer.Pages.Dashboard.Messages.IndexModel -@{ - ViewData["Title"] = "Messages"; -} - - - -

Messages

- -
- -
- -@if (Model.TotalPages > 1) -{ - -} diff --git a/source/CPDLCServer/Pages/Messages/Index.cshtml.cs b/source/CPDLCServer/Pages/Messages/Index.cshtml.cs deleted file mode 100644 index a77271d..0000000 --- a/source/CPDLCServer/Pages/Messages/Index.cshtml.cs +++ /dev/null @@ -1,88 +0,0 @@ -using CPDLCServer.Model; -using CPDLCServer.Pages.ViewModels; -using CPDLCServer.Persistence; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.RazorPages; - -namespace CPDLCServer.Pages.Dashboard.Messages; - -public class IndexModel : PageModel -{ - private readonly IDialogueRepository _dialogueRepository; - private readonly IAircraftRepository _aircraftRepository; - private const int PageSize = 50; - - public IndexModel( - IDialogueRepository dialogueRepository, - IAircraftRepository aircraftRepository) - { - _dialogueRepository = dialogueRepository; - _aircraftRepository = aircraftRepository; - } - - [BindProperty(SupportsGet = true)] - public int PageNumber { get; set; } = 1; - - public List Messages { get; private set; } = []; - public int TotalPages { get; private set; } - public int CurrentPage => PageNumber; - - public async Task OnGetAsync(CancellationToken cancellationToken) - { - var dialogues = await _dialogueRepository.All(cancellationToken); - var aircraft = await _aircraftRepository.All(cancellationToken); - var aircraftLookup = aircraft.ToDictionary(a => a.Callsign, a => a); - - var allMessages = dialogues - .SelectMany(d => d.Messages.Select(m => ToViewModel(d, m, aircraftLookup))) - .OrderByDescending(m => m.Timestamp) - .ToList(); - - TotalPages = (int)Math.Ceiling(allMessages.Count / (double)PageSize); - PageNumber = Math.Clamp(PageNumber, 1, Math.Max(1, TotalPages)); - - Messages = allMessages - .Skip((PageNumber - 1) * PageSize) - .Take(PageSize) - .ToList(); - } - - public static MessageRowViewModel ToViewModel( - Model.Dialogue dialogue, - ICpdlcMessage message, - Dictionary aircraftLookup) - { - var aircraft = aircraftLookup.GetValueOrDefault(dialogue.AircraftCallsign); - var acarsNetwork = aircraft?.AcarsClientId ?? "Unknown"; - var stationId = aircraft?.StationId ?? "Unknown"; - - return message switch - { - UplinkMessage uplink => new MessageRowViewModel( - DialogueId: dialogue.Id, - Timestamp: uplink.Sent, - AcarsNetwork: acarsNetwork, - IsUplink: true, - Sender: $"{stationId} ({uplink.SenderCallsign})", - Receiver: uplink.Recipient, - AlertType: uplink.AlertType.ToString(), - ResponseType: uplink.ResponseType.ToString(), - Content: uplink.Content, - IsClosed: uplink.IsClosed), - - DownlinkMessage downlink => new MessageRowViewModel( - DialogueId: dialogue.Id, - Timestamp: downlink.Received, - AcarsNetwork: acarsNetwork, - IsUplink: false, - Sender: downlink.Sender, - Receiver: stationId, - AlertType: downlink.AlertType.ToString(), - ResponseType: downlink.ResponseType.ToString(), - Content: downlink.Content, - IsClosed: downlink.IsClosed), - - _ => throw new InvalidOperationException("Unknown message type") - }; - } -} diff --git a/source/CPDLCServer/Pages/Pilot/Index.cshtml b/source/CPDLCServer/Pages/Pilot/Index.cshtml deleted file mode 100644 index 1570ff1..0000000 --- a/source/CPDLCServer/Pages/Pilot/Index.cshtml +++ /dev/null @@ -1,48 +0,0 @@ -@page "/pilot/{callsign}" -@model CPDLCServer.Pages.Dashboard.Pilot.IndexModel -@{ - ViewData["Title"] = $"Pilot {Model.Callsign}"; -} - - - -

Pilot: @Model.Callsign

- -@if (Model.Aircraft != null) -{ -
-
-
-
Callsign
-
@Model.Aircraft.Callsign
- -
ATSU
-
@Model.Aircraft.StationId
- -
ACARS Network
-
@Model.Aircraft.AcarsClientId
- -
Data Authority
-
@Model.Aircraft.DataAuthorityState
- -
Connection State
-
@Model.Aircraft.ConnectionState
- -
Last Seen
-
@Model.Aircraft.LastSeen.ToString("yyyy-MM-dd HH:mm:ss")
-
-
-
-} - -

Messages

- -
- -
diff --git a/source/CPDLCServer/Pages/Shared/_Layout.cshtml b/source/CPDLCServer/Pages/Shared/_Layout.cshtml deleted file mode 100644 index 145d41a..0000000 --- a/source/CPDLCServer/Pages/Shared/_Layout.cshtml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - @ViewData["Title"] - CPDLC Server - - - -
- -
-
-
- @RenderBody() -
-
- - - @await RenderSectionAsync("Scripts", required: false) - - - diff --git a/source/CPDLCServer/Pages/Shared/_MessageTable.cshtml b/source/CPDLCServer/Pages/Shared/_MessageTable.cshtml deleted file mode 100644 index 6f6d816..0000000 --- a/source/CPDLCServer/Pages/Shared/_MessageTable.cshtml +++ /dev/null @@ -1,52 +0,0 @@ -@model IEnumerable - -@{ - string GetAlertBadgeClass(string alertType) => alertType switch - { - "High" => "bg-danger", - "Medium" => "bg-warning text-dark", - "Low" => "bg-info", - _ => "bg-light text-dark" - }; -} - -
- - - - - - - - - - - - - - - - - @foreach (var msg in Model) - { - - - - - - - - - - - - - } - -
DialogueTimestampNetworkDirSenderReceiverAlertResponseContentState
@msg.DialogueId.ToString()[..8]...@msg.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")@msg.AcarsNetwork@(msg.IsUplink ? "↑" : "↓")@msg.Sender@msg.Receiver@msg.AlertType@msg.ResponseType@msg.Content@(msg.IsClosed ? "Closed" : "Open")
-
- -@if (!Model.Any()) -{ -

No messages found.

-} diff --git a/source/CPDLCServer/Pages/ViewModels/MessageRowViewModel.cs b/source/CPDLCServer/Pages/ViewModels/MessageRowViewModel.cs deleted file mode 100644 index f130cf9..0000000 --- a/source/CPDLCServer/Pages/ViewModels/MessageRowViewModel.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace CPDLCServer.Pages.ViewModels; - -public record MessageRowViewModel( - Guid DialogueId, - DateTimeOffset Timestamp, - string AcarsNetwork, - bool IsUplink, - string Sender, - string Receiver, - string AlertType, - string ResponseType, - string Content, - bool IsClosed); diff --git a/source/CPDLCServer/Pages/_ViewImports.cshtml b/source/CPDLCServer/Pages/_ViewImports.cshtml deleted file mode 100644 index 953d05a..0000000 --- a/source/CPDLCServer/Pages/_ViewImports.cshtml +++ /dev/null @@ -1,2 +0,0 @@ -@namespace CPDLCServer.Pages -@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers diff --git a/source/CPDLCServer/Persistence/CpdlcDbContext.cs b/source/CPDLCServer/Persistence/CpdlcDbContext.cs new file mode 100644 index 0000000..8e9fdd8 --- /dev/null +++ b/source/CPDLCServer/Persistence/CpdlcDbContext.cs @@ -0,0 +1,117 @@ +using CPDLCServer.AcarsConnections.ConnectionSettings; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Auth.Administrators; +using CPDLCServer.Auth.PluginTokens; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Settings; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Persistence; + +// The provider-specific contexts (SqliteCpdlcDbContext, PostgreSqlCpdlcDbContext) derive from this context, +// because EF Core keeps one set of migrations for each context type +public class CpdlcDbContext(DbContextOptions options) : DbContext(options) +{ + // A concurrency token on each entity that a unit of work can change. + // When two units of work change the same entity at the same time, the second commit fails, and the unit of work + // runs again with the new data (see UnitOfWorkMediator). + public const string VersionProperty = "Version"; + + public DbSet AircraftConnections => Set(); + public DbSet Dialogues => Set(); + public DbSet AdscContracts => Set(); + public DbSet AdscReports => Set(); + public DbSet MessageIdSequences => Set(); + public DbSet ServerSettings => Set(); + public DbSet AcarsConnections => Set(); + public DbSet Administrators => Set(); + public DbSet PluginTokens => Set(); + + protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) + { + // SQLite cannot compare or sort DateTimeOffset values in a query, so store them as UTC ticks + configurationBuilder.Properties().HaveConversion(); + configurationBuilder.Properties().HaveConversion(); + + // Store the enums as text, so that a change to the order of the members does not change the data + configurationBuilder.Properties().HaveConversion(); + configurationBuilder.Properties().HaveConversion(); + configurationBuilder.Properties().HaveConversion(); + configurationBuilder.Properties().HaveConversion(); + configurationBuilder.Properties().HaveConversion(); + configurationBuilder.Properties().HaveConversion(); + configurationBuilder.Properties().HaveConversion(); + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.ApplyConfiguration(new AircraftConnectionConfiguration()); + modelBuilder.ApplyConfiguration(new DialogueConfiguration()); + modelBuilder.ApplyConfiguration(new CpdlcMessageConfiguration()); + modelBuilder.ApplyConfiguration(new UplinkMessageConfiguration()); + modelBuilder.ApplyConfiguration(new DownlinkMessageConfiguration()); + modelBuilder.ApplyConfiguration(new AdscContractConfiguration()); + modelBuilder.ApplyConfiguration(new AircraftAdscReportConfiguration()); + modelBuilder.ApplyConfiguration(new MessageIdSequenceConfiguration()); + modelBuilder.ApplyConfiguration(new ServerSettingsConfiguration()); + modelBuilder.ApplyConfiguration(new AcarsConnectionSettingsConfiguration()); + modelBuilder.ApplyConfiguration(new AdministratorConfiguration()); + modelBuilder.ApplyConfiguration(new PluginTokenConfiguration()); + + // The messages have no version. A change to a message is a change to its dialogue (see SaveChangesAsync). + Type[] versionedEntityTypes = + [ + typeof(AircraftConnection), + typeof(Dialogue), + typeof(AdscContract), + typeof(AircraftAdscReport), + typeof(MessageIdSequence), + typeof(ServerSettings), + typeof(AcarsConnectionSettings), + typeof(Administrator) + ]; + + foreach (var entityType in versionedEntityTypes) + { + modelBuilder.Entity(entityType) + .Property(VersionProperty) + .IsConcurrencyToken(); + } + } + + public override Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default) + { + IncrementVersions(); + return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); + } + + // Increments the version of each changed entity. + // A dialogue is changed when one of its messages is added, changed or removed, so that two units of work cannot + // change the messages of the same dialogue at the same time. + void IncrementVersions() + { + ChangeTracker.DetectChanges(); + + var dialogueIdsWithChangedMessages = ChangeTracker.Entries() + .Where(e => e.State is EntityState.Added or EntityState.Modified or EntityState.Deleted) + .Select(e => e.Entity.DialogueId) + .ToHashSet(); + + var changedEntries = ChangeTracker.Entries() + .Where(e => e.Metadata.FindProperty(VersionProperty) is not null) + .Where(e => + e.State == EntityState.Modified || + (e.State == EntityState.Unchanged && e.Entity is Dialogue dialogue && dialogueIdsWithChangedMessages.Contains(dialogue.Id))) + .ToArray(); + + foreach (var entry in changedEntries) + { + var version = entry.Property(VersionProperty); + version.CurrentValue = (int)version.OriginalValue! + 1; + } + } +} diff --git a/source/CPDLCServer/Persistence/DatabaseProvider.cs b/source/CPDLCServer/Persistence/DatabaseProvider.cs new file mode 100644 index 0000000..891a87d --- /dev/null +++ b/source/CPDLCServer/Persistence/DatabaseProvider.cs @@ -0,0 +1,7 @@ +namespace CPDLCServer.Persistence; + +public enum DatabaseProvider +{ + Sqlite, + PostgreSql +} diff --git a/source/CPDLCServer/Persistence/IAdscReportRepository.cs b/source/CPDLCServer/Persistence/IAdscReportRepository.cs deleted file mode 100644 index d747265..0000000 --- a/source/CPDLCServer/Persistence/IAdscReportRepository.cs +++ /dev/null @@ -1,15 +0,0 @@ -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; - -// Holds the latest ADS-C report for each aircraft -public interface IAdscReportRepository -{ - // Stores the report, unless the repository has a newer report for the same aircraft. - // A report from Hoppie always replaces a report from VATSIM. - Task Add(AircraftAdscReport report, CancellationToken cancellationToken); - Task Find(string callsign, CancellationToken cancellationToken); - Task All(CancellationToken cancellationToken); - - Task RemoveOlderThan(DateTimeOffset cutoff, CancellationToken cancellationToken); -} diff --git a/source/CPDLCServer/Persistence/IDialogueRepository.cs b/source/CPDLCServer/Persistence/IDialogueRepository.cs deleted file mode 100644 index e201349..0000000 --- a/source/CPDLCServer/Persistence/IDialogueRepository.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Collections; -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; - -public interface IDialogueRepository -{ - Task Add(Dialogue dialogue, CancellationToken cancellationToken); - - Task FindOpenDialogueByUplink( - string aircraftCallsign, - int uplinkMessageId, - CancellationToken cancellationToken); - - Task FindById(Guid id, CancellationToken cancellationToken); - - Task All(CancellationToken cancellationToken); - - Task Remove(Dialogue dialogue, CancellationToken cancellationToken); -} diff --git a/source/CPDLCServer/Persistence/InMemoryAdscContractRepository.cs b/source/CPDLCServer/Persistence/InMemoryAdscContractRepository.cs deleted file mode 100644 index dbad12e..0000000 --- a/source/CPDLCServer/Persistence/InMemoryAdscContractRepository.cs +++ /dev/null @@ -1,46 +0,0 @@ -using CPDLCServer.Extensions; -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; - -public class InMemoryAdscContractRepository : IAdscContractRepository -{ - readonly SemaphoreSlim _semaphore = new(1, 1); - - private readonly Dictionary _contracts = new(); - - public async Task Add(AdscContractKey contractKey, AdscContract contract, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - _contracts[contractKey] = contract; - } - } - - public async Task Find(AdscContractKey contractKey, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - _contracts.TryGetValue(contractKey, out var contract); - return contract; - } - } - - public async Task All(CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - return _contracts - .Select(kvp => kvp.Value) - .ToArray(); - } - } - - public async Task Remove(AdscContractKey contractKey, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - return _contracts.Remove(contractKey); - } - } -} diff --git a/source/CPDLCServer/Persistence/InMemoryAdscReportRepository.cs b/source/CPDLCServer/Persistence/InMemoryAdscReportRepository.cs deleted file mode 100644 index 996ff90..0000000 --- a/source/CPDLCServer/Persistence/InMemoryAdscReportRepository.cs +++ /dev/null @@ -1,55 +0,0 @@ -using CPDLCServer.Extensions; -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; - -public class InMemoryAdscReportRepository : IAdscReportRepository -{ - readonly SemaphoreSlim _semaphore = new(1, 1); - - private readonly Dictionary _reports = new(); - - public async Task Add(AircraftAdscReport report, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - if (_reports.TryGetValue(report.Callsign, out var existing)) - { - // A report from Hoppie always replaces a report from VATSIM - var replacesVatsimReport = report.Report.Source == AdscReportSource.Hoppie && - existing.Report.Source == AdscReportSource.VATSIM; - - // An aircraft can report to more than one ATSU, so reports can arrive out of order - if (!replacesVatsimReport && existing.Report.Timestamp > report.Report.Timestamp) - return; - } - - _reports[report.Callsign] = report; - } - } - - public async Task Find(string callsign, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - return _reports.GetValueOrDefault(callsign); - } - } - - public async Task All(CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - return _reports.Values.ToArray(); - } - } - - public async Task RemoveOlderThan(DateTimeOffset cutoff, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - foreach (var report in _reports.Values.Where(r => r.Received < cutoff).ToArray()) - _reports.Remove(report.Callsign); - } - } -} diff --git a/source/CPDLCServer/Persistence/InMemoryAircraftRepository.cs b/source/CPDLCServer/Persistence/InMemoryAircraftRepository.cs deleted file mode 100644 index ecf08bf..0000000 --- a/source/CPDLCServer/Persistence/InMemoryAircraftRepository.cs +++ /dev/null @@ -1,46 +0,0 @@ -using CPDLCServer.Extensions; -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; - -public class InMemoryAircraftRepository : IAircraftRepository -{ - readonly SemaphoreSlim _semaphore = new(1, 1); - - private readonly Dictionary _connections = new(); - - public async Task Add(AircraftKey aircraftKey, AircraftConnection connection, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - _connections[aircraftKey] = connection; - } - } - - public async Task Find(AircraftKey aircraftKey, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - _connections.TryGetValue(aircraftKey, out var connection); - return connection; - } - } - - public async Task All(CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - return _connections - .Select(kvp => kvp.Value) - .ToArray(); - } - } - - public async Task Remove(AircraftKey aircraftKey, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - return _connections.Remove(aircraftKey); - } - } -} diff --git a/source/CPDLCServer/Persistence/InMemoryDialogueRepository.cs b/source/CPDLCServer/Persistence/InMemoryDialogueRepository.cs deleted file mode 100644 index 0b9d695..0000000 --- a/source/CPDLCServer/Persistence/InMemoryDialogueRepository.cs +++ /dev/null @@ -1,67 +0,0 @@ -using CPDLCServer.Extensions; -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; - -public class InMemoryDialogueRepository : IDialogueRepository -{ - readonly SemaphoreSlim _semaphore = new(1, 1); - - private readonly List _dialogues = new(); - - public async Task Add(Dialogue dialogue, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - _dialogues.Add(dialogue); - } - } - - public async Task FindOpenDialogueByUplink( - string aircraftCallsign, - int uplinkMessageId, - CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - // BUG: It's possible to have messageId collisions, since the server generates incrementing ids, and some - // aircraft have their own incrementing ids ticking along too. - // We need to remove this method, and re-factor how messages are correlated to Dialogues. - // Idea: - // Split into multiple streams: - // 1. ReplyToDownlink (DialogueId, MessageId) - // 2. CreateDialogueFromUplink (No params) - // 3. AddReplyToUplink (UplinkId), Hoppie doesn't track Dialogue IDs, so we need to look through open dialogues for an uplink with that ID. - // 4. CreateDialogueFromDownlink (DownlinkId) - return _dialogues - .FirstOrDefault(d => - d.AircraftCallsign == aircraftCallsign && - !d.IsClosed && - d.Messages.OfType().Any(m => m.MessageId == uplinkMessageId)); - } - } - - public async Task FindById(Guid id, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - return _dialogues.FirstOrDefault(d => d.Id == id); - } - } - - public async Task All(CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - return _dialogues.ToArray(); - } - } - - public async Task Remove(Dialogue dialogue, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - _dialogues.Remove(dialogue); - } - } -} diff --git a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121101342_InitialCreate.Designer.cs b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121101342_InitialCreate.Designer.cs new file mode 100644 index 0000000..171bb0c --- /dev/null +++ b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121101342_InitialCreate.Designer.cs @@ -0,0 +1,566 @@ +// +using System; +using System.Collections.Generic; +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace CPDLCServer.Persistence.Migrations.PostgreSql +{ + [DbContext(typeof(PostgreSqlCpdlcDbContext))] + [Migration("20261121101342_InitialCreate")] + partial class InitialCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.14") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("CPDLCServer.AcarsConnections.ConnectionSettings.AcarsConnectionSettings", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("DefaultAdscReportingInterval") + .HasColumnType("integer"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("EncryptedAuthenticationCode") + .IsRequired() + .HasColumnType("text"); + + b.Property("Motd") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("MotdDelaySeconds") + .HasColumnType("integer"); + + b.Property("Notes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("StationIdentifier") + .IsRequired() + .HasColumnType("text"); + + b.Property("Type") + .IsRequired() + .HasColumnType("text"); + + b.Property("Url") + .IsRequired() + .HasColumnType("text"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("StationIdentifier") + .IsUnique(); + + b.ToTable("AcarsConnections", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.AdscContracts.AdscContract", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("bigint"); + + b.Property("DefaultContractState") + .HasColumnType("text"); + + b.Property("DefaultReportingInterval") + .HasColumnType("bigint"); + + b.Property("DemandContractState") + .HasColumnType("text"); + + b.Property("LastActivity") + .HasColumnType("bigint"); + + b.Property("LastReportReceived") + .HasColumnType("bigint"); + + b.Property("ReportingInterval") + .HasColumnType("bigint"); + + b.Property("ReportingSource") + .HasColumnType("text"); + + b.Property("SelectedContractState") + .HasColumnType("text"); + + b.Property("SelectedReportingInterval") + .HasColumnType("bigint"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "StationId") + .IsUnique(); + + b.ToTable("AdscContracts", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.AdscContracts.Reports.AircraftAdscReport", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("Received") + .HasColumnType("bigint"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.ComplexProperty(typeof(Dictionary), "Report", "CPDLCServer.AdscContracts.Reports.AircraftAdscReport.Report#AdscReport", b1 => + { + b1.IsRequired(); + + b1.Property("Altitude") + .HasColumnType("integer") + .HasColumnName("Altitude"); + + b1.Property("Latitude") + .HasColumnType("double precision") + .HasColumnName("Latitude"); + + b1.Property("Longitude") + .HasColumnType("double precision") + .HasColumnName("Longitude"); + + b1.Property("Source") + .IsRequired() + .HasColumnType("text") + .HasColumnName("Source"); + + b1.Property("Timestamp") + .HasColumnType("bigint") + .HasColumnName("Timestamp"); + }); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "StationId") + .IsUnique(); + + b.ToTable("AdscReports", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Auth.Administrators.Administrator", b => + { + b.Property("Cid") + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("Added") + .HasColumnType("bigint"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("Cid"); + + b.ToTable("Administrators", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Auth.PluginTokens.PluginToken", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("Cid") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("Created") + .HasColumnType("bigint"); + + b.Property("Expires") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Cid"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("PluginTokens", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Connections.AircraftConnection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AcarsConnectionId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("ConnectionState") + .IsRequired() + .HasColumnType("text"); + + b.Property("DataAuthorityState") + .IsRequired() + .HasColumnType("text"); + + b.Property("DidSentNextDataAuthorityMessage") + .HasColumnType("boolean"); + + b.Property("ExpectedTransferTime") + .HasColumnType("bigint"); + + b.Property("LastSeen") + .HasColumnType("bigint"); + + b.Property("LogonAccepted") + .HasColumnType("bigint"); + + b.Property("LogonRequested") + .HasColumnType("bigint"); + + b.Property("NextDataAuthority") + .HasColumnType("text"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "AcarsConnectionId") + .IsUnique(); + + b.ToTable("AircraftConnections", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Acknowledged") + .HasColumnType("bigint"); + + b.Property("AlertType") + .IsRequired() + .HasColumnType("text"); + + b.Property("Closed") + .HasColumnType("bigint"); + + b.Property("DialogueId") + .HasColumnType("uuid"); + + b.Property("Direction") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("character varying(13)"); + + b.Property("MessageId") + .HasColumnType("integer"); + + b.Property("MessageReference") + .HasColumnType("integer"); + + b.Property("Position") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DialogueId"); + + b.ToTable("CpdlcMessages", (string)null); + + b.HasDiscriminator("Direction").HasValue("CpdlcMessage"); + + b.UseTphMappingStrategy(); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.Dialogue", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("AircraftCallsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("Archived") + .HasColumnType("bigint"); + + b.Property("Closed") + .HasColumnType("bigint"); + + b.Property("Opened") + .HasColumnType("bigint"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("Opened"); + + b.HasIndex("AircraftCallsign", "StationId"); + + b.ToTable("Dialogues", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Uplinks.MessageIdSequence", b => + { + b.Property("AcarsConnectionId") + .HasColumnType("text"); + + b.Property("Callsign") + .HasColumnType("text"); + + b.Property("LastMessageId") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("AcarsConnectionId", "Callsign"); + + b.ToTable("MessageIdSequences", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Settings.ServerSettings", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AdscContractTimeoutMinutes") + .HasColumnType("integer"); + + b.Property("AircraftConnectionTimeoutMinutes") + .HasColumnType("integer"); + + b.Property("BannerContentType") + .HasColumnType("text"); + + b.Property("BannerImage") + .HasColumnType("bytea"); + + b.Property("BannerVersion") + .HasColumnType("integer"); + + b.Property("ConnectivityCheckIntervalMinutes") + .HasColumnType("integer"); + + b.Property("DialogueRetentionHours") + .HasColumnType("integer"); + + b.Property("HandoffNotificationLeadTimeMinutes") + .HasColumnType("integer"); + + b.Property("Motd") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("OperatorName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PrivacyContact") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("ServerName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("VatsimStatusAllowNonEquippedAircraft") + .HasColumnType("boolean"); + + b.Property("VatsimStatusEnabled") + .HasColumnType("boolean"); + + b.Property("VatsimStatusPollingIntervalSeconds") + .HasColumnType("integer"); + + b.Property("VatsimStatusReportDelayMinutes") + .HasColumnType("integer"); + + b.Property("VatsimStatusUrl") + .IsRequired() + .HasColumnType("text"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.ToTable("ServerSettings", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Downlinks.DownlinkMessage", b => + { + b.HasBaseType("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage"); + + b.Property("Content") + .IsRequired() + .ValueGeneratedOnUpdateSometimes() + .HasColumnType("text") + .HasColumnName("Content"); + + b.Property("IsControllerLate") + .HasColumnType("boolean"); + + b.Property("Received") + .HasColumnType("bigint"); + + b.Property("ResponseType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("DownlinkResponseType"); + + b.Property("Sender") + .IsRequired() + .HasColumnType("text"); + + b.HasDiscriminator().HasValue("Downlink"); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Uplinks.UplinkMessage", b => + { + b.HasBaseType("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage"); + + b.Property("ClosedManually") + .HasColumnType("boolean"); + + b.Property("Content") + .IsRequired() + .ValueGeneratedOnUpdateSometimes() + .HasColumnType("text") + .HasColumnName("Content"); + + b.Property("DidTransmissionFail") + .HasColumnType("boolean"); + + b.Property("IsPilotLate") + .HasColumnType("boolean"); + + b.Property("Recipient") + .IsRequired() + .HasColumnType("text"); + + b.Property("ResponseType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("UplinkResponseType"); + + b.Property("SenderCallsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("Sent") + .HasColumnType("bigint"); + + b.HasDiscriminator().HasValue("Uplink"); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage", b => + { + b.HasOne("CPDLCServer.Cpdlc.Dialogues.Dialogue", null) + .WithMany("Messages") + .HasForeignKey("DialogueId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.Dialogue", b => + { + b.Navigation("Messages"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121101342_InitialCreate.cs b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121101342_InitialCreate.cs new file mode 100644 index 0000000..7e015ef --- /dev/null +++ b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121101342_InitialCreate.cs @@ -0,0 +1,320 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace CPDLCServer.Persistence.Migrations.PostgreSql +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AcarsConnections", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Type = table.Column(type: "text", nullable: false), + Enabled = table.Column(type: "boolean", nullable: false), + StationIdentifier = table.Column(type: "text", nullable: false), + Url = table.Column(type: "text", nullable: false), + EncryptedAuthenticationCode = table.Column(type: "text", nullable: false), + DefaultAdscReportingInterval = table.Column(type: "integer", nullable: false), + Motd = table.Column(type: "character varying(200)", maxLength: 200, nullable: true), + MotdDelaySeconds = table.Column(type: "integer", nullable: false), + Notes = table.Column(type: "character varying(2000)", maxLength: 2000, nullable: true), + Version = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AcarsConnections", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Administrators", + columns: table => new + { + Cid = table.Column(type: "character varying(16)", maxLength: 16, nullable: false), + Name = table.Column(type: "text", nullable: true), + Added = table.Column(type: "bigint", nullable: false), + Version = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Administrators", x => x.Cid); + }); + + migrationBuilder.CreateTable( + name: "AdscContracts", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Callsign = table.Column(type: "text", nullable: false), + StationId = table.Column(type: "text", nullable: false), + Created = table.Column(type: "bigint", nullable: false), + DefaultReportingInterval = table.Column(type: "bigint", nullable: false), + ReportingInterval = table.Column(type: "bigint", nullable: true), + DefaultContractState = table.Column(type: "text", nullable: true), + SelectedReportingInterval = table.Column(type: "bigint", nullable: true), + SelectedContractState = table.Column(type: "text", nullable: true), + DemandContractState = table.Column(type: "text", nullable: true), + LastActivity = table.Column(type: "bigint", nullable: false), + LastReportReceived = table.Column(type: "bigint", nullable: true), + ReportingSource = table.Column(type: "text", nullable: true), + Version = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AdscContracts", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AdscReports", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Callsign = table.Column(type: "text", nullable: false), + StationId = table.Column(type: "text", nullable: false), + Received = table.Column(type: "bigint", nullable: false), + Version = table.Column(type: "integer", nullable: false), + Altitude = table.Column(type: "integer", nullable: false), + Latitude = table.Column(type: "double precision", nullable: false), + Longitude = table.Column(type: "double precision", nullable: false), + Source = table.Column(type: "text", nullable: false), + Timestamp = table.Column(type: "bigint", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AdscReports", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AircraftConnections", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Callsign = table.Column(type: "text", nullable: false), + AcarsConnectionId = table.Column(type: "text", nullable: false), + StationId = table.Column(type: "text", nullable: false), + DataAuthorityState = table.Column(type: "text", nullable: false), + ConnectionState = table.Column(type: "text", nullable: false), + LogonRequested = table.Column(type: "bigint", nullable: false), + LogonAccepted = table.Column(type: "bigint", nullable: true), + LastSeen = table.Column(type: "bigint", nullable: false), + NextDataAuthority = table.Column(type: "text", nullable: true), + ExpectedTransferTime = table.Column(type: "bigint", nullable: true), + DidSentNextDataAuthorityMessage = table.Column(type: "boolean", nullable: false), + Version = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AircraftConnections", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Dialogues", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + AircraftCallsign = table.Column(type: "text", nullable: false), + StationId = table.Column(type: "text", nullable: false), + Opened = table.Column(type: "bigint", nullable: false), + Closed = table.Column(type: "bigint", nullable: true), + Archived = table.Column(type: "bigint", nullable: true), + Version = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Dialogues", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "MessageIdSequences", + columns: table => new + { + AcarsConnectionId = table.Column(type: "text", nullable: false), + Callsign = table.Column(type: "text", nullable: false), + LastMessageId = table.Column(type: "integer", nullable: false), + Version = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MessageIdSequences", x => new { x.AcarsConnectionId, x.Callsign }); + }); + + migrationBuilder.CreateTable( + name: "PluginTokens", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Cid = table.Column(type: "character varying(16)", maxLength: 16, nullable: false), + Name = table.Column(type: "text", nullable: false), + TokenHash = table.Column(type: "text", nullable: false), + Created = table.Column(type: "bigint", nullable: false), + Expires = table.Column(type: "bigint", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PluginTokens", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ServerSettings", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + OperatorName = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + PrivacyContact = table.Column(type: "character varying(256)", maxLength: 256, nullable: false), + ServerName = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + Motd = table.Column(type: "character varying(1000)", maxLength: 1000, nullable: true), + BannerImage = table.Column(type: "bytea", nullable: true), + BannerContentType = table.Column(type: "text", nullable: true), + BannerVersion = table.Column(type: "integer", nullable: false), + ConnectivityCheckIntervalMinutes = table.Column(type: "integer", nullable: false), + AircraftConnectionTimeoutMinutes = table.Column(type: "integer", nullable: false), + AdscContractTimeoutMinutes = table.Column(type: "integer", nullable: false), + DialogueRetentionHours = table.Column(type: "integer", nullable: false), + HandoffNotificationLeadTimeMinutes = table.Column(type: "integer", nullable: false), + VatsimStatusEnabled = table.Column(type: "boolean", nullable: false), + VatsimStatusUrl = table.Column(type: "text", nullable: false), + VatsimStatusPollingIntervalSeconds = table.Column(type: "integer", nullable: false), + VatsimStatusAllowNonEquippedAircraft = table.Column(type: "boolean", nullable: false), + VatsimStatusReportDelayMinutes = table.Column(type: "integer", nullable: false), + Version = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ServerSettings", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "CpdlcMessages", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + DialogueId = table.Column(type: "uuid", nullable: false), + MessageId = table.Column(type: "integer", nullable: false), + MessageReference = table.Column(type: "integer", nullable: true), + AlertType = table.Column(type: "text", nullable: false), + Position = table.Column(type: "integer", nullable: false), + Closed = table.Column(type: "bigint", nullable: true), + Acknowledged = table.Column(type: "bigint", nullable: true), + Direction = table.Column(type: "character varying(13)", maxLength: 13, nullable: false), + Sender = table.Column(type: "text", nullable: true), + DownlinkResponseType = table.Column(type: "text", nullable: true), + Content = table.Column(type: "text", nullable: true), + Received = table.Column(type: "bigint", nullable: true), + IsControllerLate = table.Column(type: "boolean", nullable: true), + Recipient = table.Column(type: "text", nullable: true), + SenderCallsign = table.Column(type: "text", nullable: true), + UplinkResponseType = table.Column(type: "text", nullable: true), + Sent = table.Column(type: "bigint", nullable: true), + ClosedManually = table.Column(type: "boolean", nullable: true), + IsPilotLate = table.Column(type: "boolean", nullable: true), + DidTransmissionFail = table.Column(type: "boolean", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_CpdlcMessages", x => x.Id); + table.ForeignKey( + name: "FK_CpdlcMessages_Dialogues_DialogueId", + column: x => x.DialogueId, + principalTable: "Dialogues", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_AcarsConnections_StationIdentifier", + table: "AcarsConnections", + column: "StationIdentifier", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_AdscContracts_Callsign_StationId", + table: "AdscContracts", + columns: new[] { "Callsign", "StationId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_AdscReports_Callsign_StationId", + table: "AdscReports", + columns: new[] { "Callsign", "StationId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_AircraftConnections_Callsign_AcarsConnectionId", + table: "AircraftConnections", + columns: new[] { "Callsign", "AcarsConnectionId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_CpdlcMessages_DialogueId", + table: "CpdlcMessages", + column: "DialogueId"); + + migrationBuilder.CreateIndex( + name: "IX_Dialogues_AircraftCallsign_StationId", + table: "Dialogues", + columns: new[] { "AircraftCallsign", "StationId" }); + + migrationBuilder.CreateIndex( + name: "IX_Dialogues_Opened", + table: "Dialogues", + column: "Opened"); + + migrationBuilder.CreateIndex( + name: "IX_PluginTokens_Cid", + table: "PluginTokens", + column: "Cid"); + + migrationBuilder.CreateIndex( + name: "IX_PluginTokens_TokenHash", + table: "PluginTokens", + column: "TokenHash", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AcarsConnections"); + + migrationBuilder.DropTable( + name: "Administrators"); + + migrationBuilder.DropTable( + name: "AdscContracts"); + + migrationBuilder.DropTable( + name: "AdscReports"); + + migrationBuilder.DropTable( + name: "AircraftConnections"); + + migrationBuilder.DropTable( + name: "CpdlcMessages"); + + migrationBuilder.DropTable( + name: "MessageIdSequences"); + + migrationBuilder.DropTable( + name: "PluginTokens"); + + migrationBuilder.DropTable( + name: "ServerSettings"); + + migrationBuilder.DropTable( + name: "Dialogues"); + } + } +} diff --git a/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs b/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs new file mode 100644 index 0000000..5bf6e57 --- /dev/null +++ b/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs @@ -0,0 +1,563 @@ +// +using System; +using System.Collections.Generic; +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace CPDLCServer.Persistence.Migrations.PostgreSql +{ + [DbContext(typeof(PostgreSqlCpdlcDbContext))] + partial class PostgreSqlCpdlcDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.14") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("CPDLCServer.AcarsConnections.ConnectionSettings.AcarsConnectionSettings", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("DefaultAdscReportingInterval") + .HasColumnType("integer"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("EncryptedAuthenticationCode") + .IsRequired() + .HasColumnType("text"); + + b.Property("Motd") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("MotdDelaySeconds") + .HasColumnType("integer"); + + b.Property("Notes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("StationIdentifier") + .IsRequired() + .HasColumnType("text"); + + b.Property("Type") + .IsRequired() + .HasColumnType("text"); + + b.Property("Url") + .IsRequired() + .HasColumnType("text"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("StationIdentifier") + .IsUnique(); + + b.ToTable("AcarsConnections", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.AdscContracts.AdscContract", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("bigint"); + + b.Property("DefaultContractState") + .HasColumnType("text"); + + b.Property("DefaultReportingInterval") + .HasColumnType("bigint"); + + b.Property("DemandContractState") + .HasColumnType("text"); + + b.Property("LastActivity") + .HasColumnType("bigint"); + + b.Property("LastReportReceived") + .HasColumnType("bigint"); + + b.Property("ReportingInterval") + .HasColumnType("bigint"); + + b.Property("ReportingSource") + .HasColumnType("text"); + + b.Property("SelectedContractState") + .HasColumnType("text"); + + b.Property("SelectedReportingInterval") + .HasColumnType("bigint"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "StationId") + .IsUnique(); + + b.ToTable("AdscContracts", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.AdscContracts.Reports.AircraftAdscReport", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("Received") + .HasColumnType("bigint"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.ComplexProperty(typeof(Dictionary), "Report", "CPDLCServer.AdscContracts.Reports.AircraftAdscReport.Report#AdscReport", b1 => + { + b1.IsRequired(); + + b1.Property("Altitude") + .HasColumnType("integer") + .HasColumnName("Altitude"); + + b1.Property("Latitude") + .HasColumnType("double precision") + .HasColumnName("Latitude"); + + b1.Property("Longitude") + .HasColumnType("double precision") + .HasColumnName("Longitude"); + + b1.Property("Source") + .IsRequired() + .HasColumnType("text") + .HasColumnName("Source"); + + b1.Property("Timestamp") + .HasColumnType("bigint") + .HasColumnName("Timestamp"); + }); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "StationId") + .IsUnique(); + + b.ToTable("AdscReports", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Auth.Administrators.Administrator", b => + { + b.Property("Cid") + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("Added") + .HasColumnType("bigint"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("Cid"); + + b.ToTable("Administrators", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Auth.PluginTokens.PluginToken", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("Cid") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("Created") + .HasColumnType("bigint"); + + b.Property("Expires") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Cid"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("PluginTokens", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Connections.AircraftConnection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AcarsConnectionId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("ConnectionState") + .IsRequired() + .HasColumnType("text"); + + b.Property("DataAuthorityState") + .IsRequired() + .HasColumnType("text"); + + b.Property("DidSentNextDataAuthorityMessage") + .HasColumnType("boolean"); + + b.Property("ExpectedTransferTime") + .HasColumnType("bigint"); + + b.Property("LastSeen") + .HasColumnType("bigint"); + + b.Property("LogonAccepted") + .HasColumnType("bigint"); + + b.Property("LogonRequested") + .HasColumnType("bigint"); + + b.Property("NextDataAuthority") + .HasColumnType("text"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "AcarsConnectionId") + .IsUnique(); + + b.ToTable("AircraftConnections", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Acknowledged") + .HasColumnType("bigint"); + + b.Property("AlertType") + .IsRequired() + .HasColumnType("text"); + + b.Property("Closed") + .HasColumnType("bigint"); + + b.Property("DialogueId") + .HasColumnType("uuid"); + + b.Property("Direction") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("character varying(13)"); + + b.Property("MessageId") + .HasColumnType("integer"); + + b.Property("MessageReference") + .HasColumnType("integer"); + + b.Property("Position") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DialogueId"); + + b.ToTable("CpdlcMessages", (string)null); + + b.HasDiscriminator("Direction").HasValue("CpdlcMessage"); + + b.UseTphMappingStrategy(); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.Dialogue", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("AircraftCallsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("Archived") + .HasColumnType("bigint"); + + b.Property("Closed") + .HasColumnType("bigint"); + + b.Property("Opened") + .HasColumnType("bigint"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("Opened"); + + b.HasIndex("AircraftCallsign", "StationId"); + + b.ToTable("Dialogues", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Uplinks.MessageIdSequence", b => + { + b.Property("AcarsConnectionId") + .HasColumnType("text"); + + b.Property("Callsign") + .HasColumnType("text"); + + b.Property("LastMessageId") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("AcarsConnectionId", "Callsign"); + + b.ToTable("MessageIdSequences", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Settings.ServerSettings", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AdscContractTimeoutMinutes") + .HasColumnType("integer"); + + b.Property("AircraftConnectionTimeoutMinutes") + .HasColumnType("integer"); + + b.Property("BannerContentType") + .HasColumnType("text"); + + b.Property("BannerImage") + .HasColumnType("bytea"); + + b.Property("BannerVersion") + .HasColumnType("integer"); + + b.Property("ConnectivityCheckIntervalMinutes") + .HasColumnType("integer"); + + b.Property("DialogueRetentionHours") + .HasColumnType("integer"); + + b.Property("HandoffNotificationLeadTimeMinutes") + .HasColumnType("integer"); + + b.Property("Motd") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("OperatorName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PrivacyContact") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("ServerName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("VatsimStatusAllowNonEquippedAircraft") + .HasColumnType("boolean"); + + b.Property("VatsimStatusEnabled") + .HasColumnType("boolean"); + + b.Property("VatsimStatusPollingIntervalSeconds") + .HasColumnType("integer"); + + b.Property("VatsimStatusReportDelayMinutes") + .HasColumnType("integer"); + + b.Property("VatsimStatusUrl") + .IsRequired() + .HasColumnType("text"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.ToTable("ServerSettings", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Downlinks.DownlinkMessage", b => + { + b.HasBaseType("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage"); + + b.Property("Content") + .IsRequired() + .ValueGeneratedOnUpdateSometimes() + .HasColumnType("text") + .HasColumnName("Content"); + + b.Property("IsControllerLate") + .HasColumnType("boolean"); + + b.Property("Received") + .HasColumnType("bigint"); + + b.Property("ResponseType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("DownlinkResponseType"); + + b.Property("Sender") + .IsRequired() + .HasColumnType("text"); + + b.HasDiscriminator().HasValue("Downlink"); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Uplinks.UplinkMessage", b => + { + b.HasBaseType("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage"); + + b.Property("ClosedManually") + .HasColumnType("boolean"); + + b.Property("Content") + .IsRequired() + .ValueGeneratedOnUpdateSometimes() + .HasColumnType("text") + .HasColumnName("Content"); + + b.Property("DidTransmissionFail") + .HasColumnType("boolean"); + + b.Property("IsPilotLate") + .HasColumnType("boolean"); + + b.Property("Recipient") + .IsRequired() + .HasColumnType("text"); + + b.Property("ResponseType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("UplinkResponseType"); + + b.Property("SenderCallsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("Sent") + .HasColumnType("bigint"); + + b.HasDiscriminator().HasValue("Uplink"); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage", b => + { + b.HasOne("CPDLCServer.Cpdlc.Dialogues.Dialogue", null) + .WithMany("Messages") + .HasForeignKey("DialogueId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.Dialogue", b => + { + b.Navigation("Messages"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261121101338_InitialCreate.Designer.cs b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261121101338_InitialCreate.Designer.cs new file mode 100644 index 0000000..ead6028 --- /dev/null +++ b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261121101338_InitialCreate.Designer.cs @@ -0,0 +1,551 @@ +// +using System; +using System.Collections.Generic; +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace CPDLCServer.Persistence.Migrations.Sqlite +{ + [DbContext(typeof(SqliteCpdlcDbContext))] + [Migration("20261121101338_InitialCreate")] + partial class InitialCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.14"); + + modelBuilder.Entity("CPDLCServer.AcarsConnections.ConnectionSettings.AcarsConnectionSettings", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("DefaultAdscReportingInterval") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("EncryptedAuthenticationCode") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Motd") + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("MotdDelaySeconds") + .HasColumnType("INTEGER"); + + b.Property("Notes") + .HasMaxLength(2000) + .HasColumnType("TEXT"); + + b.Property("StationIdentifier") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Url") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("StationIdentifier") + .IsUnique(); + + b.ToTable("AcarsConnections", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.AdscContracts.AdscContract", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("INTEGER"); + + b.Property("DefaultContractState") + .HasColumnType("TEXT"); + + b.Property("DefaultReportingInterval") + .HasColumnType("INTEGER"); + + b.Property("DemandContractState") + .HasColumnType("TEXT"); + + b.Property("LastActivity") + .HasColumnType("INTEGER"); + + b.Property("LastReportReceived") + .HasColumnType("INTEGER"); + + b.Property("ReportingInterval") + .HasColumnType("INTEGER"); + + b.Property("ReportingSource") + .HasColumnType("TEXT"); + + b.Property("SelectedContractState") + .HasColumnType("TEXT"); + + b.Property("SelectedReportingInterval") + .HasColumnType("INTEGER"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "StationId") + .IsUnique(); + + b.ToTable("AdscContracts", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.AdscContracts.Reports.AircraftAdscReport", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Received") + .HasColumnType("INTEGER"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.ComplexProperty(typeof(Dictionary), "Report", "CPDLCServer.AdscContracts.Reports.AircraftAdscReport.Report#AdscReport", b1 => + { + b1.IsRequired(); + + b1.Property("Altitude") + .HasColumnType("INTEGER") + .HasColumnName("Altitude"); + + b1.Property("Latitude") + .HasColumnType("REAL") + .HasColumnName("Latitude"); + + b1.Property("Longitude") + .HasColumnType("REAL") + .HasColumnName("Longitude"); + + b1.Property("Source") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnName("Source"); + + b1.Property("Timestamp") + .HasColumnType("INTEGER") + .HasColumnName("Timestamp"); + }); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "StationId") + .IsUnique(); + + b.ToTable("AdscReports", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Auth.Administrators.Administrator", b => + { + b.Property("Cid") + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Added") + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.HasKey("Cid"); + + b.ToTable("Administrators", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Auth.PluginTokens.PluginToken", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("Cid") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("INTEGER"); + + b.Property("Expires") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Cid"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("PluginTokens", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Connections.AircraftConnection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AcarsConnectionId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ConnectionState") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("DataAuthorityState") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("DidSentNextDataAuthorityMessage") + .HasColumnType("INTEGER"); + + b.Property("ExpectedTransferTime") + .HasColumnType("INTEGER"); + + b.Property("LastSeen") + .HasColumnType("INTEGER"); + + b.Property("LogonAccepted") + .HasColumnType("INTEGER"); + + b.Property("LogonRequested") + .HasColumnType("INTEGER"); + + b.Property("NextDataAuthority") + .HasColumnType("TEXT"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "AcarsConnectionId") + .IsUnique(); + + b.ToTable("AircraftConnections", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Acknowledged") + .HasColumnType("INTEGER"); + + b.Property("AlertType") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Closed") + .HasColumnType("INTEGER"); + + b.Property("DialogueId") + .HasColumnType("TEXT"); + + b.Property("Direction") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT"); + + b.Property("MessageId") + .HasColumnType("INTEGER"); + + b.Property("MessageReference") + .HasColumnType("INTEGER"); + + b.Property("Position") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("DialogueId"); + + b.ToTable("CpdlcMessages", (string)null); + + b.HasDiscriminator("Direction").HasValue("CpdlcMessage"); + + b.UseTphMappingStrategy(); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.Dialogue", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AircraftCallsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Archived") + .HasColumnType("INTEGER"); + + b.Property("Closed") + .HasColumnType("INTEGER"); + + b.Property("Opened") + .HasColumnType("INTEGER"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Opened"); + + b.HasIndex("AircraftCallsign", "StationId"); + + b.ToTable("Dialogues", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Uplinks.MessageIdSequence", b => + { + b.Property("AcarsConnectionId") + .HasColumnType("TEXT"); + + b.Property("Callsign") + .HasColumnType("TEXT"); + + b.Property("LastMessageId") + .HasColumnType("INTEGER"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.HasKey("AcarsConnectionId", "Callsign"); + + b.ToTable("MessageIdSequences", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Settings.ServerSettings", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdscContractTimeoutMinutes") + .HasColumnType("INTEGER"); + + b.Property("AircraftConnectionTimeoutMinutes") + .HasColumnType("INTEGER"); + + b.Property("BannerContentType") + .HasColumnType("TEXT"); + + b.Property("BannerImage") + .HasColumnType("BLOB"); + + b.Property("BannerVersion") + .HasColumnType("INTEGER"); + + b.Property("ConnectivityCheckIntervalMinutes") + .HasColumnType("INTEGER"); + + b.Property("DialogueRetentionHours") + .HasColumnType("INTEGER"); + + b.Property("HandoffNotificationLeadTimeMinutes") + .HasColumnType("INTEGER"); + + b.Property("Motd") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("OperatorName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PrivacyContact") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("ServerName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("VatsimStatusAllowNonEquippedAircraft") + .HasColumnType("INTEGER"); + + b.Property("VatsimStatusEnabled") + .HasColumnType("INTEGER"); + + b.Property("VatsimStatusPollingIntervalSeconds") + .HasColumnType("INTEGER"); + + b.Property("VatsimStatusReportDelayMinutes") + .HasColumnType("INTEGER"); + + b.Property("VatsimStatusUrl") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.ToTable("ServerSettings", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Downlinks.DownlinkMessage", b => + { + b.HasBaseType("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage"); + + b.Property("Content") + .IsRequired() + .ValueGeneratedOnUpdateSometimes() + .HasColumnType("TEXT") + .HasColumnName("Content"); + + b.Property("IsControllerLate") + .HasColumnType("INTEGER"); + + b.Property("Received") + .HasColumnType("INTEGER"); + + b.Property("ResponseType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnName("DownlinkResponseType"); + + b.Property("Sender") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasDiscriminator().HasValue("Downlink"); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Uplinks.UplinkMessage", b => + { + b.HasBaseType("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage"); + + b.Property("ClosedManually") + .HasColumnType("INTEGER"); + + b.Property("Content") + .IsRequired() + .ValueGeneratedOnUpdateSometimes() + .HasColumnType("TEXT") + .HasColumnName("Content"); + + b.Property("DidTransmissionFail") + .HasColumnType("INTEGER"); + + b.Property("IsPilotLate") + .HasColumnType("INTEGER"); + + b.Property("Recipient") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ResponseType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnName("UplinkResponseType"); + + b.Property("SenderCallsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Sent") + .HasColumnType("INTEGER"); + + b.HasDiscriminator().HasValue("Uplink"); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage", b => + { + b.HasOne("CPDLCServer.Cpdlc.Dialogues.Dialogue", null) + .WithMany("Messages") + .HasForeignKey("DialogueId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.Dialogue", b => + { + b.Navigation("Messages"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261121101338_InitialCreate.cs b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261121101338_InitialCreate.cs new file mode 100644 index 0000000..f54bb18 --- /dev/null +++ b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261121101338_InitialCreate.cs @@ -0,0 +1,319 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace CPDLCServer.Persistence.Migrations.Sqlite +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AcarsConnections", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Type = table.Column(type: "TEXT", nullable: false), + Enabled = table.Column(type: "INTEGER", nullable: false), + StationIdentifier = table.Column(type: "TEXT", nullable: false), + Url = table.Column(type: "TEXT", nullable: false), + EncryptedAuthenticationCode = table.Column(type: "TEXT", nullable: false), + DefaultAdscReportingInterval = table.Column(type: "INTEGER", nullable: false), + Motd = table.Column(type: "TEXT", maxLength: 200, nullable: true), + MotdDelaySeconds = table.Column(type: "INTEGER", nullable: false), + Notes = table.Column(type: "TEXT", maxLength: 2000, nullable: true), + Version = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AcarsConnections", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Administrators", + columns: table => new + { + Cid = table.Column(type: "TEXT", maxLength: 16, nullable: false), + Name = table.Column(type: "TEXT", nullable: true), + Added = table.Column(type: "INTEGER", nullable: false), + Version = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Administrators", x => x.Cid); + }); + + migrationBuilder.CreateTable( + name: "AdscContracts", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Callsign = table.Column(type: "TEXT", nullable: false), + StationId = table.Column(type: "TEXT", nullable: false), + Created = table.Column(type: "INTEGER", nullable: false), + DefaultReportingInterval = table.Column(type: "INTEGER", nullable: false), + ReportingInterval = table.Column(type: "INTEGER", nullable: true), + DefaultContractState = table.Column(type: "TEXT", nullable: true), + SelectedReportingInterval = table.Column(type: "INTEGER", nullable: true), + SelectedContractState = table.Column(type: "TEXT", nullable: true), + DemandContractState = table.Column(type: "TEXT", nullable: true), + LastActivity = table.Column(type: "INTEGER", nullable: false), + LastReportReceived = table.Column(type: "INTEGER", nullable: true), + ReportingSource = table.Column(type: "TEXT", nullable: true), + Version = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AdscContracts", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AdscReports", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Callsign = table.Column(type: "TEXT", nullable: false), + StationId = table.Column(type: "TEXT", nullable: false), + Received = table.Column(type: "INTEGER", nullable: false), + Version = table.Column(type: "INTEGER", nullable: false), + Altitude = table.Column(type: "INTEGER", nullable: false), + Latitude = table.Column(type: "REAL", nullable: false), + Longitude = table.Column(type: "REAL", nullable: false), + Source = table.Column(type: "TEXT", nullable: false), + Timestamp = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AdscReports", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AircraftConnections", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Callsign = table.Column(type: "TEXT", nullable: false), + AcarsConnectionId = table.Column(type: "TEXT", nullable: false), + StationId = table.Column(type: "TEXT", nullable: false), + DataAuthorityState = table.Column(type: "TEXT", nullable: false), + ConnectionState = table.Column(type: "TEXT", nullable: false), + LogonRequested = table.Column(type: "INTEGER", nullable: false), + LogonAccepted = table.Column(type: "INTEGER", nullable: true), + LastSeen = table.Column(type: "INTEGER", nullable: false), + NextDataAuthority = table.Column(type: "TEXT", nullable: true), + ExpectedTransferTime = table.Column(type: "INTEGER", nullable: true), + DidSentNextDataAuthorityMessage = table.Column(type: "INTEGER", nullable: false), + Version = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AircraftConnections", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Dialogues", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + AircraftCallsign = table.Column(type: "TEXT", nullable: false), + StationId = table.Column(type: "TEXT", nullable: false), + Opened = table.Column(type: "INTEGER", nullable: false), + Closed = table.Column(type: "INTEGER", nullable: true), + Archived = table.Column(type: "INTEGER", nullable: true), + Version = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Dialogues", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "MessageIdSequences", + columns: table => new + { + AcarsConnectionId = table.Column(type: "TEXT", nullable: false), + Callsign = table.Column(type: "TEXT", nullable: false), + LastMessageId = table.Column(type: "INTEGER", nullable: false), + Version = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MessageIdSequences", x => new { x.AcarsConnectionId, x.Callsign }); + }); + + migrationBuilder.CreateTable( + name: "PluginTokens", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Cid = table.Column(type: "TEXT", maxLength: 16, nullable: false), + Name = table.Column(type: "TEXT", nullable: false), + TokenHash = table.Column(type: "TEXT", nullable: false), + Created = table.Column(type: "INTEGER", nullable: false), + Expires = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PluginTokens", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ServerSettings", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + OperatorName = table.Column(type: "TEXT", maxLength: 128, nullable: false), + PrivacyContact = table.Column(type: "TEXT", maxLength: 256, nullable: false), + ServerName = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Motd = table.Column(type: "TEXT", maxLength: 1000, nullable: true), + BannerImage = table.Column(type: "BLOB", nullable: true), + BannerContentType = table.Column(type: "TEXT", nullable: true), + BannerVersion = table.Column(type: "INTEGER", nullable: false), + ConnectivityCheckIntervalMinutes = table.Column(type: "INTEGER", nullable: false), + AircraftConnectionTimeoutMinutes = table.Column(type: "INTEGER", nullable: false), + AdscContractTimeoutMinutes = table.Column(type: "INTEGER", nullable: false), + DialogueRetentionHours = table.Column(type: "INTEGER", nullable: false), + HandoffNotificationLeadTimeMinutes = table.Column(type: "INTEGER", nullable: false), + VatsimStatusEnabled = table.Column(type: "INTEGER", nullable: false), + VatsimStatusUrl = table.Column(type: "TEXT", nullable: false), + VatsimStatusPollingIntervalSeconds = table.Column(type: "INTEGER", nullable: false), + VatsimStatusAllowNonEquippedAircraft = table.Column(type: "INTEGER", nullable: false), + VatsimStatusReportDelayMinutes = table.Column(type: "INTEGER", nullable: false), + Version = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ServerSettings", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "CpdlcMessages", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + DialogueId = table.Column(type: "TEXT", nullable: false), + MessageId = table.Column(type: "INTEGER", nullable: false), + MessageReference = table.Column(type: "INTEGER", nullable: true), + AlertType = table.Column(type: "TEXT", nullable: false), + Position = table.Column(type: "INTEGER", nullable: false), + Closed = table.Column(type: "INTEGER", nullable: true), + Acknowledged = table.Column(type: "INTEGER", nullable: true), + Direction = table.Column(type: "TEXT", maxLength: 13, nullable: false), + Sender = table.Column(type: "TEXT", nullable: true), + DownlinkResponseType = table.Column(type: "TEXT", nullable: true), + Content = table.Column(type: "TEXT", nullable: true), + Received = table.Column(type: "INTEGER", nullable: true), + IsControllerLate = table.Column(type: "INTEGER", nullable: true), + Recipient = table.Column(type: "TEXT", nullable: true), + SenderCallsign = table.Column(type: "TEXT", nullable: true), + UplinkResponseType = table.Column(type: "TEXT", nullable: true), + Sent = table.Column(type: "INTEGER", nullable: true), + ClosedManually = table.Column(type: "INTEGER", nullable: true), + IsPilotLate = table.Column(type: "INTEGER", nullable: true), + DidTransmissionFail = table.Column(type: "INTEGER", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_CpdlcMessages", x => x.Id); + table.ForeignKey( + name: "FK_CpdlcMessages_Dialogues_DialogueId", + column: x => x.DialogueId, + principalTable: "Dialogues", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_AcarsConnections_StationIdentifier", + table: "AcarsConnections", + column: "StationIdentifier", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_AdscContracts_Callsign_StationId", + table: "AdscContracts", + columns: new[] { "Callsign", "StationId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_AdscReports_Callsign_StationId", + table: "AdscReports", + columns: new[] { "Callsign", "StationId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_AircraftConnections_Callsign_AcarsConnectionId", + table: "AircraftConnections", + columns: new[] { "Callsign", "AcarsConnectionId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_CpdlcMessages_DialogueId", + table: "CpdlcMessages", + column: "DialogueId"); + + migrationBuilder.CreateIndex( + name: "IX_Dialogues_AircraftCallsign_StationId", + table: "Dialogues", + columns: new[] { "AircraftCallsign", "StationId" }); + + migrationBuilder.CreateIndex( + name: "IX_Dialogues_Opened", + table: "Dialogues", + column: "Opened"); + + migrationBuilder.CreateIndex( + name: "IX_PluginTokens_Cid", + table: "PluginTokens", + column: "Cid"); + + migrationBuilder.CreateIndex( + name: "IX_PluginTokens_TokenHash", + table: "PluginTokens", + column: "TokenHash", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AcarsConnections"); + + migrationBuilder.DropTable( + name: "Administrators"); + + migrationBuilder.DropTable( + name: "AdscContracts"); + + migrationBuilder.DropTable( + name: "AdscReports"); + + migrationBuilder.DropTable( + name: "AircraftConnections"); + + migrationBuilder.DropTable( + name: "CpdlcMessages"); + + migrationBuilder.DropTable( + name: "MessageIdSequences"); + + migrationBuilder.DropTable( + name: "PluginTokens"); + + migrationBuilder.DropTable( + name: "ServerSettings"); + + migrationBuilder.DropTable( + name: "Dialogues"); + } + } +} diff --git a/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs b/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs new file mode 100644 index 0000000..393ae86 --- /dev/null +++ b/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs @@ -0,0 +1,548 @@ +// +using System; +using System.Collections.Generic; +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace CPDLCServer.Persistence.Migrations.Sqlite +{ + [DbContext(typeof(SqliteCpdlcDbContext))] + partial class SqliteCpdlcDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.14"); + + modelBuilder.Entity("CPDLCServer.AcarsConnections.ConnectionSettings.AcarsConnectionSettings", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("DefaultAdscReportingInterval") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("EncryptedAuthenticationCode") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Motd") + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("MotdDelaySeconds") + .HasColumnType("INTEGER"); + + b.Property("Notes") + .HasMaxLength(2000) + .HasColumnType("TEXT"); + + b.Property("StationIdentifier") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Url") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("StationIdentifier") + .IsUnique(); + + b.ToTable("AcarsConnections", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.AdscContracts.AdscContract", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("INTEGER"); + + b.Property("DefaultContractState") + .HasColumnType("TEXT"); + + b.Property("DefaultReportingInterval") + .HasColumnType("INTEGER"); + + b.Property("DemandContractState") + .HasColumnType("TEXT"); + + b.Property("LastActivity") + .HasColumnType("INTEGER"); + + b.Property("LastReportReceived") + .HasColumnType("INTEGER"); + + b.Property("ReportingInterval") + .HasColumnType("INTEGER"); + + b.Property("ReportingSource") + .HasColumnType("TEXT"); + + b.Property("SelectedContractState") + .HasColumnType("TEXT"); + + b.Property("SelectedReportingInterval") + .HasColumnType("INTEGER"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "StationId") + .IsUnique(); + + b.ToTable("AdscContracts", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.AdscContracts.Reports.AircraftAdscReport", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Received") + .HasColumnType("INTEGER"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.ComplexProperty(typeof(Dictionary), "Report", "CPDLCServer.AdscContracts.Reports.AircraftAdscReport.Report#AdscReport", b1 => + { + b1.IsRequired(); + + b1.Property("Altitude") + .HasColumnType("INTEGER") + .HasColumnName("Altitude"); + + b1.Property("Latitude") + .HasColumnType("REAL") + .HasColumnName("Latitude"); + + b1.Property("Longitude") + .HasColumnType("REAL") + .HasColumnName("Longitude"); + + b1.Property("Source") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnName("Source"); + + b1.Property("Timestamp") + .HasColumnType("INTEGER") + .HasColumnName("Timestamp"); + }); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "StationId") + .IsUnique(); + + b.ToTable("AdscReports", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Auth.Administrators.Administrator", b => + { + b.Property("Cid") + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Added") + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.HasKey("Cid"); + + b.ToTable("Administrators", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Auth.PluginTokens.PluginToken", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("Cid") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("INTEGER"); + + b.Property("Expires") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Cid"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("PluginTokens", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Connections.AircraftConnection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AcarsConnectionId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ConnectionState") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("DataAuthorityState") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("DidSentNextDataAuthorityMessage") + .HasColumnType("INTEGER"); + + b.Property("ExpectedTransferTime") + .HasColumnType("INTEGER"); + + b.Property("LastSeen") + .HasColumnType("INTEGER"); + + b.Property("LogonAccepted") + .HasColumnType("INTEGER"); + + b.Property("LogonRequested") + .HasColumnType("INTEGER"); + + b.Property("NextDataAuthority") + .HasColumnType("TEXT"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "AcarsConnectionId") + .IsUnique(); + + b.ToTable("AircraftConnections", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Acknowledged") + .HasColumnType("INTEGER"); + + b.Property("AlertType") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Closed") + .HasColumnType("INTEGER"); + + b.Property("DialogueId") + .HasColumnType("TEXT"); + + b.Property("Direction") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT"); + + b.Property("MessageId") + .HasColumnType("INTEGER"); + + b.Property("MessageReference") + .HasColumnType("INTEGER"); + + b.Property("Position") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("DialogueId"); + + b.ToTable("CpdlcMessages", (string)null); + + b.HasDiscriminator("Direction").HasValue("CpdlcMessage"); + + b.UseTphMappingStrategy(); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.Dialogue", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AircraftCallsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Archived") + .HasColumnType("INTEGER"); + + b.Property("Closed") + .HasColumnType("INTEGER"); + + b.Property("Opened") + .HasColumnType("INTEGER"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Opened"); + + b.HasIndex("AircraftCallsign", "StationId"); + + b.ToTable("Dialogues", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Uplinks.MessageIdSequence", b => + { + b.Property("AcarsConnectionId") + .HasColumnType("TEXT"); + + b.Property("Callsign") + .HasColumnType("TEXT"); + + b.Property("LastMessageId") + .HasColumnType("INTEGER"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.HasKey("AcarsConnectionId", "Callsign"); + + b.ToTable("MessageIdSequences", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Settings.ServerSettings", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdscContractTimeoutMinutes") + .HasColumnType("INTEGER"); + + b.Property("AircraftConnectionTimeoutMinutes") + .HasColumnType("INTEGER"); + + b.Property("BannerContentType") + .HasColumnType("TEXT"); + + b.Property("BannerImage") + .HasColumnType("BLOB"); + + b.Property("BannerVersion") + .HasColumnType("INTEGER"); + + b.Property("ConnectivityCheckIntervalMinutes") + .HasColumnType("INTEGER"); + + b.Property("DialogueRetentionHours") + .HasColumnType("INTEGER"); + + b.Property("HandoffNotificationLeadTimeMinutes") + .HasColumnType("INTEGER"); + + b.Property("Motd") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("OperatorName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PrivacyContact") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("ServerName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("VatsimStatusAllowNonEquippedAircraft") + .HasColumnType("INTEGER"); + + b.Property("VatsimStatusEnabled") + .HasColumnType("INTEGER"); + + b.Property("VatsimStatusPollingIntervalSeconds") + .HasColumnType("INTEGER"); + + b.Property("VatsimStatusReportDelayMinutes") + .HasColumnType("INTEGER"); + + b.Property("VatsimStatusUrl") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.ToTable("ServerSettings", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Downlinks.DownlinkMessage", b => + { + b.HasBaseType("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage"); + + b.Property("Content") + .IsRequired() + .ValueGeneratedOnUpdateSometimes() + .HasColumnType("TEXT") + .HasColumnName("Content"); + + b.Property("IsControllerLate") + .HasColumnType("INTEGER"); + + b.Property("Received") + .HasColumnType("INTEGER"); + + b.Property("ResponseType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnName("DownlinkResponseType"); + + b.Property("Sender") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasDiscriminator().HasValue("Downlink"); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Uplinks.UplinkMessage", b => + { + b.HasBaseType("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage"); + + b.Property("ClosedManually") + .HasColumnType("INTEGER"); + + b.Property("Content") + .IsRequired() + .ValueGeneratedOnUpdateSometimes() + .HasColumnType("TEXT") + .HasColumnName("Content"); + + b.Property("DidTransmissionFail") + .HasColumnType("INTEGER"); + + b.Property("IsPilotLate") + .HasColumnType("INTEGER"); + + b.Property("Recipient") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ResponseType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnName("UplinkResponseType"); + + b.Property("SenderCallsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Sent") + .HasColumnType("INTEGER"); + + b.HasDiscriminator().HasValue("Uplink"); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage", b => + { + b.HasOne("CPDLCServer.Cpdlc.Dialogues.Dialogue", null) + .WithMany("Messages") + .HasForeignKey("DialogueId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.Dialogue", b => + { + b.Navigation("Messages"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/source/CPDLCServer/Persistence/PersistenceServiceCollectionExtensions.cs b/source/CPDLCServer/Persistence/PersistenceServiceCollectionExtensions.cs new file mode 100644 index 0000000..2b79d02 --- /dev/null +++ b/source/CPDLCServer/Persistence/PersistenceServiceCollectionExtensions.cs @@ -0,0 +1,41 @@ +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Persistence; + +public static class PersistenceServiceCollectionExtensions +{ + // Registers the context of the provider. The repositories use it as CpdlcDbContext. + public static IServiceCollection AddPersistence( + this IServiceCollection services, + IConfiguration configuration, + DatabaseProvider provider, + string databasePath) + { + switch (provider) + { + case DatabaseProvider.Sqlite: + services.AddDbContext(options => + options.UseSqlite($"Data Source={databasePath}")); + services.AddScoped(sp => sp.GetRequiredService()); + break; + + case DatabaseProvider.PostgreSql: + var connectionString = configuration["DatabaseConnectionString"]; + if (string.IsNullOrWhiteSpace(connectionString)) + throw new Exception("The PostgreSQL database provider needs DatabaseConnectionString."); + + services.AddDbContext(options => + options.UseNpgsql(PostgreSqlConnectionString.Parse(connectionString))); + services.AddScoped(sp => sp.GetRequiredService()); + break; + + default: + throw new ArgumentOutOfRangeException(nameof(provider), provider, null); + } + + services.AddScoped(); + services.AddScoped(sp => sp.GetRequiredService()); + + return services; + } +} diff --git a/source/CPDLCServer/Persistence/PostgreSqlConnectionString.cs b/source/CPDLCServer/Persistence/PostgreSqlConnectionString.cs new file mode 100644 index 0000000..ea000e3 --- /dev/null +++ b/source/CPDLCServer/Persistence/PostgreSqlConnectionString.cs @@ -0,0 +1,40 @@ +using Npgsql; + +namespace CPDLCServer.Persistence; + +public static class PostgreSqlConnectionString +{ + // Npgsql accepts only "Key=Value" connection strings. + // Some platforms, for example DigitalOcean, give a URL (postgresql://user:password@host:port/database?sslmode=require). + // This changes a URL to a "Key=Value" connection string, and does not change other values. + public static string Parse(string value) + { + if (!value.StartsWith("postgres://", StringComparison.OrdinalIgnoreCase) && + !value.StartsWith("postgresql://", StringComparison.OrdinalIgnoreCase)) + return value; + + var uri = new Uri(value); + var builder = new NpgsqlConnectionStringBuilder + { + Host = uri.Host, + Database = Uri.UnescapeDataString(uri.AbsolutePath.TrimStart('/')) + }; + + if (uri.Port > 0) + builder.Port = uri.Port; + + var userInfo = uri.UserInfo.Split(':', 2); + builder.Username = Uri.UnescapeDataString(userInfo[0]); + if (userInfo.Length > 1) + builder.Password = Uri.UnescapeDataString(userInfo[1]); + + foreach (var parameter in uri.Query.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var parts = parameter.Split('=', 2); + if (parts.Length == 2 && parts[0].Equals("sslmode", StringComparison.OrdinalIgnoreCase)) + builder.SslMode = Enum.Parse(parts[1].Replace("-", string.Empty), ignoreCase: true); + } + + return builder.ConnectionString; + } +} diff --git a/source/CPDLCServer/Persistence/PostgreSqlCpdlcDbContext.cs b/source/CPDLCServer/Persistence/PostgreSqlCpdlcDbContext.cs new file mode 100644 index 0000000..a296be3 --- /dev/null +++ b/source/CPDLCServer/Persistence/PostgreSqlCpdlcDbContext.cs @@ -0,0 +1,21 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; + +namespace CPDLCServer.Persistence; + +// Has the PostgreSQL migrations (Migrations/PostgreSql) +public class PostgreSqlCpdlcDbContext(DbContextOptions options) : CpdlcDbContext(options); + +// Lets "dotnet ef" make the PostgreSQL migrations without the configuration of the server. +// "dotnet ef migrations add" does not connect to the database. +public class PostgreSqlCpdlcDbContextFactory : IDesignTimeDbContextFactory +{ + public PostgreSqlCpdlcDbContext CreateDbContext(string[] args) + { + var options = new DbContextOptionsBuilder() + .UseNpgsql("Host=localhost;Database=cpdlc") + .Options; + + return new PostgreSqlCpdlcDbContext(options); + } +} diff --git a/source/CPDLCServer/Persistence/SqliteCpdlcDbContext.cs b/source/CPDLCServer/Persistence/SqliteCpdlcDbContext.cs new file mode 100644 index 0000000..071a0db --- /dev/null +++ b/source/CPDLCServer/Persistence/SqliteCpdlcDbContext.cs @@ -0,0 +1,20 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; + +namespace CPDLCServer.Persistence; + +// Has the SQLite migrations (Migrations/Sqlite) +public class SqliteCpdlcDbContext(DbContextOptions options) : CpdlcDbContext(options); + +// Lets "dotnet ef" make the SQLite migrations without the configuration of the server +public class SqliteCpdlcDbContextFactory : IDesignTimeDbContextFactory +{ + public SqliteCpdlcDbContext CreateDbContext(string[] args) + { + var options = new DbContextOptionsBuilder() + .UseSqlite("Data Source=design-time.db") + .Options; + + return new SqliteCpdlcDbContext(options); + } +} diff --git a/source/CPDLCServer/Persistence/UnitOfWork.cs b/source/CPDLCServer/Persistence/UnitOfWork.cs new file mode 100644 index 0000000..dafea06 --- /dev/null +++ b/source/CPDLCServer/Persistence/UnitOfWork.cs @@ -0,0 +1,49 @@ +namespace CPDLCServer.Persistence; + +/// +/// One unit of work for each service scope. +/// The changes in all of the repositories are saved together. Then the messages are sent in the order that they were added. +/// +public interface IUnitOfWork +{ + /// + /// Runs the action after the changes are saved. + /// Use this for all messages to controllers and aircraft, so that they do not see changes that were not saved. + /// + void AfterCommit(Func action); +} + +public class UnitOfWork(CpdlcDbContext dbContext) : IUnitOfWork +{ + readonly List> _afterCommitActions = []; + + public void AfterCommit(Func action) + { + _afterCommitActions.Add(action); + } + + public async Task Commit(CancellationToken cancellationToken) + { + await dbContext.SaveChangesAsync(cancellationToken); + + var actions = _afterCommitActions.ToArray(); + _afterCommitActions.Clear(); + + // The changes are saved, so a failure of one message must not stop the other messages + var exceptions = new List(); + foreach (var action in actions) + { + try + { + await action(cancellationToken); + } + catch (Exception ex) + { + exceptions.Add(ex); + } + } + + if (exceptions.Count > 0) + throw new AggregateException("The changes were saved, but one or more messages were not sent", exceptions); + } +} diff --git a/source/CPDLCServer/Persistence/UtcTicksConverter.cs b/source/CPDLCServer/Persistence/UtcTicksConverter.cs new file mode 100644 index 0000000..2e10254 --- /dev/null +++ b/source/CPDLCServer/Persistence/UtcTicksConverter.cs @@ -0,0 +1,10 @@ +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace CPDLCServer.Persistence; + +/// +/// Stores a DateTimeOffset as the number of ticks in UTC. The offset is not kept. +/// +public class UtcTicksConverter() : ValueConverter( + value => value.UtcTicks, + value => new DateTimeOffset(value, TimeSpan.Zero)); diff --git a/source/CPDLCServer/Program.cs b/source/CPDLCServer/Program.cs index bd7fff3..c0f7f70 100644 --- a/source/CPDLCServer/Program.cs +++ b/source/CPDLCServer/Program.cs @@ -1,111 +1,210 @@ -using CPDLCServer.Clients; -using CPDLCServer.Hubs; -using CPDLCServer.Infrastructure; -using CPDLCServer.Persistence; -using CPDLCServer.Services; -using DotNetEnv; -using Serilog; -using Serilog.Events; - -// TODO: -// - Remove FlightSimulationNetwork variable -// - Aggregate controller connections for multiple FIRs -// - Introduce a Contracts project -// - Value types for IDs -// - Improved configuration -// - Re-do dashboard -// - Authentication - -TryLoadEnvFile(); - -var builder = WebApplication.CreateBuilder(args); - -builder.Configuration.AddEnvironmentVariables(); - -ConfigureSerilog(builder); - -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(sp => sp.GetRequiredService()); -builder.Services.AddHostedService(sp => sp.GetRequiredService()); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(builder.Configuration.GetSection("VatsimStatus").Get() ?? new VatsimStatusConfiguration()); -builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(Program).Assembly)); -builder.Services.AddSignalR() - .AddJsonProtocol(); -builder.Services.AddRazorPages(); - -builder.Services.AddHostedService(); -builder.Services.AddHostedService(); -builder.Services.AddHostedService(); -builder.Services.AddHostedService(); -builder.Services.AddHostedService(); -builder.Services.AddHostedService(); - -var app = builder.Build(); - -app.UseHttpsRedirection(); -app.UseRouting(); - -app.MapRazorPages(); -app.MapHub("/hubs/controller"); - -app.MapGet("/health", () => Results.Ok()); - -app.Run(); -return; - -void TryLoadEnvFile() -{ - // Only load .env file in development - if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") != "Development") - return; - - // Search for .env file in current directory and parent directories up to git root or filesystem root - var currentDir = new DirectoryInfo(Directory.GetCurrentDirectory()); - while (currentDir != null) - { - var envPath = Path.Combine(currentDir.FullName, ".env"); - if (File.Exists(envPath)) - { - Env.Load(envPath); - break; - } - - // Stop at git root - if (Directory.Exists(Path.Combine(currentDir.FullName, ".git"))) - { - break; - } - - currentDir = currentDir.Parent; - } -} - -void ConfigureSerilog(WebApplicationBuilder builder) -{ - if (!Enum.TryParse(builder.Configuration["Logging:Level"], out var logLevel)) - { - logLevel = LogEventLevel.Information; - } - - Log.Logger = new LoggerConfiguration() - .MinimumLevel.Is(logLevel) - .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) - .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning) - .Enrich.FromLogContext() - .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}") - .CreateLogger(); - - builder.Host.UseSerilog(); - - builder.Services.AddSingleton(Log.Logger); -} +using CPDLCServer.AcarsConnections; +using CPDLCServer.AdscContracts; +using CPDLCServer.Auth; +using CPDLCServer.Auth.PluginTokens; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc; +using CPDLCServer.Infrastructure; +using CPDLCServer.Logging; +using CPDLCServer.Persistence; +using CPDLCServer.Security; +using CPDLCServer.Settings; +using CPDLCServer.Setup; +using CPDLCServer.VatsimStatus; +using CPDLCServer.Web; +using DotNetEnv; +using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.EntityFrameworkCore; +using Serilog; +using Serilog.Events; + +// TODO: +// - Aggregate controller connections for multiple FIRs +// - Introduce a Contracts project +// - Value types for IDs + +TryLoadEnvFile(); + +var builder = WebApplication.CreateBuilder(args); + +builder.Configuration.AddEnvironmentVariables(); + +ConfigureSerilog(builder); + +// The data directory holds the SQLite database +var dataPath = GetDataPath(builder); + +var databaseProvider = GetDatabaseProvider(builder); +var databasePath = Path.Combine(dataPath, "cpdlc.db"); + +builder.Services + .AddInfrastructure() + .AddPersistence(builder.Configuration, databaseProvider, databasePath) + .AddSecurity(builder.Configuration) + .AddSetup() + .AddAuth(builder.Configuration, builder.Environment) + .AddSettings() + .AddAcarsConnections() + .AddAirTrafficControllers() + .AddCpdlc() + .AddAdsContracts() + .AddVatsimStatus() + .AddWeb(); + +var app = builder.Build(); + +await MigrateDatabase(app, databaseProvider, databasePath); +await SeedServerSettings(app); + +var setupState = app.Services.GetRequiredService(); +await setupState.Load(CancellationToken.None); +if (!setupState.IsConfigured) + Log.Warning("The server is not set up. Open /setup on this server to set it up"); + +// Behind a proxy that ends TLS, the request comes with http. VATSIM Connect needs the https redirect URL, so use the +// scheme that the proxy received. +var forwardedHeadersOptions = new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedProto }; +forwardedHeadersOptions.KnownIPNetworks.Clear(); +forwardedHeadersOptions.KnownProxies.Clear(); +app.UseForwardedHeaders(forwardedHeadersOptions); + +app.UseHttpsRedirection(); +app.UseRouting(); + +app.UseMiddleware(); +app.UseAuthentication(); +app.UseAuthorization(); + +app.MapRazorPages(); +app.MapHub("/hubs/controller"); +app.MapPluginEndpoints(); + +app.MapGet("/logs/stream", LogStreamEndpoint.Handle).RequireAuthorization(AdministratorRequirement.PolicyName); +app.MapGet("/health", () => Results.Ok()); +app.MapGet("/branding/banner", BannerEndpoint.Handle); + +app.Run(); +return; + +void TryLoadEnvFile() +{ + // Only load .env file in development + if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") != "Development") + return; + + // Search for .env file in current directory and parent directories up to git root or filesystem root + var currentDir = new DirectoryInfo(Directory.GetCurrentDirectory()); + while (currentDir != null) + { + var envPath = Path.Combine(currentDir.FullName, ".env"); + if (File.Exists(envPath)) + { + Env.Load(envPath); + break; + } + + // Stop at git root + if (Directory.Exists(Path.Combine(currentDir.FullName, ".git"))) + { + break; + } + + currentDir = currentDir.Parent; + } +} + +DatabaseProvider GetDatabaseProvider(WebApplicationBuilder builder) +{ + var configuredProvider = builder.Configuration["DatabaseProvider"]; + if (string.IsNullOrWhiteSpace(configuredProvider)) + return DatabaseProvider.Sqlite; + + if (!Enum.TryParse(configuredProvider, ignoreCase: true, out var provider)) + throw new Exception($"The database provider {configuredProvider} is not supported. Use {nameof(DatabaseProvider.Sqlite)} or {nameof(DatabaseProvider.PostgreSql)}."); + + return provider; +} + +string GetDataPath(WebApplicationBuilder builder) +{ + var configuredPath = builder.Configuration["DataPath"]; + if (!string.IsNullOrWhiteSpace(configuredPath)) + return Path.GetFullPath(configuredPath); + + // For local development, keep the data in the .data directory at the root of the repository + if (builder.Environment.IsDevelopment()) + return Path.Combine(FindRepositoryRoot() ?? Directory.GetCurrentDirectory(), ".data"); + + return "/data"; +} + +string? FindRepositoryRoot() +{ + var currentDir = new DirectoryInfo(Directory.GetCurrentDirectory()); + while (currentDir != null) + { + if (Directory.Exists(Path.Combine(currentDir.FullName, ".git"))) + return currentDir.FullName; + + currentDir = currentDir.Parent; + } + + return null; +} + +async Task MigrateDatabase(WebApplication app, DatabaseProvider provider, string databasePath) +{ + await using var scope = app.Services.CreateAsyncScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + + if (provider == DatabaseProvider.Sqlite) + { + // SQLite makes the database file, but not the directory + var databaseDirectory = Path.GetDirectoryName(databasePath); + if (databaseDirectory is not null) + Directory.CreateDirectory(databaseDirectory); + + Log.Information("Using SQLite database {DatabasePath}", databasePath); + } + else + { + // Do not write the connection string to the log, because it contains the password + var connection = dbContext.Database.GetDbConnection(); + Log.Information("Using PostgreSQL database {Database} on {Host}", connection.Database, connection.DataSource); + } + + await dbContext.Database.MigrateAsync(); +} + +// Adds the default settings to the database if they do not exist already +async Task SeedServerSettings(WebApplication app) +{ + await using var scope = app.Services.CreateAsyncScope(); + await scope.ServiceProvider.GetRequiredService().SeedDefaults(CancellationToken.None); + await scope.ServiceProvider.GetRequiredService().Commit(CancellationToken.None); +} + +void ConfigureSerilog(WebApplicationBuilder builder) +{ + if (!Enum.TryParse(builder.Configuration["Logging:Level"], out var logLevel)) + { + logLevel = LogEventLevel.Information; + } + + // Keeps the recent log entries for the Logs page + var logBuffer = new LogBuffer(capacity: 5000); + + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Is(logLevel) + .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) + .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning) + .Enrich.FromLogContext() + .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") + .WriteTo.Sink(new InMemoryLogBufferSink(logBuffer)) + .CreateLogger(); + + builder.Host.UseSerilog(); + + builder.Services.AddSingleton(Log.Logger); + builder.Services.AddSingleton(logBuffer); +} diff --git a/source/CPDLCServer/Security/MasterKeyEncryption.cs b/source/CPDLCServer/Security/MasterKeyEncryption.cs new file mode 100644 index 0000000..880cbc3 --- /dev/null +++ b/source/CPDLCServer/Security/MasterKeyEncryption.cs @@ -0,0 +1,70 @@ +using System.Security.Cryptography; +using System.Text; + +namespace CPDLCServer.Security; + +/// +/// Encrypts data with AES-GCM and the master key, so that the database does not contain them as plain text. +/// The encrypted value is the nonce, the tag and the ciphertext, as Base64 text. +/// If the master key changes, the server cannot decrypt the secrets that were encrypted with the old key. +/// The key comes from the MasterKey environment variable. A missing or invalid key stops the server at startup. +/// +public class MasterKeyEncryption(string masterKey) +{ + const int KeySize = 32; + const int NonceSize = 12; + const int TagSize = 16; + + readonly byte[] _key = ParseKey(masterKey); + + public string Encrypt(string plaintext) + { + var plaintextBytes = Encoding.UTF8.GetBytes(plaintext); + var nonce = RandomNumberGenerator.GetBytes(NonceSize); + var tag = new byte[TagSize]; + var ciphertext = new byte[plaintextBytes.Length]; + + using var aes = new AesGcm(_key, TagSize); + aes.Encrypt(nonce, plaintextBytes, ciphertext, tag); + + return Convert.ToBase64String([..nonce, ..tag, ..ciphertext]); + } + + public string Decrypt(string encrypted) + { + var bytes = Convert.FromBase64String(encrypted); + if (bytes.Length < NonceSize + TagSize) + throw new CryptographicException("The encrypted value is too short"); + + var nonce = bytes.AsSpan(0, NonceSize); + var tag = bytes.AsSpan(NonceSize, TagSize); + var ciphertext = bytes.AsSpan(NonceSize + TagSize); + var plaintextBytes = new byte[ciphertext.Length]; + + using var aes = new AesGcm(_key, TagSize); + aes.Decrypt(nonce, ciphertext, tag, plaintextBytes); + + return Encoding.UTF8.GetString(plaintextBytes); + } + + static byte[] ParseKey(string? masterKey) + { + if (string.IsNullOrWhiteSpace(masterKey)) + throw new Exception("The MasterKey environment variable is not set. Make a key with: openssl rand -base64 32"); + + byte[] key; + try + { + key = Convert.FromBase64String(masterKey); + } + catch (FormatException ex) + { + throw new Exception("The MasterKey environment variable is not valid Base64. Make a key with: openssl rand -base64 32", ex); + } + + if (key.Length != KeySize) + throw new Exception($"The MasterKey environment variable must contain a key of {KeySize} bytes. Make a key with: openssl rand -base64 32"); + + return key; + } +} diff --git a/source/CPDLCServer/Security/SecurityServiceCollectionExtensions.cs b/source/CPDLCServer/Security/SecurityServiceCollectionExtensions.cs new file mode 100644 index 0000000..11f5ddc --- /dev/null +++ b/source/CPDLCServer/Security/SecurityServiceCollectionExtensions.cs @@ -0,0 +1,15 @@ +using CPDLCServer.Infrastructure; + +namespace CPDLCServer.Security; + +public static class SecurityServiceCollectionExtensions +{ + public static IServiceCollection AddSecurity(this IServiceCollection services, IConfiguration configuration) + { + // The master key encrypts the secrets in the database. A missing or invalid MasterKey stops the server. + var masterKey = configuration.GetRequiredValue("MasterKey"); + services.AddSingleton(new MasterKeyEncryption(masterKey)); + + return services; + } +} diff --git a/source/CPDLCServer/Services/IStatisticsService.cs b/source/CPDLCServer/Services/IStatisticsService.cs deleted file mode 100644 index 9b071ed..0000000 --- a/source/CPDLCServer/Services/IStatisticsService.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace CPDLCServer.Services; - -public interface IStatisticsService -{ - ServerStatistics GetCurrentStatistics(); -} - -public class ServerStatistics -{ - public int TotalConnections { get; set; } - public int UniqueNetworks { get; set; } - public int UniqueStations { get; set; } - public List Connections { get; set; } = new(); -} - -public class ConnectionInfo -{ - public required string Network { get; set; } - public required string StationId { get; set; } - public required string Callsign { get; set; } - public required string VatsimCid { get; set; } -} diff --git a/source/CPDLCServer/Services/MessageIdProvider.cs b/source/CPDLCServer/Services/MessageIdProvider.cs deleted file mode 100644 index b9c2548..0000000 --- a/source/CPDLCServer/Services/MessageIdProvider.cs +++ /dev/null @@ -1,44 +0,0 @@ -namespace CPDLCServer.Services; - -public interface IMessageIdProvider -{ - Task GetNextMessageId( - string acarsClientId, - string callsign, - CancellationToken cancellationToken); -} - -public class MessageIdProvider : IMessageIdProvider, IDisposable -{ - private readonly Dictionary _ids = new(); - readonly SemaphoreSlim _semaphore = new(1, 1); - - public async Task GetNextMessageId( - string acarsClientId, - string callsign, - CancellationToken cancellationToken) - { - await _semaphore.WaitAsync(cancellationToken); - try - { - var key = new Key(acarsClientId, callsign); - if (!_ids.TryGetValue(key, out var nextId)) - { - nextId = 0; - } - - return _ids[key] = nextId + 1; - } - finally - { - _semaphore.Release(); - } - } - - record Key(string AcarsClientId, string Callsign); - - public void Dispose() - { - _semaphore.Dispose(); - } -} diff --git a/source/CPDLCServer/Services/MessageMonitorService.cs b/source/CPDLCServer/Services/MessageMonitorService.cs deleted file mode 100644 index a877082..0000000 --- a/source/CPDLCServer/Services/MessageMonitorService.cs +++ /dev/null @@ -1,212 +0,0 @@ -using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using MediatR; -using Microsoft.EntityFrameworkCore.Metadata.Conventions; - -namespace CPDLCServer.Services; - -public class MessageMonitorService( - IDialogueRepository repository, - IAdscMessageLogRepository adscMessageLogRepository, - IAdscReportRepository adscReportRepository, - IClock clock, - IPublisher publisher, - ILogger logger) - : BackgroundService -{ - readonly TimeSpan _timeoutCheckInterval = TimeSpan.FromSeconds(5); - - readonly TimeSpan _pilotLateTimeout = TimeSpan.FromMinutes(2); - readonly TimeSpan _controllerLateTimeout = TimeSpan.FromMinutes(2); - private readonly TimeSpan _archiveDelay = TimeSpan.FromSeconds(10); - readonly TimeSpan _purgeTimeout = TimeSpan.FromHours(24); - - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - logger.Information("Starting message monitor service"); - try - { - while (!stoppingToken.IsCancellationRequested) - { - try - { - // TODO: Time out entire dialogues when they take too long - - logger.Verbose("Running message monitor iteration"); - await PurgeOldDialogues(stoppingToken); - await PurgeOldAdscMessages(stoppingToken); - await PurgeOldAdscReports(stoppingToken); - await CheckForTimeouts(stoppingToken); - await ArchiveCompletedDialogues(stoppingToken); - } - catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) - { - logger.Verbose("Message monitor task cancellation requested"); - } - catch (Exception ex) - { - logger.Error(ex, "Error during message monitoring iteration"); - } - finally - { - await Task.Delay(_timeoutCheckInterval, stoppingToken); - } - } - } - catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) - { - logger.Information("Message monitor task stopped"); - } - catch (Exception ex) - { - logger.Error(ex, "Fatal error in message monitor task"); - } - } - - internal async Task PurgeOldDialogues(CancellationToken cancellationToken) - { - var now = clock.UtcNow(); - var dialogues = await repository.All(cancellationToken); - - foreach (var dialogue in dialogues) - { - var timeSinceOpened = now - dialogue.Opened; - if (timeSinceOpened < _purgeTimeout) - continue; - - // I don't care if it's closed or not. It's been long enough. - await repository.Remove(dialogue, cancellationToken); - logger.Information("Purging dialogue"); // TODO: Dialogue identifier - } - } - - internal async Task PurgeOldAdscMessages(CancellationToken cancellationToken) - { - var cutoff = clock.UtcNow() - _purgeTimeout; - await adscMessageLogRepository.RemoveOlderThan(cutoff, cancellationToken); - } - - internal async Task PurgeOldAdscReports(CancellationToken cancellationToken) - { - var cutoff = clock.UtcNow() - _purgeTimeout; - await adscReportRepository.RemoveOlderThan(cutoff, cancellationToken); - } - - internal async Task CheckForTimeouts(CancellationToken cancellationToken) - { - // TODO: Verify if this is supposed to apply to message closures or acknowledgements. - - var now = clock.UtcNow(); - var dialogues = await repository.All(cancellationToken); - - logger.Verbose("Checking for timeouts in {DialogueCount} dialogues", dialogues.Length); - - foreach (var dialogue in dialogues) - { - if (dialogue.IsClosed) - continue; - - var anyChanges = false; - foreach (var message in dialogue.Messages) - { - switch (message) - { - case UplinkMessage uplink: - if (CheckUplinkTimeout(uplink, now)) - { - anyChanges = true; - } - break; - - case DownlinkMessage downlink: - if (CheckDownlinkTimeout(downlink, now)) - { - anyChanges = true; - } - break; - } - } - - if (anyChanges) - { - await publisher.Publish(new DialogueChangedNotification(dialogue), cancellationToken); - } - } - } - - internal async Task ArchiveCompletedDialogues(CancellationToken cancellationToken) - { - var now = clock.UtcNow(); - var dialogues = await repository.All(cancellationToken); - - logger.Verbose("Checking for completed dialogues to archive"); - - foreach (var dialogue in dialogues) - { - if (!dialogue.IsClosed || dialogue.IsArchived) - continue; - - // Ensure all messages are acknowledged before archiving - if (!dialogue.Messages.All(m => m.IsAcknowledged)) - continue; - - // Find the last acknowledged time across all messages - var lastAckTime = dialogue.Messages.Max(m => m.Acknowledged); - - // Take the later of the last acknowledgement time or dialogue closed time - var latest = lastAckTime.Value > dialogue.Closed - ? lastAckTime.Value - : dialogue.Closed; - - var archiveTime = latest.Value.Add(_archiveDelay); - if (now < archiveTime) - continue; - - logger.Verbose("Archiving dialogue for {Callsign}", dialogue.AircraftCallsign); - dialogue.Archive(now); - - await publisher.Publish(new DialogueChangedNotification(dialogue), cancellationToken); - } - } - - bool CheckUplinkTimeout(UplinkMessage uplink, DateTimeOffset now) - { - // Skip if already closed, in timeout/failed state, or doesn't require response - if (uplink.IsClosed || - uplink.IsPilotLate || - uplink.IsTransmissionFailed || - uplink.ResponseType == CpdlcUplinkResponseType.NoResponse) - return false; - - // Check if timeout has been exceeded - var timeSinceSent = now - uplink.Sent; - if (timeSinceSent < _pilotLateTimeout) - return false; - - logger.Verbose("Uplink message {UplinkId} marked as pilot late (time since sent: {TimeSinceSent}s)", - uplink.MessageId, timeSinceSent.TotalSeconds); - uplink.IsPilotLate = true; - return true; - } - - bool CheckDownlinkTimeout(DownlinkMessage downlink, DateTimeOffset now) - { - // Skip if already closed, in timeout state, or doesn't require response - if (downlink.IsClosed || - downlink.IsControllerLate || - downlink.ResponseType == CpdlcDownlinkResponseType.NoResponse) - return false; - - // Check if timeout has been exceeded - var timeSinceReceived = now - downlink.Received; - if (timeSinceReceived < _controllerLateTimeout) - return false; - - logger.Verbose("Downlink message {DownlinkId} marked as controller late (time since received: {TimeSinceReceived}s)", - downlink.MessageId, timeSinceReceived.TotalSeconds); - downlink.IsControllerLate = true; - return true; - } -} diff --git a/source/CPDLCServer/Services/VatsimStatusConfiguration.cs b/source/CPDLCServer/Services/VatsimStatusConfiguration.cs deleted file mode 100644 index 53afe9c..0000000 --- a/source/CPDLCServer/Services/VatsimStatusConfiguration.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace CPDLCServer.Services; - -// Settings for the ADS-C reports that the server makes from the VATSIM status data -public class VatsimStatusConfiguration -{ - // When false, the server does not download the VATSIM status data - public bool Enabled { get; init; } - - public Uri Url { get; init; } = new("https://data.vatsim.net/v3/vatsim-data.json"); - - // The time in seconds between downloads of the VATSIM status data - public int PollingIntervalSeconds { get; init; } = 120; - - // When true, the server also makes reports for aircraft that do not have D1 or G1 in Item 10b of the flight plan - public bool AllowNonEquippedAircraft { get; init; } -} diff --git a/source/CPDLCServer/Settings/BannerEndpoint.cs b/source/CPDLCServer/Settings/BannerEndpoint.cs new file mode 100644 index 0000000..6fcb698 --- /dev/null +++ b/source/CPDLCServer/Settings/BannerEndpoint.cs @@ -0,0 +1,19 @@ +using Microsoft.Net.Http.Headers; + +namespace CPDLCServer.Settings; + +// Sends the banner image. The URL contains the banner version, so the browser can keep the image in its cache. +public static class BannerEndpoint +{ + public static async Task Handle(HttpContext context, IServerSettingsProvider settingsProvider, CancellationToken cancellationToken) + { + var banner = await settingsProvider.LoadBanner(cancellationToken); + if (banner is null) + return Results.NotFound(); + + context.Response.Headers[HeaderNames.CacheControl] = "public, max-age=31536000, immutable"; + context.Response.Headers[HeaderNames.XContentTypeOptions] = "nosniff"; + + return Results.File(banner.Value.Image, banner.Value.ContentType); + } +} diff --git a/source/CPDLCServer/Settings/BannerImageFormat.cs b/source/CPDLCServer/Settings/BannerImageFormat.cs new file mode 100644 index 0000000..3ec0429 --- /dev/null +++ b/source/CPDLCServer/Settings/BannerImageFormat.cs @@ -0,0 +1,28 @@ +namespace CPDLCServer.Settings; + +// Finds the type of an image from its first bytes. The type from the browser is not used, because the browser can send any type. +// SVG is not accepted, because an SVG file can contain scripts. +public static class BannerImageFormat +{ + public const int MaxSize = 1024 * 1024; + + static readonly byte[] Png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; + static readonly byte[] Jpeg = [0xFF, 0xD8, 0xFF]; + static readonly byte[] Riff = "RIFF"u8.ToArray(); + static readonly byte[] Webp = "WEBP"u8.ToArray(); + + // Returns null when the image is not PNG, JPEG or WebP + public static string? FindContentType(ReadOnlySpan image) + { + if (image.StartsWith(Png)) + return "image/png"; + + if (image.StartsWith(Jpeg)) + return "image/jpeg"; + + if (image.Length >= 12 && image[..4].SequenceEqual(Riff) && image[8..12].SequenceEqual(Webp)) + return "image/webp"; + + return null; + } +} diff --git a/source/CPDLCServer/Settings/BrandingInfo.cs b/source/CPDLCServer/Settings/BrandingInfo.cs new file mode 100644 index 0000000..848641f --- /dev/null +++ b/source/CPDLCServer/Settings/BrandingInfo.cs @@ -0,0 +1,4 @@ +namespace CPDLCServer.Settings; + +// The branding of the server settings without the image, for each page of the dashboard +public record BrandingInfo(string ServerName, string? Motd, bool HasBanner, int BannerVersion); diff --git a/source/CPDLCServer/Settings/PrivacyContactFormat.cs b/source/CPDLCServer/Settings/PrivacyContactFormat.cs new file mode 100644 index 0000000..8ac5ddc --- /dev/null +++ b/source/CPDLCServer/Settings/PrivacyContactFormat.cs @@ -0,0 +1,43 @@ +using System.ComponentModel.DataAnnotations; +using System.Net.Mail; + +namespace CPDLCServer.Settings; + +/// +/// The contact of the operator for privacy requests: an email address, or an http or https URL. +/// +public static class PrivacyContactFormat +{ + public static bool IsEmail(string contact) + { + return !contact.Contains("://") && MailAddress.TryCreate(contact, out var address) && address.Address == contact; + } + + public static bool IsUrl(string contact) + { + return Uri.TryCreate(contact, UriKind.Absolute, out var uri) && (uri.Scheme == Uri.UriSchemeHttps || uri.Scheme == Uri.UriSchemeHttp); + } + + // The link of the contact on the privacy policy + public static string ToHref(string contact) + { + return IsEmail(contact) ? $"mailto:{contact}" : contact; + } +} + +public class PrivacyContactAttribute : ValidationAttribute +{ + public PrivacyContactAttribute() + : base("Enter an email address, or a URL that starts with https://") + { + } + + // An empty value is valid. Use [Required] when the value is necessary. + public override bool IsValid(object? value) + { + return value is not string contact || + string.IsNullOrWhiteSpace(contact) || + PrivacyContactFormat.IsEmail(contact.Trim()) || + PrivacyContactFormat.IsUrl(contact.Trim()); + } +} diff --git a/source/CPDLCServer/Settings/SaveServerSettingsCommand.cs b/source/CPDLCServer/Settings/SaveServerSettingsCommand.cs new file mode 100644 index 0000000..5c39f29 --- /dev/null +++ b/source/CPDLCServer/Settings/SaveServerSettingsCommand.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.Settings; + +public record SaveServerSettingsCommand(ServerSettings Settings) : IRequest; diff --git a/source/CPDLCServer/Settings/SaveServerSettingsCommandHandler.cs b/source/CPDLCServer/Settings/SaveServerSettingsCommandHandler.cs new file mode 100644 index 0000000..adf84d6 --- /dev/null +++ b/source/CPDLCServer/Settings/SaveServerSettingsCommandHandler.cs @@ -0,0 +1,23 @@ +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.Settings; + +public class SaveServerSettingsCommandHandler( + IServerSettingsProvider settingsProvider, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(SaveServerSettingsCommand request, CancellationToken cancellationToken) + { + await settingsProvider.Save(request.Settings, cancellationToken); + + unitOfWork.AfterCommit(_ => + { + // Without the banner, so that the image bytes are not in the log + logger.Information("Server settings changed: {@Settings}", request.Settings with { BannerImage = null }); + return Task.CompletedTask; + }); + } +} diff --git a/source/CPDLCServer/Settings/ServerSettings.cs b/source/CPDLCServer/Settings/ServerSettings.cs new file mode 100644 index 0000000..9d88414 --- /dev/null +++ b/source/CPDLCServer/Settings/ServerSettings.cs @@ -0,0 +1,80 @@ +using System.ComponentModel.DataAnnotations; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; + +namespace CPDLCServer.Settings; + +/// +/// Settings that can be changed while the server is running. +/// +public record ServerSettings +{ + public const string DefaultServerName = "CPDLC Server"; + public const int MaxServerNameLength = 64; + public const int MaxMotdLength = 1000; + public const int MaxOperatorNameLength = 128; + public const int MaxPrivacyContactLength = 256; + + // The person or organisation that operates the server. The privacy policy shows it, and the setup sets it. + [Required] + [StringLength(MaxOperatorNameLength)] + public string OperatorName { get; init; } = string.Empty; + + // An email address or a URL, for questions about the privacy policy and requests to delete data + [Required] + [StringLength(MaxPrivacyContactLength)] + [PrivacyContact] + public string PrivacyContact { get; init; } = string.Empty; + + // Branding: the dashboard shows the name, the banner and the message of the day at the top of the sidebar and on + // the login page. + [Required] + [StringLength(MaxServerNameLength)] + public string ServerName { get; init; } = DefaultServerName; + + // Plain text. The dashboard keeps the line breaks. + [StringLength(MaxMotdLength)] + public string? Motd { get; init; } + + // The banner is changed with SetBannerImageCommand, not with the settings form + [BindNever] + [ValidateNever] + public byte[]? BannerImage { get; set; } + + [BindNever] + [ValidateNever] + public string? BannerContentType { get; set; } + + // Increases each time that the banner changes, so that the browser does not show an old banner from its cache + [BindNever] + [ValidateNever] + public int BannerVersion { get; set; } + + [Range(1, int.MaxValue)] + public int ConnectivityCheckIntervalMinutes { get; init; } = 15; + + [Range(1, int.MaxValue)] + public int AircraftConnectionTimeoutMinutes { get; init; } = 45; + + [Range(1, int.MaxValue)] + public int AdscContractTimeoutMinutes { get; init; } = 120; + + [Range(1, int.MaxValue)] + public int DialogueRetentionHours { get; init; } = 24; + + [Range(0, int.MaxValue)] + public int HandoffNotificationLeadTimeMinutes { get; init; } = 20; + + public bool VatsimStatusEnabled { get; init; } + + [Required] + public Uri VatsimStatusUrl { get; init; } = new("https://data.vatsim.net/v3/vatsim-data.json"); + + [Range(1, int.MaxValue)] + public int VatsimStatusPollingIntervalSeconds { get; init; } = 120; + + public bool VatsimStatusAllowNonEquippedAircraft { get; init; } + + [Range(0, int.MaxValue)] + public int VatsimStatusReportDelayMinutes { get; init; } = 5; +} diff --git a/source/CPDLCServer/Settings/ServerSettingsConfiguration.cs b/source/CPDLCServer/Settings/ServerSettingsConfiguration.cs new file mode 100644 index 0000000..a9ef67f --- /dev/null +++ b/source/CPDLCServer/Settings/ServerSettingsConfiguration.cs @@ -0,0 +1,26 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.Settings; + +// The table has one row +public class ServerSettingsConfiguration : IEntityTypeConfiguration +{ + public const string IdProperty = "Id"; + + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("ServerSettings"); + + // The settings have no ID, so the key is a shadow property + builder.Property(IdProperty); + builder.HasKey(IdProperty); + + builder.Property(s => s.VatsimStatusUrl).HasConversion(); + + builder.Property(s => s.ServerName).HasMaxLength(ServerSettings.MaxServerNameLength); + builder.Property(s => s.Motd).HasMaxLength(ServerSettings.MaxMotdLength); + builder.Property(s => s.OperatorName).HasMaxLength(ServerSettings.MaxOperatorNameLength); + builder.Property(s => s.PrivacyContact).HasMaxLength(ServerSettings.MaxPrivacyContactLength); + } +} diff --git a/source/CPDLCServer/Settings/ServerSettingsProvider.cs b/source/CPDLCServer/Settings/ServerSettingsProvider.cs new file mode 100644 index 0000000..9e9ade9 --- /dev/null +++ b/source/CPDLCServer/Settings/ServerSettingsProvider.cs @@ -0,0 +1,74 @@ +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Settings; + +public interface IServerSettingsProvider +{ + /// + /// Adds the default settings when the database has no settings, for example at the first start + /// + Task SeedDefaults(CancellationToken cancellationToken); + Task Load(CancellationToken cancellationToken); + + // Does not change the banner + Task Save(ServerSettings settings, CancellationToken cancellationToken); + + // Does not load the image + Task LoadBranding(CancellationToken cancellationToken); + + Task<(byte[] Image, string ContentType)?> LoadBanner(CancellationToken cancellationToken); +} + +public class ServerSettingsProvider(CpdlcDbContext dbContext) : IServerSettingsProvider +{ + public async Task SeedDefaults(CancellationToken cancellationToken) + { + if (await dbContext.ServerSettings.AnyAsync(cancellationToken)) + return; + + dbContext.ServerSettings.Add(new ServerSettings()); + } + + public async Task Load(CancellationToken cancellationToken) + { + await dbContext.ServerSettings.LoadAsync(cancellationToken); + return dbContext.ServerSettings.Local.Single(); + } + + public async Task Save(ServerSettings settings, CancellationToken cancellationToken) + { + var current = await Load(cancellationToken); + + // The settings form does not have the banner, so keep the current banner + var changes = settings with + { + BannerImage = current.BannerImage, + BannerContentType = current.BannerContentType, + BannerVersion = current.BannerVersion + }; + + dbContext.Entry(current).CurrentValues.SetValues(changes); + } + + public async Task LoadBranding(CancellationToken cancellationToken) + { + return await dbContext.ServerSettings + .AsNoTracking() + .Select(s => new BrandingInfo(s.ServerName, s.Motd, s.BannerImage != null, s.BannerVersion)) + .SingleAsync(cancellationToken); + } + + public async Task<(byte[] Image, string ContentType)?> LoadBanner(CancellationToken cancellationToken) + { + var banner = await dbContext.ServerSettings + .AsNoTracking() + .Select(s => new { s.BannerImage, s.BannerContentType }) + .SingleAsync(cancellationToken); + + if (banner.BannerImage is null || banner.BannerContentType is null) + return null; + + return (banner.BannerImage, banner.BannerContentType); + } +} diff --git a/source/CPDLCServer/Settings/SetBannerImageCommand.cs b/source/CPDLCServer/Settings/SetBannerImageCommand.cs new file mode 100644 index 0000000..e127352 --- /dev/null +++ b/source/CPDLCServer/Settings/SetBannerImageCommand.cs @@ -0,0 +1,6 @@ +using MediatR; + +namespace CPDLCServer.Settings; + +// A null image removes the banner +public record SetBannerImageCommand(byte[]? Image) : IRequest; diff --git a/source/CPDLCServer/Settings/SetBannerImageCommandHandler.cs b/source/CPDLCServer/Settings/SetBannerImageCommandHandler.cs new file mode 100644 index 0000000..ea4d470 --- /dev/null +++ b/source/CPDLCServer/Settings/SetBannerImageCommandHandler.cs @@ -0,0 +1,35 @@ +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.Settings; + +public class SetBannerImageCommandHandler( + IServerSettingsProvider settingsProvider, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(SetBannerImageCommand request, CancellationToken cancellationToken) + { + string? contentType = null; + if (request.Image is not null) + { + if (request.Image.Length > BannerImageFormat.MaxSize) + throw new InvalidOperationException("The image is larger than 1 MB"); + + contentType = BannerImageFormat.FindContentType(request.Image) + ?? throw new InvalidOperationException("The image must be PNG, JPEG or WebP"); + } + + var settings = await settingsProvider.Load(cancellationToken); + settings.BannerImage = request.Image; + settings.BannerContentType = contentType; + settings.BannerVersion++; + + unitOfWork.AfterCommit(_ => + { + logger.Information(request.Image is null ? "Banner removed" : "Banner changed"); + return Task.CompletedTask; + }); + } +} diff --git a/source/CPDLCServer/Settings/SettingsServiceCollectionExtensions.cs b/source/CPDLCServer/Settings/SettingsServiceCollectionExtensions.cs new file mode 100644 index 0000000..0c2f7d4 --- /dev/null +++ b/source/CPDLCServer/Settings/SettingsServiceCollectionExtensions.cs @@ -0,0 +1,10 @@ +namespace CPDLCServer.Settings; + +public static class SettingsServiceCollectionExtensions +{ + public static IServiceCollection AddSettings(this IServiceCollection services) + { + services.AddScoped(); + return services; + } +} diff --git a/source/CPDLCServer/Setup/CompleteSetupCommand.cs b/source/CPDLCServer/Setup/CompleteSetupCommand.cs new file mode 100644 index 0000000..f10c896 --- /dev/null +++ b/source/CPDLCServer/Setup/CompleteSetupCommand.cs @@ -0,0 +1,6 @@ +using MediatR; + +namespace CPDLCServer.Setup; + +// The setup adds the first administrator, and the operator details for the privacy policy +public record CompleteSetupCommand(string AdministratorCid, string OperatorName, string PrivacyContact) : IRequest; diff --git a/source/CPDLCServer/Setup/CompleteSetupCommandHandler.cs b/source/CPDLCServer/Setup/CompleteSetupCommandHandler.cs new file mode 100644 index 0000000..0636a87 --- /dev/null +++ b/source/CPDLCServer/Setup/CompleteSetupCommandHandler.cs @@ -0,0 +1,43 @@ +using CPDLCServer.Auth.Administrators; +using CPDLCServer.Infrastructure; +using CPDLCServer.Persistence; +using CPDLCServer.Settings; +using MediatR; + +namespace CPDLCServer.Setup; + +public class CompleteSetupCommandHandler( + IAdministratorRepository administratorRepository, + IServerSettingsProvider settingsProvider, + SetupState setupState, + IClock clock, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(CompleteSetupCommand request, CancellationToken cancellationToken) + { + if (await administratorRepository.Any(cancellationToken)) + throw new InvalidOperationException("An administrator already exists"); + + await administratorRepository.Add( + new Administrator { Cid = request.AdministratorCid, Added = clock.UtcNow() }, + cancellationToken); + + var settings = await settingsProvider.Load(cancellationToken); + await settingsProvider.Save( + settings with + { + OperatorName = request.OperatorName.Trim(), + PrivacyContact = request.PrivacyContact.Trim() + }, + cancellationToken); + + unitOfWork.AfterCommit(_ => + { + setupState.MarkConfigured(); + logger.Information("First administrator {Cid} added. The setup is complete", request.AdministratorCid); + return Task.CompletedTask; + }); + } +} diff --git a/source/CPDLCServer/Setup/RedirectToSetupMiddleware.cs b/source/CPDLCServer/Setup/RedirectToSetupMiddleware.cs new file mode 100644 index 0000000..e271ae9 --- /dev/null +++ b/source/CPDLCServer/Setup/RedirectToSetupMiddleware.cs @@ -0,0 +1,25 @@ +namespace CPDLCServer.Setup; + +/// +/// Redirects requests to the setup page until the setup has been completed. +/// +public class RedirectToSetupMiddleware(RequestDelegate next, SetupState setupState) +{ + static readonly string[] AllowedPaths = ["/setup", "/health", "/hubs", "/branding"]; + + public async Task InvokeAsync(HttpContext context) + { + if (!setupState.IsConfigured && !IsAllowed(context.Request.Path)) + { + context.Response.Redirect("/setup"); + return; + } + + await next(context); + } + + static bool IsAllowed(PathString path) + { + return AllowedPaths.Any(allowedPath => path.StartsWithSegments(allowedPath, StringComparison.OrdinalIgnoreCase)); + } +} diff --git a/source/CPDLCServer/Setup/SetupServiceCollectionExtensions.cs b/source/CPDLCServer/Setup/SetupServiceCollectionExtensions.cs new file mode 100644 index 0000000..02b232b --- /dev/null +++ b/source/CPDLCServer/Setup/SetupServiceCollectionExtensions.cs @@ -0,0 +1,10 @@ +namespace CPDLCServer.Setup; + +public static class SetupServiceCollectionExtensions +{ + public static IServiceCollection AddSetup(this IServiceCollection services) + { + services.AddSingleton(); + return services; + } +} diff --git a/source/CPDLCServer/Setup/SetupState.cs b/source/CPDLCServer/Setup/SetupState.cs new file mode 100644 index 0000000..fed85fa --- /dev/null +++ b/source/CPDLCServer/Setup/SetupState.cs @@ -0,0 +1,24 @@ +using CPDLCServer.Auth.Administrators; + +namespace CPDLCServer.Setup; + +// The setup adds the first administrator. The server is configured when an administrator exists. +public class SetupState(IServiceScopeFactory serviceScopeFactory) +{ + volatile bool _isConfigured; + + public bool IsConfigured => _isConfigured; + + public async Task Load(CancellationToken cancellationToken) + { + await using var scope = serviceScopeFactory.CreateAsyncScope(); + var administratorRepository = scope.ServiceProvider.GetRequiredService(); + + _isConfigured = await administratorRepository.Any(cancellationToken); + } + + public void MarkConfigured() + { + _isConfigured = true; + } +} diff --git a/source/CPDLCServer/Persistence/IVatsimPilotRepository.cs b/source/CPDLCServer/VatsimStatus/IVatsimPilotRepository.cs similarity index 55% rename from source/CPDLCServer/Persistence/IVatsimPilotRepository.cs rename to source/CPDLCServer/VatsimStatus/IVatsimPilotRepository.cs index 85e975e..9461e87 100644 --- a/source/CPDLCServer/Persistence/IVatsimPilotRepository.cs +++ b/source/CPDLCServer/VatsimStatus/IVatsimPilotRepository.cs @@ -1,11 +1,7 @@ -using CPDLCServer.Model; +namespace CPDLCServer.VatsimStatus; -namespace CPDLCServer.Persistence; - -// Holds the pilots from the latest download of the VATSIM status data public interface IVatsimPilotRepository { - // Replaces all the pilots Task Replace(VatsimPilot[] pilots, CancellationToken cancellationToken); Task Find(string callsign, CancellationToken cancellationToken); } diff --git a/source/CPDLCServer/Persistence/InMemoryVatsimPilotRepository.cs b/source/CPDLCServer/VatsimStatus/InMemoryVatsimPilotRepository.cs similarity index 90% rename from source/CPDLCServer/Persistence/InMemoryVatsimPilotRepository.cs rename to source/CPDLCServer/VatsimStatus/InMemoryVatsimPilotRepository.cs index 44bab16..c4185bd 100644 --- a/source/CPDLCServer/Persistence/InMemoryVatsimPilotRepository.cs +++ b/source/CPDLCServer/VatsimStatus/InMemoryVatsimPilotRepository.cs @@ -1,7 +1,6 @@ -using CPDLCServer.Extensions; -using CPDLCServer.Model; +using CPDLCServer.Infrastructure; -namespace CPDLCServer.Persistence; +namespace CPDLCServer.VatsimStatus; public class InMemoryVatsimPilotRepository : IVatsimPilotRepository { diff --git a/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequest.cs b/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequest.cs new file mode 100644 index 0000000..0a7da94 --- /dev/null +++ b/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequest.cs @@ -0,0 +1,8 @@ +using MediatR; + +namespace CPDLCServer.VatsimStatus; + +/// +/// Creates an ADS-C position report using VATSIM status data. +/// +public record ProduceVatsimAdscReportsRequest : IRequest; diff --git a/source/CPDLCServer/Handlers/ProduceVatsimAdscReportsRequestHandler.cs b/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequestHandler.cs similarity index 56% rename from source/CPDLCServer/Handlers/ProduceVatsimAdscReportsRequestHandler.cs rename to source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequestHandler.cs index 1c09b7a..94b2131 100644 --- a/source/CPDLCServer/Handlers/ProduceVatsimAdscReportsRequestHandler.cs +++ b/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequestHandler.cs @@ -1,25 +1,24 @@ +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using CPDLCServer.Services; +using CPDLCServer.Settings; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.VatsimStatus; /// -/// Makes ADS-C reports from the VATSIM status data, for aircraft that do not support ADS-C over Hoppie's network. +/// Creates an ADS-C position report using VATSIM status data. /// -/// A report from Hoppie stops the VATSIM reports. The VATSIM reports start again when the Hoppie reports are more than two reporting intervals late. +/// The VATSIM reports start after the report delay from when the contract was made, so that the aircraft can send its first report through Hoppie. +/// A report from Hoppie stops the VATSIM reports. The VATSIM reports start again when the Hoppie report times out. /// A rejected contract stops the VATSIM reports. /// A report is made only when the contract needs one: a demand request, or a periodic report that is due. /// /// public class ProduceVatsimAdscReportsRequestHandler( IAdscContractRepository adscContractRepository, - IAdscReportRepository adscReportRepository, IVatsimPilotRepository vatsimPilotRepository, - VatsimStatusConfiguration configuration, + IServerSettingsProvider settingsProvider, IClock clock, IMediator mediator, ILogger logger) @@ -27,6 +26,7 @@ public class ProduceVatsimAdscReportsRequestHandler( { public async Task Handle(ProduceVatsimAdscReportsRequest request, CancellationToken cancellationToken) { + var settings = await settingsProvider.Load(cancellationToken); var contracts = await adscContractRepository.All(cancellationToken); var now = clock.UtcNow(); @@ -35,7 +35,7 @@ public async Task Handle(ProduceVatsimAdscReportsRequest request, CancellationTo // A failure for one aircraft must not stop the other aircraft try { - await ProduceReport(contract, now, cancellationToken); + await ProduceReport(contract, settings, now, cancellationToken); } catch (Exception ex) when (!cancellationToken.IsCancellationRequested) { @@ -48,13 +48,13 @@ public async Task Handle(ProduceVatsimAdscReportsRequest request, CancellationTo } } - async Task ProduceReport(AdscContract contract, DateTimeOffset now, CancellationToken cancellationToken) + async Task ProduceReport(AdscContract contract, ServerSettings settings, DateTimeOffset now, CancellationToken cancellationToken) { if (!contract.IsActive) return; - var latestReport = await adscReportRepository.Find(contract.Callsign, cancellationToken); - if (!CanUseVatsimData(contract, latestReport, now) || !IsReportDue(contract, latestReport, now)) + var reportDelay = TimeSpan.FromMinutes(settings.VatsimStatusReportDelayMinutes); + if (!CanUseVatsimData(contract, reportDelay, now) || !IsReportDue(contract, now)) return; var pilot = await vatsimPilotRepository.Find(contract.Callsign, cancellationToken); @@ -64,29 +64,17 @@ async Task ProduceReport(AdscContract contract, DateTimeOffset now, Cancellation return; } - if (!pilot.IsAdscEquipped && !configuration.AllowNonEquippedAircraft) + if (!pilot.IsAdscEquipped && !settings.VatsimStatusAllowNonEquippedAircraft) { logger.Debug("{Callsign} is not ADS-C equipped, cannot make ADS-C report", contract.Callsign); return; } logger.Information( - "Made ADS-C report from VATSIM data for {Callsign} to {StationId}", + "Faking ADS-C report from VATSIM data for {Callsign} to {StationId}", contract.Callsign, contract.StationId); - contract.LogActivity(now); - - if (contract.ReportReceived()) - { - logger.Information( - "{Callsign} accepted the ADS-C contract with {StationId}", - contract.Callsign, - contract.StationId); - - await mediator.Publish(new AdscContractChangedNotification(contract), cancellationToken); - } - var report = new AdscReport( pilot.LastUpdated, pilot.Latitude, @@ -94,25 +82,25 @@ async Task ProduceReport(AdscContract contract, DateTimeOffset now, Cancellation pilot.Altitude, AdscReportSource.VATSIM); + contract.LogActivity(now); + contract.ReportReceived(report); + await mediator.Publish(new AdscContractChangedNotification(contract), cancellationToken); + await mediator.Publish( new AdscReportReceivedNotification(contract.Callsign, contract.StationId, report, now), cancellationToken); } - // VATSIM data is used only when there is no report from Hoppie, or when the Hoppie reports are late - static bool CanUseVatsimData(AdscContract contract, AircraftAdscReport? latestReport, DateTimeOffset now) + static bool CanUseVatsimData(AdscContract contract, TimeSpan reportDelay, DateTimeOffset now) { - if (latestReport is null || latestReport.Report.Source == AdscReportSource.VATSIM) - return true; - - // Only a periodic contract makes the reports late - if (!contract.HasPeriodicContract || contract.ReportingInterval is null) + if (now - contract.Created < reportDelay) return false; - return now - latestReport.Received > contract.ReportingInterval.Value * 2; + // The source is null when there is no report, or when the last report timed out + return contract.ReportingSource is null or AdscReportSource.VATSIM; } - static bool IsReportDue(AdscContract contract, AircraftAdscReport? latestReport, DateTimeOffset now) + static bool IsReportDue(AdscContract contract, DateTimeOffset now) { if (contract.DemandContractState == AdscContractState.Sent) return true; @@ -120,6 +108,10 @@ static bool IsReportDue(AdscContract contract, AircraftAdscReport? latestReport, if (!contract.HasPeriodicContract || contract.ReportingInterval is null) return false; - return latestReport is null || now - latestReport.Received >= contract.ReportingInterval.Value; + if (contract.LastReportReceived is null) + return true; + + var timeSinceLastReport = now - contract.LastReportReceived.Value; + return timeSinceLastReport >= contract.ReportingInterval.Value; } } diff --git a/source/CPDLCServer/Model/VatsimPilot.cs b/source/CPDLCServer/VatsimStatus/VatsimPilot.cs similarity index 88% rename from source/CPDLCServer/Model/VatsimPilot.cs rename to source/CPDLCServer/VatsimStatus/VatsimPilot.cs index 9e46bc8..086e548 100644 --- a/source/CPDLCServer/Model/VatsimPilot.cs +++ b/source/CPDLCServer/VatsimStatus/VatsimPilot.cs @@ -1,6 +1,8 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.VatsimStatus; -// A pilot from the VATSIM status data. Altitude is in feet. +/// +/// A pilot from the VATSIM status data +/// public record VatsimPilot( string Callsign, double Latitude, diff --git a/source/CPDLCServer/Services/VatsimStatusService.cs b/source/CPDLCServer/VatsimStatus/VatsimStatusService.cs similarity index 65% rename from source/CPDLCServer/Services/VatsimStatusService.cs rename to source/CPDLCServer/VatsimStatus/VatsimStatusService.cs index 8f180cf..4abbf39 100644 --- a/source/CPDLCServer/Services/VatsimStatusService.cs +++ b/source/CPDLCServer/VatsimStatus/VatsimStatusService.cs @@ -1,39 +1,27 @@ -using System.Net.Http.Json; using System.Text.Json.Serialization; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using MediatR; +using CPDLCServer.Infrastructure; +using CPDLCServer.Settings; -namespace CPDLCServer.Services; +namespace CPDLCServer.VatsimStatus; /// /// Downloads the VATSIM status data, then makes the ADS-C reports that are due. -/// Not all aircraft support ADS-C over Hoppie's network, so the server uses the VATSIM data for these aircraft. /// -public class VatsimStatusService : IHostedService, IDisposable +public class VatsimStatusService( + IVatsimPilotRepository vatsimPilotRepository, + IUnitOfWorkMediator mediator, + IServiceScopeFactory serviceScopeFactory, + ILogger logger) + : IHostedService, IDisposable { - readonly VatsimStatusConfiguration _configuration; - readonly IVatsimPilotRepository _vatsimPilotRepository; - readonly IMediator _mediator; - readonly ILogger _logger; + readonly TimeSpan _errorInterval = TimeSpan.FromMinutes(1); + + readonly ILogger _logger = logger.ForContext(); readonly HttpClient _httpClient = new(); CancellationTokenSource? _cancellationTokenSource; Task? _task; - public VatsimStatusService( - VatsimStatusConfiguration configuration, - IVatsimPilotRepository vatsimPilotRepository, - IMediator mediator, - ILogger logger) - { - _configuration = configuration; - _vatsimPilotRepository = vatsimPilotRepository; - _mediator = mediator; - _logger = logger.ForContext(); - } - public Task StartAsync(CancellationToken cancellationToken) { if (_cancellationTokenSource is not null || _task is not null) @@ -59,12 +47,6 @@ public async Task StopAsync(CancellationToken cancellationToken) async Task DoWork(CancellationToken stoppingToken) { - if (!_configuration.Enabled) - { - _logger.Information("ADS-C reports from VATSIM data are disabled"); - return; - } - _logger.Information("Starting VATSIM status service"); try @@ -73,13 +55,24 @@ async Task DoWork(CancellationToken stoppingToken) { try { + // The settings can change while the server is running, so read them each time + var settings = await LoadSettings(stoppingToken); + var pollingInterval = TimeSpan.FromSeconds(settings.VatsimStatusPollingIntervalSeconds); + + if (!settings.VatsimStatusEnabled) + { + _logger.Verbose("ADS-C reports from VATSIM data are disabled"); + await Task.Delay(pollingInterval, stoppingToken); + continue; + } + using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); timeoutCts.CancelAfter(TimeSpan.FromMinutes(1)); - await DownloadPilots(timeoutCts.Token); - await _mediator.Send(new ProduceVatsimAdscReportsRequest(), timeoutCts.Token); + await DownloadPilots(settings.VatsimStatusUrl, timeoutCts.Token); + await mediator.Send(new ProduceVatsimAdscReportsRequest(), timeoutCts.Token); - await Task.Delay(TimeSpan.FromSeconds(_configuration.PollingIntervalSeconds), stoppingToken); + await Task.Delay(pollingInterval, stoppingToken); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { @@ -88,7 +81,7 @@ async Task DoWork(CancellationToken stoppingToken) catch (Exception ex) { _logger.Error(ex, "Error downloading VATSIM status data"); - await Task.Delay(TimeSpan.FromSeconds(_configuration.PollingIntervalSeconds), stoppingToken); + await Task.Delay(_errorInterval, stoppingToken); } } } @@ -104,11 +97,19 @@ async Task DoWork(CancellationToken stoppingToken) _logger.Information("Stopped VATSIM status service"); } - async Task DownloadPilots(CancellationToken cancellationToken) + // The settings provider is scoped, and this service is a singleton + async Task LoadSettings(CancellationToken cancellationToken) + { + await using var scope = serviceScopeFactory.CreateAsyncScope(); + var settingsProvider = scope.ServiceProvider.GetRequiredService(); + return await settingsProvider.Load(cancellationToken); + } + + async Task DownloadPilots(Uri url, CancellationToken cancellationToken) { _logger.Debug("Downloading VATSIM status data"); - var data = await _httpClient.GetFromJsonAsync(_configuration.Url, cancellationToken); + var data = await _httpClient.GetFromJsonAsync(url, cancellationToken); if (data is null) throw new Exception("VATSIM status data is empty"); @@ -122,7 +123,7 @@ async Task DownloadPilots(CancellationToken cancellationToken) VatsimPilot.HasAdscEquipment(p.FlightPlan?.Aircraft))) .ToArray(); - await _vatsimPilotRepository.Replace(pilots, cancellationToken); + await vatsimPilotRepository.Replace(pilots, cancellationToken); _logger.Debug("Downloaded {PilotCount} pilot(s) from VATSIM status data", pilots.Length); } diff --git a/source/CPDLCServer/VatsimStatus/VatsimStatusServiceCollectionExtensions.cs b/source/CPDLCServer/VatsimStatus/VatsimStatusServiceCollectionExtensions.cs new file mode 100644 index 0000000..ad512a1 --- /dev/null +++ b/source/CPDLCServer/VatsimStatus/VatsimStatusServiceCollectionExtensions.cs @@ -0,0 +1,12 @@ +namespace CPDLCServer.VatsimStatus; + +public static class VatsimStatusServiceCollectionExtensions +{ + public static IServiceCollection AddVatsimStatus(this IServiceCollection services) + { + services.AddSingleton(); + services.AddHostedService(); + + return services; + } +} diff --git a/source/CPDLCServer/Hubs/ControllerHub.cs b/source/CPDLCServer/Web/ControllerHub.cs similarity index 65% rename from source/CPDLCServer/Hubs/ControllerHub.cs rename to source/CPDLCServer/Web/ControllerHub.cs index c45a8fd..7cff8e4 100644 --- a/source/CPDLCServer/Hubs/ControllerHub.cs +++ b/source/CPDLCServer/Web/ControllerHub.cs @@ -1,18 +1,28 @@ using CPDLCServer.Contracts; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using MediatR; +using CPDLCServer.AcarsConnections.Stations; +using CPDLCServer.Auth; +using CPDLCServer.Auth.PluginTokens; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Infrastructure; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; using CpdlcUplinkResponseType = CPDLCServer.Contracts.CpdlcUplinkResponseType; -namespace CPDLCServer.Hubs; +namespace CPDLCServer.Web; +// Only a plugin with a valid token can connect +[Authorize(Policy = PluginTokenAuthenticationHandler.PolicyName)] public class ControllerHub( IControllerRepository controllerRepository, IDialogueRepository dialogueRepository, IAcarsStationRepository acarsConnectedCallsignsRepository, - IMediator mediator, + IUnitOfWorkMediator mediator, ILogger logger) : Hub { @@ -40,27 +50,21 @@ public override async Task OnConnectedAsync() throw new HubException("callsign must be provided"); } - // Validate API key - // var validationResult = await _apiKeyValidator.ValidateAsync(apiKey); - // if (validationResult is null) - // { - // _logger.Warning("Invalid API key attempt from {ConnectionId}", Context.ConnectionId); - // throw new HubException("Invalid API key"); - // } - + // The policy accepted the plugin token, so the user has a CID + var user = Context.User!; var controller = new ControllerInfo( Guid.NewGuid(), Context.ConnectionId, stationId, callsign, - "TEST"); - // validationResult.VatsimCid); + user.GetCid()!, + user.GetName()); await controllerRepository.Add(controller, Context.GetHttpContext()?.RequestAborted ?? CancellationToken.None); _logger.Information( - "Controller connected: {Callsign} (VATSIM CID: {VatsimCid}; ConnectionId: {ConnectionId})", - callsign, "TEST", Context.ConnectionId); + "Controller connected: {Callsign} ({Name}, {Cid}). ConnectionId: {ConnectionId}", + callsign, controller.Name, controller.Cid, Context.ConnectionId); await mediator.Publish( new ControllerConnectedNotification( @@ -85,18 +89,19 @@ public async Task BeginDialogue( var modelResponseType = responseType switch { - CpdlcUplinkResponseType.NoResponse => Model.CpdlcUplinkResponseType.NoResponse, - CpdlcUplinkResponseType.WilcoUnable => Model.CpdlcUplinkResponseType.WilcoUnable, - CpdlcUplinkResponseType.AffirmativeNegative => Model.CpdlcUplinkResponseType.AffirmativeNegative, - CpdlcUplinkResponseType.Roger => Model.CpdlcUplinkResponseType.Roger, + CpdlcUplinkResponseType.NoResponse => Cpdlc.Uplinks.CpdlcUplinkResponseType.NoResponse, + CpdlcUplinkResponseType.WilcoUnable => Cpdlc.Uplinks.CpdlcUplinkResponseType.WilcoUnable, + CpdlcUplinkResponseType.AffirmativeNegative => Cpdlc.Uplinks.CpdlcUplinkResponseType.AffirmativeNegative, + CpdlcUplinkResponseType.Roger => Cpdlc.Uplinks.CpdlcUplinkResponseType.Roger, _ => throw new ArgumentOutOfRangeException(nameof(responseType), responseType, null) }; - await mediator.Send(new BeginDialogueCommand( - controller.Callsign, - recipient, - modelResponseType, - content)); + await mediator.Send( + new BeginDialogueCommand( + controller.Callsign, + recipient, + modelResponseType, + content)); } public async Task ReplyToDownlink( @@ -114,19 +119,20 @@ public async Task ReplyToDownlink( var modelResponseType = responseType switch { - CpdlcUplinkResponseType.NoResponse => Model.CpdlcUplinkResponseType.NoResponse, - CpdlcUplinkResponseType.WilcoUnable => Model.CpdlcUplinkResponseType.WilcoUnable, - CpdlcUplinkResponseType.AffirmativeNegative => Model.CpdlcUplinkResponseType.AffirmativeNegative, - CpdlcUplinkResponseType.Roger => Model.CpdlcUplinkResponseType.Roger, + CpdlcUplinkResponseType.NoResponse => Cpdlc.Uplinks.CpdlcUplinkResponseType.NoResponse, + CpdlcUplinkResponseType.WilcoUnable => Cpdlc.Uplinks.CpdlcUplinkResponseType.WilcoUnable, + CpdlcUplinkResponseType.AffirmativeNegative => Cpdlc.Uplinks.CpdlcUplinkResponseType.AffirmativeNegative, + CpdlcUplinkResponseType.Roger => Cpdlc.Uplinks.CpdlcUplinkResponseType.Roger, _ => throw new ArgumentOutOfRangeException(nameof(responseType), responseType, null) }; - await mediator.Send(new ReplyToDownlinkCommand( - controller.Callsign, - dialogueId, - downlinkMessageId, - modelResponseType, - content)); + await mediator.Send( + new ReplyToDownlinkCommand( + controller.Callsign, + dialogueId, + downlinkMessageId, + modelResponseType, + content)); } public async Task RequestConnection(string callsign, string stationId) @@ -139,12 +145,6 @@ public async Task RequestConnection(string callsign, string stationId) } await mediator.Send(new SendConnectionRequestCommand(callsign, stationId)); - - _logger.Information( - "Controller {Callsign} requested a connection between {AircraftCallsign} and {StationId}", - controller.Callsign, - callsign, - stationId); } public async Task GetConnectedAircraft() @@ -156,9 +156,7 @@ public async Task GetConnectedAircraft() throw new InvalidOperationException($"Controller not found for connection {Context.ConnectionId}"); } - var query = new GetConnectedAircraftRequest(); - var result = await mediator.Send(query); - + var result = await mediator.Send(new GetConnectedAircraftRequest()); return result.Aircraft; } @@ -171,9 +169,7 @@ public async Task GetConnectedControllers() throw new InvalidOperationException($"Controller not found for connection {Context.ConnectionId}"); } - var query = new GetConnectedControllersRequest(); - var result = await mediator.Send(query); - + var result = await mediator.Send(new GetConnectedControllersRequest()); return result.Controllers; } @@ -184,34 +180,17 @@ public async Task GetAcarsStations() public async Task AcknowledgeDownlink(Guid dialogueId, int downlinkMessageId) { - var command = new AcknowledgeDownlinkCommand(dialogueId, downlinkMessageId); - await mediator.Send(command); - - _logger.Information( - "Controller acknowledged downlink {MessageId} in dialogue {DialogueId}", - downlinkMessageId, - dialogueId); + await mediator.Send(new AcknowledgeDownlinkCommand(dialogueId, downlinkMessageId)); } public async Task AcknowledgeUplink(Guid dialogueId, int uplinkMessageId) { - var command = new AcknowledgeUplinkCommand(dialogueId, uplinkMessageId); - await mediator.Send(command); - - _logger.Information( - "Controller acknowledged uplink {MessageId} in dialogue {DialogueId}", - uplinkMessageId, - dialogueId); + await mediator.Send(new AcknowledgeUplinkCommand(dialogueId, uplinkMessageId)); } public async Task ArchiveDialogue(Guid dialogueId) { - var command = new ArchiveDialogueCommand(dialogueId); - await mediator.Send(command); - - _logger.Information( - "Controller manually archived dialogue {DialogueId}", - dialogueId); + await mediator.Send(new ArchiveDialogueCommand(dialogueId)); } public async Task UpdateNextDataAuthority( @@ -226,35 +205,16 @@ public async Task UpdateNextDataAuthority( throw new InvalidOperationException($"Controller not found for connection {Context.ConnectionId}"); } - var command = new UpdateNextDataAuthorityCommand( - controller.StationId, - callsign, - nextDataAuthority, - expectedTransferTime); - - await mediator.Send(command); - - _logger.Information( - "Controller {Callsign} updated next data authority for {AircraftCallsign} to {NextDataAuthority}", - controller.Callsign, - callsign, - nextDataAuthority ?? "(none)"); - } - - public async Task GetAtsuSettings() - { - var controller = await controllerRepository.FindByConnectionId(Context.ConnectionId, CancellationToken.None); - if (controller is null) - { - _logger.Warning("Controller not found for connection {ConnectionId}", Context.ConnectionId); - throw new InvalidOperationException($"Controller not found for connection {Context.ConnectionId}"); - } - - return await mediator.Send(new GetAtsuSettingsRequest(controller.StationId)); + await mediator.Send( + new UpdateNextDataAuthorityCommand( + controller.StationId, + callsign, + nextDataAuthority, + expectedTransferTime)); } - // A null reporting interval ends the selected contract and requests the default contract again - public async Task RequestPeriodicAdscContract(string callsign, TimeSpan? reportingInterval) + // The default reporting interval of the ATSU requests the default contract. Any other interval requests a selected contract. + public async Task RequestPeriodicAdscContract(string callsign, TimeSpan reportingInterval) { var controller = await controllerRepository.FindByConnectionId(Context.ConnectionId, CancellationToken.None); if (controller is null) @@ -263,23 +223,7 @@ public async Task RequestPeriodicAdscContract(string callsign, TimeSpan? reporti throw new InvalidOperationException($"Controller not found for connection {Context.ConnectionId}"); } - if (reportingInterval is null) - { - await mediator.Send(new RequestDefaultAdscContractCommand(controller.StationId, callsign)); - } - else - { - await mediator.Send(new RequestSelectedAdscContractCommand( - controller.StationId, - callsign, - reportingInterval.Value)); - } - - _logger.Information( - "Controller {Callsign} requested periodic ADS-C contract with {AircraftCallsign} (Interval: {ReportingInterval})", - controller.Callsign, - callsign, - reportingInterval?.ToString() ?? "Default"); + await mediator.Send(new RequestPeriodicAdscContractCommand(controller.StationId, callsign, reportingInterval)); } public async Task RequestAdscDemandReport(string callsign) @@ -292,11 +236,6 @@ public async Task RequestAdscDemandReport(string callsign) } await mediator.Send(new RequestAdscDemandReportCommand(controller.StationId, callsign)); - - _logger.Information( - "Controller {Callsign} requested ADS-C demand report from {AircraftCallsign}", - controller.Callsign, - callsign); } public async Task CancelAdscContract(string callsign) @@ -309,11 +248,6 @@ public async Task CancelAdscContract(string callsign) } await mediator.Send(new CancelAdscContractCommand(controller.StationId, callsign)); - - _logger.Information( - "Controller {Callsign} cancelled ADS-C contract with {AircraftCallsign}", - controller.Callsign, - callsign); } public async Task GetAdscContracts() @@ -359,12 +293,6 @@ public async Task GetAllDialogues() async Task GetAllDialoguesFor(ControllerInfo controller, CancellationToken cancellationToken) { var dialogues = await dialogueRepository.All(cancellationToken); - - _logger.Information( - "Sending {DialogueCount} dialogues to controller {Callsign}", - dialogues.Length, - controller.Callsign); - return dialogues.Select(DialogueConverter.ToDto).ToArray(); } diff --git a/source/CPDLCServer/Web/Pages/Account/AccessDenied.cshtml b/source/CPDLCServer/Web/Pages/Account/AccessDenied.cshtml new file mode 100644 index 0000000..119ec19 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Account/AccessDenied.cshtml @@ -0,0 +1,8 @@ +@page "/access-denied" +@{ + ViewData["Title"] = "Access denied"; +} + +

Access denied

+

Only an administrator can open this page. To get access, speak to an administrator of this server.

+Go to the overview diff --git a/source/CPDLCServer/Web/Pages/Account/Login.cshtml b/source/CPDLCServer/Web/Pages/Account/Login.cshtml new file mode 100644 index 0000000..11dae37 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Account/Login.cshtml @@ -0,0 +1,19 @@ +@page "/login" +@model LoginModel +@{ + ViewData["Title"] = "Log in"; + Layout = "_CenteredLayout"; +} + +

Log in

+

Log in with your VATSIM account.

+ + + + + + +

+ When you log in, VATSIM gives this server your CID and your name. + By logging in, you accept the privacy policy. +

diff --git a/source/CPDLCServer/Web/Pages/Account/Login.cshtml.cs b/source/CPDLCServer/Web/Pages/Account/Login.cshtml.cs new file mode 100644 index 0000000..d9d0bc0 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Account/Login.cshtml.cs @@ -0,0 +1,50 @@ +using CPDLCServer.Auth; +using CPDLCServer.Auth.Administrators; +using CPDLCServer.Auth.VatsimConnect; +using CPDLCServer.Infrastructure; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Account; + +public class LoginModel(DevelopmentLogin developmentLogin, IUnitOfWorkMediator mediator, ILogger logger) : PageModel +{ + // The page to open after the login + [BindProperty(SupportsGet = true)] + public string? ReturnUrl { get; set; } + + public async Task OnGet(CancellationToken cancellationToken) + { + if (User.Identity?.IsAuthenticated == true) + return LocalRedirect(SafeReturnUrl()); + + if (developmentLogin.Cid is { } cid) + return await DevelopmentSignIn(cid, cancellationToken); + + return Page(); + } + + // A form post starts the login, so that a link on a different site cannot start it + public IActionResult OnPost() + { + return Challenge( + new AuthenticationProperties { RedirectUri = SafeReturnUrl() }, + VatsimConnectOptions.AuthenticationScheme); + } + + async Task DevelopmentSignIn(string cid, CancellationToken cancellationToken) + { + var identity = CurrentUser.CreateIdentity(cid, DevelopmentLogin.Name, CookieAuthenticationDefaults.AuthenticationScheme); + await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new(identity)); + + await mediator.Send(new UpdateAdministratorNameCommand(cid, DevelopmentLogin.Name), cancellationToken); + logger.Warning("{Cid} logged in with the development login. VATSIM Connect was not used", cid); + + return LocalRedirect(SafeReturnUrl()); + } + + // Open only pages on this server, so that a link cannot send the user to a different site + string SafeReturnUrl() => Url.IsLocalUrl(ReturnUrl) ? ReturnUrl : "/"; +} diff --git a/source/CPDLCServer/Web/Pages/Account/Logout.cshtml b/source/CPDLCServer/Web/Pages/Account/Logout.cshtml new file mode 100644 index 0000000..e957fc3 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Account/Logout.cshtml @@ -0,0 +1,2 @@ +@page "/logout" +@model LogoutModel diff --git a/source/CPDLCServer/Web/Pages/Account/Logout.cshtml.cs b/source/CPDLCServer/Web/Pages/Account/Logout.cshtml.cs new file mode 100644 index 0000000..719b406 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Account/Logout.cshtml.cs @@ -0,0 +1,21 @@ +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Account; + +// Only a form post logs out, so that a link on a different site cannot log the user out +public class LogoutModel : PageModel +{ + public IActionResult OnGet() + { + return Redirect("/"); + } + + public async Task OnPostAsync() + { + await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); + return Redirect("/login"); + } +} diff --git a/source/CPDLCServer/Web/Pages/Adsc/Index.cshtml b/source/CPDLCServer/Web/Pages/Adsc/Index.cshtml new file mode 100644 index 0000000..ef84ce9 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Adsc/Index.cshtml @@ -0,0 +1,61 @@ +@page "/adsc" +@using CPDLCServer.AdscContracts +@model IndexModel +@{ + ViewData["Title"] = "ADS-C contracts"; + + string FormatInterval(TimeSpan? interval) => interval is null ? "-" : $"{interval.Value.TotalMinutes:0.#} min"; + + string GetStateBadgeClass(AdscContractState? state) => state switch + { + AdscContractState.Sent => "text-bg-info", + AdscContractState.Accepted => "text-bg-success", + AdscContractState.Rejected => "text-bg-danger", + _ => "text-bg-light" + }; +} + +

ADS-C contracts

+ +
+
+ @if (Model.Contracts.Length == 0) + { +

No ADS-C contracts.

+ } + else + { +
+ + + + + + + + + + + + + + + @foreach (var contract in Model.Contracts) + { + + + + + + + + + + + } + +
CallsignStationCurrent intervalDefaultSelected intervalSelectedDemandReport source
@contract.Callsign@contract.StationId@FormatInterval(contract.ReportingInterval)@(contract.DefaultContractState?.ToString() ?? "-")@FormatInterval(contract.SelectedReportingInterval)@(contract.SelectedContractState?.ToString() ?? "-")@(contract.DemandContractState?.ToString() ?? "-")@(Model.ReportSources.TryGetValue(contract.Callsign, out var source) ? source.ToString() : "-")
+
+ } +
+
diff --git a/source/CPDLCServer/Pages/Adsc/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Adsc/Index.cshtml.cs similarity index 50% rename from source/CPDLCServer/Pages/Adsc/Index.cshtml.cs rename to source/CPDLCServer/Web/Pages/Adsc/Index.cshtml.cs index 45e08bc..50764d7 100644 --- a/source/CPDLCServer/Pages/Adsc/Index.cshtml.cs +++ b/source/CPDLCServer/Web/Pages/Adsc/Index.cshtml.cs @@ -1,36 +1,26 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using Microsoft.AspNetCore.Mvc; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; using Microsoft.AspNetCore.Mvc.RazorPages; -namespace CPDLCServer.Pages.Dashboard.Adsc; +namespace CPDLCServer.Web.Pages.Adsc; public class IndexModel : PageModel { private readonly IAdscContractRepository _adscContractRepository; - private readonly IAdscMessageLogRepository _adscMessageLogRepository; private readonly IAdscReportRepository _adscReportRepository; - private const int PageSize = 50; public IndexModel( IAdscContractRepository adscContractRepository, - IAdscMessageLogRepository adscMessageLogRepository, IAdscReportRepository adscReportRepository) { _adscContractRepository = adscContractRepository; - _adscMessageLogRepository = adscMessageLogRepository; _adscReportRepository = adscReportRepository; } - [BindProperty(SupportsGet = true)] - public int PageNumber { get; set; } = 1; - public AdscContract[] Contracts { get; private set; } = []; + // The source of the latest report for each aircraft public Dictionary ReportSources { get; private set; } = new(); - public AdscMessageLogEntry[] LogEntries { get; private set; } = []; - public int TotalPages { get; private set; } - public int CurrentPage => PageNumber; public async Task OnGetAsync(CancellationToken cancellationToken) { @@ -40,17 +30,7 @@ public async Task OnGetAsync(CancellationToken cancellationToken) .ThenBy(c => c.StationId) .ToArray(); - var reports = await _adscReportRepository.All(cancellationToken); + var reports = await _adscReportRepository.AllLatest(cancellationToken); ReportSources = reports.ToDictionary(r => r.Callsign, r => r.Report.Source); - - var logEntries = await _adscMessageLogRepository.All(cancellationToken); - - TotalPages = (int)Math.Ceiling(logEntries.Length / (double)PageSize); - PageNumber = Math.Clamp(PageNumber, 1, Math.Max(1, TotalPages)); - - LogEntries = logEntries - .Skip((PageNumber - 1) * PageSize) - .Take(PageSize) - .ToArray(); } } diff --git a/source/CPDLCServer/Web/Pages/Adsc/Messages.cshtml b/source/CPDLCServer/Web/Pages/Adsc/Messages.cshtml new file mode 100644 index 0000000..b6b5ff0 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Adsc/Messages.cshtml @@ -0,0 +1,49 @@ +@page "/adsc/messages" +@using CPDLCServer.AdscContracts.MessageLog +@model MessagesModel +@{ + ViewData["Title"] = "ADS-C message log"; +} + +

ADS-C message log

+ +
+
+ @if (Model.LogEntries.Length == 0) + { +

No ADS-C messages.

+ } + else + { +
+ + + + + + + + + + + + + @foreach (var entry in Model.LogEntries) + { + + + + + + + + + } + +
TimeCallsignStationPacketACARS connection
@entry.Time.ToString("yyyy-MM-dd HH:mm:ss")@(entry.Direction == AdscMessageDirection.Uplink ? "↑" : "↓")@entry.Callsign@entry.StationId@entry.Packet@entry.AcarsConnectionId
+
+ } + + +
+
diff --git a/source/CPDLCServer/Web/Pages/Adsc/Messages.cshtml.cs b/source/CPDLCServer/Web/Pages/Adsc/Messages.cshtml.cs new file mode 100644 index 0000000..184d47d --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Adsc/Messages.cshtml.cs @@ -0,0 +1,38 @@ +using CPDLCServer.AdscContracts.MessageLog; +using CPDLCServer.Web.Pages.ViewModels; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Adsc; + +public class MessagesModel : PageModel +{ + private const int PageSize = 50; + + private readonly IAdscMessageLogRepository _adscMessageLogRepository; + + public MessagesModel(IAdscMessageLogRepository adscMessageLogRepository) + { + _adscMessageLogRepository = adscMessageLogRepository; + } + + [BindProperty(SupportsGet = true)] + public int PageNumber { get; set; } = 1; + + public AdscMessageLogEntry[] LogEntries { get; private set; } = []; + public PaginationViewModel Pagination { get; private set; } = new("/adsc/messages", 1, 1); + + public async Task OnGetAsync(CancellationToken cancellationToken) + { + var logEntries = await _adscMessageLogRepository.All(cancellationToken); + + var totalPages = (int)Math.Ceiling(logEntries.Length / (double)PageSize); + PageNumber = Math.Clamp(PageNumber, 1, Math.Max(1, totalPages)); + Pagination = new PaginationViewModel("/adsc/messages", PageNumber, totalPages); + + LogEntries = logEntries + .Skip((PageNumber - 1) * PageSize) + .Take(PageSize) + .ToArray(); + } +} diff --git a/source/CPDLCServer/Web/Pages/Configuration/Acars/Edit.cshtml b/source/CPDLCServer/Web/Pages/Configuration/Acars/Edit.cshtml new file mode 100644 index 0000000..6a565da --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Acars/Edit.cshtml @@ -0,0 +1,130 @@ +@page "/configuration/acars/edit/{id:guid?}" +@using CPDLCServer.AcarsConnections.ConnectionSettings +@model EditModel +@{ + ViewData["Title"] = Model.IsNew ? "Add ACARS connection" : "Edit ACARS connection"; +} + +

@ViewData["Title"]

+ + + +
+
+
+
+
+ +
+
+
+ +
+
+
+ +
+
+ +
+
+ + +
+
+ +
+
+ +
+
+ + +
+
+ +
+
+ +
+
+ + +
+
Default: @Model.Defaults.Url
+
+ +
+
+ + @if (!Model.IsNew) + { +
+ Leave it empty to keep the current code. +
+ } +
+
+ + +
+
+ +
+
+ +
+
+
+ + minutes +
+ +
+
Default: @Model.Defaults.DefaultAdscReportingInterval minutes
+
+ +
+
+ +
Optional. A CPDLC free text message that the server sends to each aircraft after it logs on. Use letters, digits, spaces and . , : ? ' ( ) + -
+
+
+ + +
+
+ +
+
+ +
+
+
+ + seconds +
+ +
+
Default: @Model.Defaults.MotdDelaySeconds seconds
+
+ +
+
+ +
Information for the administrators, for example who owns the station.
+
+
+ + +
+
+
+
+ +
+ Cancel + +
+
diff --git a/source/CPDLCServer/Web/Pages/Configuration/Acars/Edit.cshtml.cs b/source/CPDLCServer/Web/Pages/Configuration/Acars/Edit.cshtml.cs new file mode 100644 index 0000000..f731867 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Acars/Edit.cshtml.cs @@ -0,0 +1,109 @@ +using CPDLCServer.AcarsConnections.ConnectionSettings; +using CPDLCServer.Infrastructure; +using CPDLCServer.Persistence; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Web.Pages.Configuration.Acars; + +public class EditModel : PageModel +{ + private readonly CpdlcDbContext _dbContext; + private readonly IUnitOfWorkMediator _mediator; + private readonly ILogger _logger; + + public EditModel( + CpdlcDbContext dbContext, + IUnitOfWorkMediator mediator, + ILogger logger) + { + _dbContext = dbContext; + _mediator = mediator; + _logger = logger; + } + + [BindProperty] + public AcarsConnectionSettings Connection { get; set; } = new(); + + // Plain text. It is not shown. For an existing connection, an empty value keeps the current code. + [BindProperty] + public string? AuthenticationCode { get; set; } + + public AcarsConnectionSettings Defaults { get; } = new(); + + // Null for a new connection + public Guid? Id { get; private set; } + + public bool IsNew => Id is null; + + [TempData] + public string? StatusMessage { get; set; } + + [TempData] + public string? ErrorMessage { get; set; } + + public async Task OnGetAsync(Guid? id, CancellationToken cancellationToken) + { + Id = id; + if (id is null) + return Page(); + + var connection = await _dbContext.AcarsConnections + .AsNoTracking() + .SingleOrDefaultAsync(c => c.Id == id.Value, cancellationToken); + if (connection is null) + return NotFound(); + + Connection = connection; + return Page(); + } + + public async Task OnPostAsync(Guid? id, CancellationToken cancellationToken) + { + Id = id; + + if (id is null && string.IsNullOrWhiteSpace(AuthenticationCode)) + ModelState.AddModelError(nameof(AuthenticationCode), "Enter the authentication code."); + + if (Connection.Url is { IsAbsoluteUri: false }) + ModelState.AddModelError($"{nameof(Connection)}.{nameof(Connection.Url)}", "Enter an absolute URL."); + + // The ACARS connection ID comes from the station identifier, so only one connection can use a station identifier + var stationIdentifier = Connection.StationIdentifier.ToUpperInvariant(); + var otherId = id ?? Guid.Empty; + if (await _dbContext.AcarsConnections.AnyAsync(c => c.Id != otherId && c.StationIdentifier == stationIdentifier, cancellationToken)) + ModelState.AddModelError($"{nameof(Connection)}.{nameof(Connection.StationIdentifier)}", "Another ACARS connection uses this station identifier."); + + if (!ModelState.IsValid) + return Page(); + + try + { + if (id is null) + { + await _mediator.Send(new CreateAcarsConnectionCommand(Connection, AuthenticationCode), cancellationToken); + } + else + { + await _mediator.Send(new UpdateAcarsConnectionCommand(id.Value, Connection, AuthenticationCode), cancellationToken); + } + } + catch (AggregateException ex) + { + // The unit of work saved the settings, but the connection did not start + _logger.Error(ex, "ACARS connection for {StationId} was saved, but did not start", stationIdentifier); + ErrorMessage = $"The ACARS connection for {stationIdentifier} was saved, but it did not start: {ex.InnerException?.Message}"; + return RedirectToPage("Index"); + } + catch (Exception ex) + { + _logger.Error(ex, "Failed to save ACARS connection for {StationId}", stationIdentifier); + ModelState.AddModelError(string.Empty, $"The ACARS connection was not saved: {ex.Message}"); + return Page(); + } + + StatusMessage = $"The ACARS connection for {stationIdentifier} was saved."; + return RedirectToPage("Index"); + } +} diff --git a/source/CPDLCServer/Web/Pages/Configuration/Acars/Index.cshtml b/source/CPDLCServer/Web/Pages/Configuration/Acars/Index.cshtml new file mode 100644 index 0000000..e67da0a --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Acars/Index.cshtml @@ -0,0 +1,84 @@ +@page "/configuration/acars" +@model IndexModel +@{ + ViewData["Title"] = "ACARS connections"; +} + +
+

ACARS connections

+ Add ACARS connection +
+ +@if (Model.StatusMessage is not null) +{ + +} + +@if (Model.ErrorMessage is not null) +{ + +} + +
+
+ @if (Model.Connections.Length == 0) + { +

There are no ACARS connections. Add one to connect to an ACARS network.

+ } + else + { +
+ + + + + + + + + + + + @foreach (var connection in Model.Connections) + { + + + + + + + + } + +
StationTypeURLStatus
+ @connection.StationIdentifier + @if (!string.IsNullOrWhiteSpace(connection.Notes)) + { +
@connection.Notes
+ } +
@connection.Type@connection.Url + @if (!connection.Enabled) + { + Disabled + } + else if (Model.IsRunning(connection)) + { + Running + } + else + { + Not running + } + + Logs + Traffic + Edit +
+ +
+
+
+ } +
+
diff --git a/source/CPDLCServer/Web/Pages/Configuration/Acars/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Configuration/Acars/Index.cshtml.cs new file mode 100644 index 0000000..9b25ad2 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Acars/Index.cshtml.cs @@ -0,0 +1,62 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.AcarsConnections.ConnectionSettings; +using CPDLCServer.Infrastructure; +using CPDLCServer.Persistence; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Web.Pages.Configuration.Acars; + +public class IndexModel : PageModel +{ + private readonly CpdlcDbContext _dbContext; + private readonly IAcarsConnectionManager _acarsConnectionManager; + private readonly IUnitOfWorkMediator _mediator; + private readonly ILogger _logger; + + public IndexModel( + CpdlcDbContext dbContext, + IAcarsConnectionManager acarsConnectionManager, + IUnitOfWorkMediator mediator, + ILogger logger) + { + _dbContext = dbContext; + _acarsConnectionManager = acarsConnectionManager; + _mediator = mediator; + _logger = logger; + } + + public AcarsConnectionSettings[] Connections { get; private set; } = []; + + [TempData] + public string? StatusMessage { get; set; } + + [TempData] + public string? ErrorMessage { get; set; } + + public bool IsRunning(AcarsConnectionSettings settings) => _acarsConnectionManager.IsRunning(settings.Id); + public async Task OnGetAsync(CancellationToken cancellationToken) + { + Connections = await _dbContext.AcarsConnections + .AsNoTracking() + .OrderBy(c => c.StationIdentifier) + .ToArrayAsync(cancellationToken); + } + + public async Task OnPostDeleteAsync(Guid id, CancellationToken cancellationToken) + { + try + { + await _mediator.Send(new DeleteAcarsConnectionCommand(id), cancellationToken); + StatusMessage = "The ACARS connection was deleted."; + } + catch (Exception ex) + { + _logger.Error(ex, "Failed to delete ACARS connection {Id}", id); + ErrorMessage = $"The ACARS connection was not deleted: {ex.Message}"; + } + + return RedirectToPage(); + } +} diff --git a/source/CPDLCServer/Web/Pages/Configuration/Acars/Traffic.cshtml b/source/CPDLCServer/Web/Pages/Configuration/Acars/Traffic.cshtml new file mode 100644 index 0000000..0517cab --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Acars/Traffic.cshtml @@ -0,0 +1,74 @@ +@page "/configuration/acars/{id:guid}/traffic" +@model TrafficModel +@{ + ViewData["Title"] = $"Traffic of {Model.AcarsConnectionId}"; +} + +
+

Traffic of @Model.AcarsConnectionId

+ +
+ +
+
+ + +
+
+ + +
+
+ +
+
+
+ + + + + + + + + + + + + +
TimeTypeStatusRequestResponse
+
+
+
+ +@section Scripts { + +} diff --git a/source/CPDLCServer/Web/Pages/Configuration/Acars/Traffic.cshtml.cs b/source/CPDLCServer/Web/Pages/Configuration/Acars/Traffic.cshtml.cs new file mode 100644 index 0000000..1cb60d3 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Acars/Traffic.cshtml.cs @@ -0,0 +1,59 @@ +using CPDLCServer.AcarsConnections.Traffic; +using CPDLCServer.Persistence; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Web.Pages.Configuration.Acars; + +public class TrafficModel : PageModel +{ + private readonly CpdlcDbContext _dbContext; + private readonly AcarsTrafficLog _trafficLog; + + public TrafficModel(CpdlcDbContext dbContext, AcarsTrafficLog trafficLog) + { + _dbContext = dbContext; + _trafficLog = trafficLog; + } + + [BindProperty(SupportsGet = true)] + public bool ShowEmptyPolls { get; set; } + + public string AcarsConnectionId { get; private set; } = string.Empty; + public AcarsTrafficEntry[] Entries { get; private set; } = []; + + public int Capacity => _trafficLog.Capacity; + + public async Task OnGetAsync(Guid id, CancellationToken cancellationToken) + { + if (!await Load(id, cancellationToken)) + return NotFound(); + + return Page(); + } + + // The rows only, for the automatic refresh + public async Task OnGetRowsAsync(Guid id, CancellationToken cancellationToken) + { + if (!await Load(id, cancellationToken)) + return NotFound(); + + return Partial("_TrafficRows", Entries); + } + + async Task Load(Guid id, CancellationToken cancellationToken) + { + var connection = await _dbContext.AcarsConnections + .AsNoTracking() + .SingleOrDefaultAsync(c => c.Id == id, cancellationToken); + if (connection is null) + return false; + + AcarsConnectionId = connection.AcarsConnectionId; + Entries = _trafficLog.Get(AcarsConnectionId) + .Where(e => ShowEmptyPolls || !e.IsEmptyPoll) + .ToArray(); + return true; + } +} diff --git a/source/CPDLCServer/Web/Pages/Configuration/Acars/_TrafficRows.cshtml b/source/CPDLCServer/Web/Pages/Configuration/Acars/_TrafficRows.cshtml new file mode 100644 index 0000000..e303e88 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Acars/_TrafficRows.cshtml @@ -0,0 +1,29 @@ +@model CPDLCServer.AcarsConnections.Traffic.AcarsTrafficEntry[] + +@if (Model.Length == 0) +{ + No traffic. +} + +@foreach (var entry in Model) +{ + + + @entry.Time.ToString("HH:mm:ss") +
@entry.Duration.TotalMilliseconds.ToString("0") ms
+ + @entry.Type + @(entry.StatusCode?.ToString() ?? "-") +
@entry.Request
+ + @if (entry.Response is not null) + { +
@entry.Response
+ } + @if (entry.Error is not null) + { +
@entry.Error
+ } + + +} diff --git a/source/CPDLCServer/Web/Pages/Configuration/Administrators/Index.cshtml b/source/CPDLCServer/Web/Pages/Configuration/Administrators/Index.cshtml new file mode 100644 index 0000000..36aaa71 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Administrators/Index.cshtml @@ -0,0 +1,82 @@ +@page "/configuration/administrators" +@model IndexModel +@{ + ViewData["Title"] = "Administrators"; +} + +

Administrators

+ +@if (Model.StatusMessage is not null) +{ + +} + +@if (Model.ErrorMessage is not null) +{ + +} + +
+
Add an administrator
+
+
+
+ + + +
+
+ +
+
+
+
+ +
+
+
+ + + + + + + + + + + @foreach (var administrator in Model.Administrators) + { + + + + + + + } + +
CIDNameAdded
@administrator.Cid + @if (administrator.Name is null) + { + Not logged in yet + } + else + { + @administrator.Name + } + @if (Model.IsCurrentUser(administrator)) + { + You + } + @administrator.Added.ToString("yyyy-MM-dd HH:mm") UTC + @if (!Model.IsCurrentUser(administrator)) + { +
+ +
+ } +
+
+
+
diff --git a/source/CPDLCServer/Web/Pages/Configuration/Administrators/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Configuration/Administrators/Index.cshtml.cs new file mode 100644 index 0000000..9a6db87 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Administrators/Index.cshtml.cs @@ -0,0 +1,82 @@ +using System.ComponentModel.DataAnnotations; +using CPDLCServer.Auth; +using CPDLCServer.Auth.Administrators; +using CPDLCServer.Infrastructure; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Configuration.Administrators; + +public class IndexModel : PageModel +{ + private readonly IAdministratorRepository _administratorRepository; + private readonly IUnitOfWorkMediator _mediator; + + public IndexModel(IAdministratorRepository administratorRepository, IUnitOfWorkMediator mediator) + { + _administratorRepository = administratorRepository; + _mediator = mediator; + } + + public Administrator[] Administrators { get; private set; } = []; + + [BindProperty] + [Required(ErrorMessage = "Enter a CID.")] + [StringLength(VatsimCid.MaxLength)] + [RegularExpression(VatsimCid.Pattern, ErrorMessage = VatsimCid.ErrorMessage)] + [Display(Name = "CID")] + public string? Cid { get; set; } + + [TempData] + public string? StatusMessage { get; set; } + + [TempData] + public string? ErrorMessage { get; set; } + + public bool IsCurrentUser(Administrator administrator) => User.GetCid() == administrator.Cid; + + public async Task OnGetAsync(CancellationToken cancellationToken) + { + Administrators = await _administratorRepository.All(cancellationToken); + } + + public async Task OnPostAddAsync(CancellationToken cancellationToken) + { + if (!ModelState.IsValid) + { + Administrators = await _administratorRepository.All(cancellationToken); + return Page(); + } + + try + { + await _mediator.Send(new AddAdministratorCommand(Cid!), cancellationToken); + StatusMessage = $"{Cid} is now an administrator."; + } + catch (InvalidOperationException ex) + { + ErrorMessage = ex.Message; + } + + return RedirectToPage(); + } + + public async Task OnPostRemoveAsync(string cid, CancellationToken cancellationToken) + { + var currentUserCid = User.GetCid(); + if (currentUserCid is null) + return Forbid(); + + try + { + await _mediator.Send(new RemoveAdministratorCommand(cid, currentUserCid), cancellationToken); + StatusMessage = $"{cid} is no longer an administrator."; + } + catch (InvalidOperationException ex) + { + ErrorMessage = ex.Message; + } + + return RedirectToPage(); + } +} diff --git a/source/CPDLCServer/Web/Pages/Configuration/Logs/Index.cshtml b/source/CPDLCServer/Web/Pages/Configuration/Logs/Index.cshtml new file mode 100644 index 0000000..f8557ac --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Logs/Index.cshtml @@ -0,0 +1,232 @@ +@page "/configuration/logs" +@using CPDLCServer.Logging +@model IndexModel +@{ + ViewData["Title"] = "Logs"; +} + +
+

Logs

+ Connecting +
+ +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+ + +
+ + +
+
+ +@* The log has a dark background, the same as the console *@ +
+ +@section Scripts { + +} diff --git a/source/CPDLCServer/Web/Pages/Configuration/Logs/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Configuration/Logs/Index.cshtml.cs new file mode 100644 index 0000000..53ee28e --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Logs/Index.cshtml.cs @@ -0,0 +1,23 @@ +using CPDLCServer.AcarsConnections; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Configuration.Logs; + +// The page gets the log entries from /logs/stream with JavaScript. The filters are in the query string, so that a +// link can open the page with a filter, for example the logs of one ACARS connection. +public class IndexModel : PageModel +{ + private readonly IAcarsConnectionManager _acarsConnectionManager; + + public IndexModel(IAcarsConnectionManager acarsConnectionManager) + { + _acarsConnectionManager = acarsConnectionManager; + } + + public string[] AcarsConnectionIds { get; private set; } = []; + + public void OnGet() + { + AcarsConnectionIds = _acarsConnectionManager.GetAcarsConnectionIds().Order().ToArray(); + } +} diff --git a/source/CPDLCServer/Web/Pages/Configuration/Settings/Index.cshtml b/source/CPDLCServer/Web/Pages/Configuration/Settings/Index.cshtml new file mode 100644 index 0000000..cbe2895 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Settings/Index.cshtml @@ -0,0 +1,304 @@ +@page "/configuration/settings" +@model IndexModel +@{ + ViewData["Title"] = "Settings"; +} + +

Settings

+ +@if (Model.StatusMessage is not null) +{ + +} + + + +
+
+
Branding
+
+
+
+ +
Shows in the browser tab, and in the sidebar.
+
+
+
+ + +
+ +
+
Default: @Model.Defaults.ServerName
+
+ +
+
+ +
+
+ + +
+
+ +
+
+ +
Optional. PNG, JPEG or WebP, 1 MB or less.
+
+
+ @if (Model.Branding.HasBanner) + { + Current banner + } + + @* These controls are in the banner forms below the settings form, because a form cannot contain a form *@ + + @Html.ValidationMessage("Banner", null, new { @class = "text-danger small" }) +
+ + @if (Model.Branding.HasBanner) + { + + } +
+
+
+
+
+ +
+
Operator
+
+

The privacy policy shows the operator and the contact.

+ +
+
+ +
The person or organisation that operates this server, for example a VATSIM division.
+
+
+ + +
+
+ +
+
+ +
An email address or a URL. Users can use it to ask questions about their data, or to ask you to delete it.
+
+
+ + +
+
+
+
+ +
+
Connections
+
+ @if (Model.OneFailedCheckCausesTimeout) + { + + } + +
+
+ +
The time between checks of the connected callsigns on the ACARS network.
+
+
+
+ + minutes + +
+ +
+
Default: @Model.Defaults.ConnectivityCheckIntervalMinutes minutes
+
+ +
+
+ +
The time without contact from an aircraft before its connection times out. Use a value of more than two times the connectivity check interval. If not, one failed check will cause connections to time out.
+
+
+
+ + minutes + +
+ +
+
Default: @Model.Defaults.AircraftConnectionTimeoutMinutes minutes
+
+
+
+ +
+
Dialogues
+
+
+
+ +
The time from when a dialogue opens until the server deletes it.
+
+
+
+ + hours + +
+ +
+
Default: @Model.Defaults.DialogueRetentionHours hours
+
+
+
+ +
+
ADS-C
+
+
+
+ +
The time without ADS-C activity from an aircraft before the server cancels the ADS-C contract.
+
+
+
+ + minutes + +
+ +
+
Default: @Model.Defaults.AdscContractTimeoutMinutes minutes
+
+
+
+ +
+
Handoff
+
+
+
+ +
The time before the expected transfer time to send the NEXT DATA AUTHORITY message.
+
+
+
+ + minutes + +
+ +
+
Default: @Model.Defaults.HandoffNotificationLeadTimeMinutes minutes
+
+
+
+ +
+
ADS-C from VATSIM status data
+
+
+
+ +
Generate ADS-C reports from the VATSIM API for aircraft that do not support ADS-C over ACARS.
+
+
+
+ +
+
+
Default: @(Model.Defaults.VatsimStatusEnabled ? "On" : "Off")
+
+ +
+
+ +
The URL of the VATSIM status data.
+
+
+
+ + +
+ +
+
Default: @Model.Defaults.VatsimStatusUrl
+
+ +
+
+ +
The time between downloads of the VATSIM status data.
+
+
+
+ + seconds + +
+ +
+
Default: @Model.Defaults.VatsimStatusPollingIntervalSeconds seconds
+
+ +
+
+ +
The time after a new ADS-C contract before VATSIM reports are used. During this time, the aircraft can send its first report through ACARS.
+
+
+
+ + minutes + +
+ +
+
Default: @Model.Defaults.VatsimStatusReportDelayMinutes minutes
+
+ +
+
+ +
Also make reports for aircraft that do not have D1 or G1 in Item 10b of the flight plan.
+
+
+
+ +
+
+
Default: @(Model.Defaults.VatsimStatusAllowNonEquippedAircraft ? "On" : "Off")
+
+
+
+ +
+ Discard changes + +
+
+ + + + +@section Scripts { + +} diff --git a/source/CPDLCServer/Web/Pages/Configuration/Settings/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Configuration/Settings/Index.cshtml.cs new file mode 100644 index 0000000..c712e1a --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Settings/Index.cshtml.cs @@ -0,0 +1,97 @@ +using CPDLCServer.Infrastructure; +using CPDLCServer.Settings; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Configuration.Settings; + +public class IndexModel : PageModel +{ + private readonly IServerSettingsProvider _settingsProvider; + private readonly IUnitOfWorkMediator _mediator; + + public IndexModel(IServerSettingsProvider settingsProvider, IUnitOfWorkMediator mediator) + { + _settingsProvider = settingsProvider; + _mediator = mediator; + } + + [BindProperty] + public ServerSettings Settings { get; set; } = new(); + + public ServerSettings Defaults { get; } = new(); + + // The branding without the image, for the banner preview + public BrandingInfo Branding { get; private set; } = new(ServerSettings.DefaultServerName, null, false, 0); + + [TempData] + public string? StatusMessage { get; set; } + + // If one connectivity check fails, the time between two updates of the last seen time is two check intervals + public bool OneFailedCheckCausesTimeout => + Settings.AircraftConnectionTimeoutMinutes <= Settings.ConnectivityCheckIntervalMinutes * 2; + + public async Task OnGetAsync(CancellationToken cancellationToken) + { + Settings = await _settingsProvider.Load(cancellationToken); + Branding = await _settingsProvider.LoadBranding(cancellationToken); + } + + public async Task OnPostAsync(CancellationToken cancellationToken) + { + if (Settings.VatsimStatusUrl is { IsAbsoluteUri: false }) + ModelState.AddModelError($"{nameof(Settings)}.{nameof(Settings.VatsimStatusUrl)}", "Enter an absolute URL."); + + if (!ModelState.IsValid) + { + Branding = await _settingsProvider.LoadBranding(cancellationToken); + return Page(); + } + + await _mediator.Send(new SaveServerSettingsCommand(Settings), cancellationToken); + + StatusMessage = "The settings were saved."; + return RedirectToPage(); + } + + public async Task OnPostUploadBannerAsync(IFormFile? banner, CancellationToken cancellationToken) + { + // The settings fields are not in the banner form + ModelState.Clear(); + + if (banner is null || banner.Length == 0) + ModelState.AddModelError("Banner", "Select an image."); + else if (banner.Length > BannerImageFormat.MaxSize) + ModelState.AddModelError("Banner", "The image is larger than 1 MB."); + + byte[]? image = null; + if (ModelState.IsValid) + { + using var stream = new MemoryStream(); + await banner!.CopyToAsync(stream, cancellationToken); + image = stream.ToArray(); + + if (BannerImageFormat.FindContentType(image) is null) + ModelState.AddModelError("Banner", "The image must be PNG, JPEG or WebP."); + } + + if (!ModelState.IsValid) + { + await OnGetAsync(cancellationToken); + return Page(); + } + + await _mediator.Send(new SetBannerImageCommand(image), cancellationToken); + + StatusMessage = "The banner was saved."; + return RedirectToPage(); + } + + public async Task OnPostRemoveBannerAsync(CancellationToken cancellationToken) + { + await _mediator.Send(new SetBannerImageCommand(null), cancellationToken); + + StatusMessage = "The banner was removed."; + return RedirectToPage(); + } +} diff --git a/source/CPDLCServer/Web/Pages/Cpdlc/Aircraft/Index.cshtml b/source/CPDLCServer/Web/Pages/Cpdlc/Aircraft/Index.cshtml new file mode 100644 index 0000000..98ff6a6 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Cpdlc/Aircraft/Index.cshtml @@ -0,0 +1,45 @@ +@page "/cpdlc/aircraft/{callsign}" +@model IndexModel +@{ + ViewData["Title"] = Model.Callsign; +} + +

@Model.Callsign

+ +@if (Model.Aircraft != null) +{ +
+
+
+
Callsign
+
@Model.Aircraft.Callsign
+ +
Station
+
@Model.Aircraft.StationId
+ +
ACARS connection
+
@Model.Aircraft.AcarsConnectionId
+ +
Data authority
+
@Model.Aircraft.DataAuthorityState
+ +
Connection state
+
@Model.Aircraft.ConnectionState
+ +
Last seen
+
@Model.Aircraft.LastSeen.ToString("yyyy-MM-dd HH:mm:ss")
+
+
+
+} +else +{ +
@Model.Callsign is not connected.
+} + +
+
Messages
+
+ +
+
diff --git a/source/CPDLCServer/Pages/Pilot/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Cpdlc/Aircraft/Index.cshtml.cs similarity index 83% rename from source/CPDLCServer/Pages/Pilot/Index.cshtml.cs rename to source/CPDLCServer/Web/Pages/Cpdlc/Aircraft/Index.cshtml.cs index 0df50ca..a5eb889 100644 --- a/source/CPDLCServer/Pages/Pilot/Index.cshtml.cs +++ b/source/CPDLCServer/Web/Pages/Cpdlc/Aircraft/Index.cshtml.cs @@ -1,10 +1,10 @@ -using CPDLCServer.Model; -using CPDLCServer.Pages.ViewModels; -using CPDLCServer.Persistence; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Web.Pages.ViewModels; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -namespace CPDLCServer.Pages.Dashboard.Pilot; +namespace CPDLCServer.Web.Pages.Cpdlc.Aircraft; public class IndexModel : PageModel { @@ -34,7 +34,7 @@ public async Task OnGetAsync(string callsign, CancellationToken c Messages = dialogues .Where(d => d.AircraftCallsign == callsign) - .SelectMany(d => d.Messages.Select(m => Dashboard.Messages.IndexModel.ToViewModel(d, m, aircraftLookup))) + .SelectMany(d => d.Messages.Select(m => MessageRowViewModel.From(d, m, aircraftLookup))) .OrderByDescending(m => m.Timestamp) .ToList(); diff --git a/source/CPDLCServer/Web/Pages/Cpdlc/Dialogues/Index.cshtml b/source/CPDLCServer/Web/Pages/Cpdlc/Dialogues/Index.cshtml new file mode 100644 index 0000000..304c919 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Cpdlc/Dialogues/Index.cshtml @@ -0,0 +1,46 @@ +@page "/cpdlc/dialogues/{id:guid}" +@model IndexModel +@{ + ViewData["Title"] = $"Dialogue {Model.Dialogue?.Id.ToString()[..8]}"; +} + +
+

Dialogue

+ + @(Model.Dialogue?.IsClosed == true ? "Closed" : "Open") + +
+ +
+
+
+
ID
+
@Model.Dialogue?.Id
+ +
Aircraft
+
@Model.Dialogue?.AircraftCallsign
+ +
Station
+
@Model.StationId
+ +
ACARS connection
+
@Model.AcarsNetwork
+ +
Opened
+
@Model.Dialogue?.Opened.ToString("yyyy-MM-dd HH:mm:ss")
+ + @if (Model.Dialogue?.IsClosed == true) + { +
Closed
+
@Model.Dialogue?.Closed?.ToString("yyyy-MM-dd HH:mm:ss")
+ } +
+
+
+ +
+
Messages
+
+ +
+
diff --git a/source/CPDLCServer/Pages/Dialogue/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Cpdlc/Dialogues/Index.cshtml.cs similarity index 72% rename from source/CPDLCServer/Pages/Dialogue/Index.cshtml.cs rename to source/CPDLCServer/Web/Pages/Cpdlc/Dialogues/Index.cshtml.cs index ee7eb68..632afec 100644 --- a/source/CPDLCServer/Pages/Dialogue/Index.cshtml.cs +++ b/source/CPDLCServer/Web/Pages/Cpdlc/Dialogues/Index.cshtml.cs @@ -1,10 +1,10 @@ -using CPDLCServer.Model; -using CPDLCServer.Pages.ViewModels; -using CPDLCServer.Persistence; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Web.Pages.ViewModels; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -namespace CPDLCServer.Pages.Dashboard.Dialogue; +namespace CPDLCServer.Web.Pages.Cpdlc.Dialogues; public class IndexModel : PageModel { @@ -19,7 +19,7 @@ public IndexModel( _aircraftRepository = aircraftRepository; } - public Model.Dialogue? Dialogue { get; private set; } + public CPDLCServer.Cpdlc.Dialogues.Dialogue? Dialogue { get; private set; } public List Messages { get; private set; } = []; public string AcarsNetwork { get; private set; } = "Unknown"; public string StationId { get; private set; } = "Unknown"; @@ -34,15 +34,15 @@ public async Task OnGetAsync(Guid id, CancellationToken cancellat } var aircraft = await _aircraftRepository.All(cancellationToken); - var match = aircraft.FirstOrDefault(a => a.Callsign == Dialogue.AircraftCallsign); - AcarsNetwork = match?.AcarsClientId ?? "Unknown"; - StationId = match?.StationId ?? "Unknown"; + var match = aircraft.FirstOrDefault(a => a.Callsign == Dialogue.AircraftCallsign && a.StationId == Dialogue.StationId); + AcarsNetwork = match?.AcarsConnectionId ?? "Unknown"; + StationId = Dialogue.StationId; var aircraftLookup = aircraft.ToDictionary(a => a.Callsign, a => a); Messages = Dialogue.Messages .OrderBy(m => m.Time) - .Select(m => Dashboard.Messages.IndexModel.ToViewModel(Dialogue, m, aircraftLookup)) + .Select(m => MessageRowViewModel.From(Dialogue, m, aircraftLookup)) .ToList(); return Page(); diff --git a/source/CPDLCServer/Web/Pages/Cpdlc/Index.cshtml b/source/CPDLCServer/Web/Pages/Cpdlc/Index.cshtml new file mode 100644 index 0000000..6a2fc43 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Cpdlc/Index.cshtml @@ -0,0 +1,124 @@ +@page "/cpdlc" +@model IndexModel +@{ + ViewData["Title"] = "CPDLC"; +} + +

CPDLC overview

+ +
+
+
+
Controllers
+
@Model.Controllers.Length
+
+
+
+
+
Aircraft
+
@Model.Aircraft.Length
+
+
+
+
+
Open dialogues
+
@Model.OpenDialogueCount
+
+
+
+
+
Messages
+
@Model.TotalMessageCount
+
+
+
+ +
+
+
+
Controllers
+
+ @if (Model.Controllers.Length == 0) + { +

No controllers are connected.

+ } + else + { +
+ + + + + + + + + + @foreach (var controller in Model.Controllers) + { + + + + + + } + +
CallsignStationController
@controller.Callsign@controller.StationId@controller.Name (@controller.Cid)
+
+ } +
+
+
+ +
+
+
Aircraft
+
+ @if (Model.Aircraft.Length == 0) + { +

No aircraft are connected.

+ } + else + { +
+ + + + + + + + + + + + @foreach (var aircraft in Model.Aircraft) + { + + + + + + + + } + +
CallsignStationData authorityACARS connectionLast seen
@aircraft.Callsign@aircraft.StationId@aircraft.DataAuthorityState@aircraft.AcarsConnectionId@aircraft.LastSeen.ToString("HH:mm:ss")
+
+ } +
+
+
+ +
+
+
+ Recent messages + All messages +
+
+ +
+
+
+
diff --git a/source/CPDLCServer/Web/Pages/Cpdlc/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Cpdlc/Index.cshtml.cs new file mode 100644 index 0000000..d85f937 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Cpdlc/Index.cshtml.cs @@ -0,0 +1,56 @@ +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Web.Pages.ViewModels; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Cpdlc; + +public class IndexModel : PageModel +{ + private const int RecentMessageCount = 10; + + private readonly IControllerRepository _controllerRepository; + private readonly IAircraftRepository _aircraftRepository; + private readonly IDialogueRepository _dialogueRepository; + + public IndexModel( + IControllerRepository controllerRepository, + IAircraftRepository aircraftRepository, + IDialogueRepository dialogueRepository) + { + _controllerRepository = controllerRepository; + _aircraftRepository = aircraftRepository; + _dialogueRepository = dialogueRepository; + } + + public ControllerInfo[] Controllers { get; private set; } = []; + public AircraftConnection[] Aircraft { get; private set; } = []; + + public int TotalMessageCount { get; private set; } + public int OpenDialogueCount { get; private set; } + + public List RecentMessages { get; private set; } = []; + + public async Task OnGetAsync(CancellationToken cancellationToken) + { + Controllers = (await _controllerRepository.All(cancellationToken)) + .OrderBy(c => c.StationId) + .ThenBy(c => c.Callsign) + .ToArray(); + Aircraft = (await _aircraftRepository.All(cancellationToken)) + .OrderBy(a => a.Callsign) + .ToArray(); + var dialogues = await _dialogueRepository.All(cancellationToken); + + TotalMessageCount = dialogues.Sum(d => d.Messages.Count); + OpenDialogueCount = dialogues.Count(d => !d.IsClosed); + + var aircraftLookup = Aircraft.ToDictionary(a => a.Callsign, a => a); + RecentMessages = dialogues + .SelectMany(d => d.Messages.Select(m => MessageRowViewModel.From(d, m, aircraftLookup))) + .OrderByDescending(m => m.Timestamp) + .Take(RecentMessageCount) + .ToList(); + } +} diff --git a/source/CPDLCServer/Web/Pages/Cpdlc/Messages.cshtml b/source/CPDLCServer/Web/Pages/Cpdlc/Messages.cshtml new file mode 100644 index 0000000..c8b7e94 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Cpdlc/Messages.cshtml @@ -0,0 +1,14 @@ +@page "/cpdlc/messages" +@model MessagesModel +@{ + ViewData["Title"] = "CPDLC messages"; +} + +

Messages

+ +
+
+ + +
+
diff --git a/source/CPDLCServer/Web/Pages/Cpdlc/Messages.cshtml.cs b/source/CPDLCServer/Web/Pages/Cpdlc/Messages.cshtml.cs new file mode 100644 index 0000000..880902b --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Cpdlc/Messages.cshtml.cs @@ -0,0 +1,48 @@ +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Web.Pages.ViewModels; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Cpdlc; + +public class MessagesModel : PageModel +{ + private const int PageSize = 50; + + private readonly IAircraftRepository _aircraftRepository; + private readonly IDialogueRepository _dialogueRepository; + + public MessagesModel(IAircraftRepository aircraftRepository, IDialogueRepository dialogueRepository) + { + _aircraftRepository = aircraftRepository; + _dialogueRepository = dialogueRepository; + } + + [BindProperty(SupportsGet = true)] + public int PageNumber { get; set; } = 1; + + public List Messages { get; private set; } = []; + public PaginationViewModel Pagination { get; private set; } = new("/cpdlc/messages", 1, 1); + + public async Task OnGetAsync(CancellationToken cancellationToken) + { + var aircraft = await _aircraftRepository.All(cancellationToken); + var dialogues = await _dialogueRepository.All(cancellationToken); + + var aircraftLookup = aircraft.ToDictionary(a => a.Callsign, a => a); + var allMessages = dialogues + .SelectMany(d => d.Messages.Select(m => MessageRowViewModel.From(d, m, aircraftLookup))) + .OrderByDescending(m => m.Timestamp) + .ToList(); + + var totalPages = (int)Math.Ceiling(allMessages.Count / (double)PageSize); + PageNumber = Math.Clamp(PageNumber, 1, Math.Max(1, totalPages)); + Pagination = new PaginationViewModel("/cpdlc/messages", PageNumber, totalPages); + + Messages = allMessages + .Skip((PageNumber - 1) * PageSize) + .Take(PageSize) + .ToList(); + } +} diff --git a/source/CPDLCServer/Web/Pages/Cpdlc/Stations/Index.cshtml b/source/CPDLCServer/Web/Pages/Cpdlc/Stations/Index.cshtml new file mode 100644 index 0000000..539da1d --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Cpdlc/Stations/Index.cshtml @@ -0,0 +1,46 @@ +@page "/cpdlc/stations/{stationId}" +@model IndexModel +@{ + ViewData["Title"] = Model.StationId; +} + +

@Model.StationId

+ +@if (Model.Controllers.Length > 0) +{ +
+
Controllers
+
+
+ + + + + + + + + @foreach (var controller in Model.Controllers) + { + + + + + } + +
CallsignController
@controller.Callsign@controller.Name (@controller.Cid)
+
+
+
+} +else +{ +
No controllers are connected to @Model.StationId.
+} + +
+
Messages
+
+ +
+
diff --git a/source/CPDLCServer/Pages/Atsu/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Cpdlc/Stations/Index.cshtml.cs similarity index 75% rename from source/CPDLCServer/Pages/Atsu/Index.cshtml.cs rename to source/CPDLCServer/Web/Pages/Cpdlc/Stations/Index.cshtml.cs index 70825ac..72bf4b9 100644 --- a/source/CPDLCServer/Pages/Atsu/Index.cshtml.cs +++ b/source/CPDLCServer/Web/Pages/Cpdlc/Stations/Index.cshtml.cs @@ -1,10 +1,11 @@ -using CPDLCServer.Model; -using CPDLCServer.Pages.ViewModels; -using CPDLCServer.Persistence; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Web.Pages.ViewModels; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -namespace CPDLCServer.Pages.Dashboard.Atsu; +namespace CPDLCServer.Web.Pages.Cpdlc.Stations; public class IndexModel : PageModel { @@ -37,14 +38,11 @@ public async Task OnGetAsync(string stationId, CancellationToken Controllers = controllers.Where(c => c.StationId == stationId).ToArray(); var aircraftLookup = aircraft.ToDictionary(a => a.Callsign, a => a); - var aircraftAtStation = aircraft - .Where(a => a.StationId == stationId) - .Select(a => a.Callsign) - .ToHashSet(); + // The dialogues stay after the aircraft disconnects, so find them by their own station Messages = dialogues - .Where(d => aircraftAtStation.Contains(d.AircraftCallsign)) - .SelectMany(d => d.Messages.Select(m => Dashboard.Messages.IndexModel.ToViewModel(d, m, aircraftLookup))) + .Where(d => d.StationId == stationId) + .SelectMany(d => d.Messages.Select(m => MessageRowViewModel.From(d, m, aircraftLookup))) .OrderByDescending(m => m.Timestamp) .ToList(); diff --git a/source/CPDLCServer/Web/Pages/Index.cshtml b/source/CPDLCServer/Web/Pages/Index.cshtml new file mode 100644 index 0000000..fb613a1 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Index.cshtml @@ -0,0 +1,2 @@ +@page "/" +@model IndexModel diff --git a/source/CPDLCServer/Web/Pages/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Index.cshtml.cs new file mode 100644 index 0000000..a71ba6d --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Index.cshtml.cs @@ -0,0 +1,13 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages; + +// The CPDLC overview is the start page +public class IndexModel : PageModel +{ + public IActionResult OnGet() + { + return Redirect("/cpdlc"); + } +} diff --git a/source/CPDLCServer/Web/Pages/Plugin/Authorize.cshtml b/source/CPDLCServer/Web/Pages/Plugin/Authorize.cshtml new file mode 100644 index 0000000..6a056e2 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Plugin/Authorize.cshtml @@ -0,0 +1,30 @@ +@page "/plugin/authorize" +@model AuthorizeModel +@{ + ViewData["Title"] = "Connect the plugin"; + Layout = "_CenteredLayout"; +} + +@if (!Model.IsValidRequest) +{ +

The request is not valid

+

Start the authentication again from the SETUP window of the CPDLC plugin in vatSys.

+} +else +{ +

Connect the vatSys plugin

+

+ The CPDLC plugin on this computer will connect to the server as + @User.GetName() (@User.GetCid()). +

+

Continue only if you started the authentication from the SETUP window in vatSys.

+ +
+ @* The same names as the query string of the GET request *@ + + + + + +
+} diff --git a/source/CPDLCServer/Web/Pages/Plugin/Authorize.cshtml.cs b/source/CPDLCServer/Web/Pages/Plugin/Authorize.cshtml.cs new file mode 100644 index 0000000..41de16e --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Plugin/Authorize.cshtml.cs @@ -0,0 +1,51 @@ +using CPDLCServer.Auth; +using CPDLCServer.Auth.PluginTokens; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Plugin; + +// The browser part of the plugin login. The user logs in with VATSIM, then allows the plugin to connect. +// Then the browser goes to the plugin on this computer with a one-use code. +public class AuthorizeModel : PageModel +{ + private readonly PluginAuthorizationCodes _authorizationCodes; + + public AuthorizeModel(PluginAuthorizationCodes authorizationCodes) + { + _authorizationCodes = authorizationCodes; + } + + [BindProperty(SupportsGet = true, Name = "redirect_uri")] + public string? RedirectUri { get; set; } + + [BindProperty(SupportsGet = true, Name = "state")] + public string? State { get; set; } + + [BindProperty(SupportsGet = true, Name = "code_challenge")] + public string? CodeChallenge { get; set; } + + [BindProperty(SupportsGet = true, Name = "code_challenge_method")] + public string? CodeChallengeMethod { get; set; } + + public bool IsValidRequest => + PluginRedirectUri.IsValid(RedirectUri) && + !string.IsNullOrEmpty(State) && + !string.IsNullOrEmpty(CodeChallenge) && + CodeChallengeMethod == "S256"; + + public void OnGet() + { + } + + public IActionResult OnPost() + { + if (!IsValidRequest) + return Page(); + + var code = _authorizationCodes.Create(User.GetCid()!, User.GetName(), RedirectUri!, CodeChallenge!); + + var redirectUri = $"{RedirectUri}?code={Uri.EscapeDataString(code)}&state={Uri.EscapeDataString(State!)}"; + return Redirect(redirectUri); + } +} diff --git a/source/CPDLCServer/Web/Pages/Privacy.cshtml b/source/CPDLCServer/Web/Pages/Privacy.cshtml new file mode 100644 index 0000000..0ea0cf1 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Privacy.cshtml @@ -0,0 +1,193 @@ +@page "/privacy" +@model PrivacyModel +@{ + ViewData["Title"] = "Privacy policy"; + ViewData["Wide"] = true; + Layout = "_CenteredLayout"; + + var operatorName = string.IsNullOrWhiteSpace(Model.Settings.OperatorName) ? "the operator of this server" : Model.Settings.OperatorName; + var contact = Model.Settings.PrivacyContact; + + string Hours(TimeSpan time) => time.TotalHours == 1 ? "1 hour" : $"{time.TotalHours:0.#} hours"; + string Days(TimeSpan time) => $"{time.TotalDays:0} days"; +} + +

Privacy policy

+ +
+ @Model.Settings.ServerName is a third-party service. + It is not provided, operated or endorsed by VATSIM. +
+ +

About this service

+

+ This server relays CPDLC and ADS-C messages between air traffic controllers on VATSIM and aircraft on the + ACARS network. @operatorName operates this server. In this policy, "the operator" is + @operatorName. +

+@if (!string.IsNullOrWhiteSpace(contact)) +{ +

+ For questions about your data, or to ask the operator to delete your data, use this contact: + @contact. +

+} +

+ The server uses the open source CPDLC Plugin software. + The authors of the software do not operate this server, and they cannot see its data. +

+ +

The data that the server collects

+
    +
  • + Your VATSIM account. You log in with VATSIM Connect. VATSIM gives the server your CID and + your full name. The server also asks VATSIM for your VATSIM details (for example, your rating and division), + but it does not use or keep them. The server does not get your email address or your password. +
  • +
  • + Controllers. When you connect with the vatSys plugin, the server records your CID, your name, + your callsign and your station while you are connected. +
  • +
  • + Administrators. The server records the CID and the name of each administrator, and the date + when they became an administrator. +
  • +
  • + Flight data. The server receives aircraft callsigns, CPDLC messages and ADS-C reports + (position, level and time) from the ACARS network. + @if (Model.Settings.VatsimStatusEnabled) + { + It also reads aircraft positions from the public VATSIM status data. + } + CPDLC messages can contain free text from pilots and controllers. +
  • +
  • + Logs. The server log records events, for example logins, plugin connections and messages. + A log entry can contain your CID, your name, your callsign and the text of a message. +
  • +
  • + Cookies. The server uses only the cookies that are necessary for it to operate: one cookie + that keeps you logged in, and short-term cookies that protect the login and the forms. The server does not use + cookies for analytics or advertising. +
  • +
  • + IP addresses. The server does not record your IP address. The hosting provider of the server + can record it (see Third parties). +
  • +
+ +

How the server uses the data

+

The server uses the data only to operate the service:

+
    +
  • to identify you, and to give administrators access to the configuration,
  • +
  • to relay CPDLC and ADS-C messages between controllers and aircraft,
  • +
  • to show the connected controllers and aircraft, and the messages,
  • +
  • to find and correct problems.
  • +
+

The operator does not sell the data, and does not use it for advertising or analytics.

+ +

Who can see the data

+
    +
  • + Each VATSIM user who logs in to this server can see the CPDLC and ADS-C pages. These pages show the name and + the CID of each connected controller, the callsigns of the aircraft, the CPDLC messages and the ADS-C data. +
  • +
  • Controllers who use the plugin see the CPDLC messages and the ADS-C data of the aircraft.
  • +
  • Administrators can also see the server log and the raw messages to and from the ACARS network.
  • +
+ +

Third parties

+
    +
  • VATSIM operates VATSIM Connect, which identifies you when you log in.
  • +
  • + The ACARS network (for example, Hoppie's ACARS) + carries the CPDLC and ADS-C messages to and from the aircraft. It receives the station, the callsigns and + the messages. It does not receive your CID or your name. +
  • +
  • The hosting provider of the server stores the database and can record network data, for example IP addresses.
  • +
  • + jsDelivr (cdn.jsdelivr.net) supplies the styles and scripts of the web pages. Your browser + downloads them from jsDelivr, so jsDelivr receives your IP address. +
  • +
+ +

How long the server keeps the data

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
DataKept
Login cookieUntil you log out, or after @Hours(Model.SessionLifetime) without activity. A restart of the server also logs out all users.
Plugin authentication (CID, name and token)The token is valid for @Days(Model.PluginTokenLifetime). When you select Log out in the plugin, the server deletes it. The record of an expired token stays in the database.
AdministratorsUntil an administrator removes them.
Connected controllersOnly in memory, until the controller disconnects.
Aircraft connectionsUntil the connection ends, or after @Model.Settings.AircraftConnectionTimeoutMinutes minutes without contact from the aircraft.
CPDLC messages@Model.Settings.DialogueRetentionHours hours from the start of the dialogue.
ADS-C contracts and reportsUntil the contract ends, or after @Model.Settings.AdscContractTimeoutMinutes minutes without ADS-C activity. The server keeps only the latest report of each contract.
ADS-C message logOnly in memory, for @Hours(Model.AdscMessageLogRetention), and not more than the last @Model.AdscMessageLogCapacity messages.
Server logOnly in memory, the last @Model.LogCapacity entries. A restart deletes them. The hosting provider can keep a copy of the log output for a period that the operator sets.
Raw ACARS messagesOnly in memory, the last @Model.TrafficLogCapacity requests of each ACARS connection. A restart deletes them.
+
+

+ The vatSys plugin keeps your token on your computer, encrypted for your Windows account. The plugin log on your + computer is kept for 5 days by default. +

+ +

Security

+

+ The server keeps only a hash of each plugin token. It encrypts the ACARS network codes with a key that is not in + the database. Use the server only over HTTPS. +

+ +

Your choices

+
    +
  • To remove the plugin authentication, select Log out in the SETUP window of the plugin.
  • + @if (!string.IsNullOrWhiteSpace(contact)) + { +
  • To ask for a copy of your data, or to ask the operator to delete it, use the contact: @contact.
  • + } + else + { +
  • To ask for a copy of your data, or to ask the operator to delete it, speak to an administrator of this server.
  • + } +
  • If you do not accept this policy, do not log in to this server and do not connect the plugin to it.
  • +
+ +

Changes to this policy

+

The operator can change this policy. This page always shows the current policy.

diff --git a/source/CPDLCServer/Web/Pages/Privacy.cshtml.cs b/source/CPDLCServer/Web/Pages/Privacy.cshtml.cs new file mode 100644 index 0000000..a77671a --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Privacy.cshtml.cs @@ -0,0 +1,39 @@ +using CPDLCServer.AcarsConnections.Traffic; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.MessageLog; +using CPDLCServer.Auth; +using CPDLCServer.Auth.PluginTokens; +using CPDLCServer.Logging; +using CPDLCServer.Settings; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages; + +// The privacy policy. The values come from the settings and the code, so the page is correct when they change. +public class PrivacyModel : PageModel +{ + private readonly IServerSettingsProvider _settingsProvider; + private readonly LogBuffer _logBuffer; + private readonly AcarsTrafficLog _trafficLog; + + public PrivacyModel(IServerSettingsProvider settingsProvider, LogBuffer logBuffer, AcarsTrafficLog trafficLog) + { + _settingsProvider = settingsProvider; + _logBuffer = logBuffer; + _trafficLog = trafficLog; + } + + public ServerSettings Settings { get; private set; } = new(); + + public TimeSpan SessionLifetime => AuthServiceCollectionExtensions.SessionLifetime; + public TimeSpan PluginTokenLifetime => PluginToken.Lifetime; + public TimeSpan AdscMessageLogRetention => PurgeExpiredAdscDataRequestHandler.MessageLogRetention; + public int AdscMessageLogCapacity => InMemoryAdscMessageLogRepository.Capacity; + public int LogCapacity => _logBuffer.Capacity; + public int TrafficLogCapacity => _trafficLog.Capacity; + + public async Task OnGetAsync(CancellationToken cancellationToken) + { + Settings = await _settingsProvider.Load(cancellationToken); + } +} diff --git a/source/CPDLCServer/Web/Pages/Setup/Index.cshtml b/source/CPDLCServer/Web/Pages/Setup/Index.cshtml new file mode 100644 index 0000000..0af28d9 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Setup/Index.cshtml @@ -0,0 +1,36 @@ +@page "/setup" +@model IndexModel +@{ + ViewData["Title"] = "Setup"; + Layout = "_CenteredLayout"; +} + +

Set up the server

+

You can do the setup only one time. You can change the operator details later in Configuration → Settings.

+ + + +
+
+ + +
The VATSIM CID of the first administrator. That person logs in with VATSIM and can add more administrators.
+ +
+ +
+ + +
The person or organisation that operates this server, for example a VATSIM division or FIR. The privacy policy shows it.
+ +
+ +
+ + +
An email address or a URL. Users use it to ask questions about their data, or to ask you to delete it.
+ +
+ + +
diff --git a/source/CPDLCServer/Web/Pages/Setup/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Setup/Index.cshtml.cs new file mode 100644 index 0000000..4c8f728 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Setup/Index.cshtml.cs @@ -0,0 +1,82 @@ +using System.ComponentModel.DataAnnotations; +using CPDLCServer.Auth; +using CPDLCServer.Infrastructure; +using CPDLCServer.Settings; +using CPDLCServer.Setup; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Setup; + +// The setup adds the first administrator and the operator details. After the setup, the page does not exist. +public class IndexModel : PageModel +{ + private readonly SetupState _setupState; + private readonly IUnitOfWorkMediator _mediator; + private readonly ILogger _logger; + + public IndexModel( + SetupState setupState, + IUnitOfWorkMediator mediator, + ILogger logger) + { + _setupState = setupState; + _mediator = mediator; + _logger = logger; + } + + [BindProperty] + public SetupInput Input { get; set; } = new(); + + public IActionResult OnGet() + { + if (_setupState.IsConfigured) + return NotFound(); + + return Page(); + } + + public async Task OnPostAsync(CancellationToken cancellationToken) + { + if (_setupState.IsConfigured) + return NotFound(); + + if (!ModelState.IsValid) + return Page(); + + try + { + await _mediator.Send( + new CompleteSetupCommand(Input.Cid!, Input.OperatorName, Input.PrivacyContact), + cancellationToken); + } + catch (InvalidOperationException ex) + { + // Another person completed the setup first + _logger.Warning(ex, "Failed to complete the setup"); + return NotFound(); + } + + return Redirect("/login"); + } + + public class SetupInput + { + [Required(ErrorMessage = "Enter a CID.")] + [StringLength(VatsimCid.MaxLength)] + [RegularExpression(VatsimCid.Pattern, ErrorMessage = VatsimCid.ErrorMessage)] + [Display(Name = "Administrator CID")] + public string? Cid { get; set; } + + [Required(ErrorMessage = "Enter the operator name.")] + [StringLength(ServerSettings.MaxOperatorNameLength)] + [Display(Name = "Operator name")] + public string OperatorName { get; set; } = string.Empty; + + [Required(ErrorMessage = "Enter a privacy contact.")] + [StringLength(ServerSettings.MaxPrivacyContactLength)] + [PrivacyContact] + [Display(Name = "Privacy contact")] + public string PrivacyContact { get; set; } = string.Empty; + } +} diff --git a/source/CPDLCServer/Web/Pages/Shared/_Branding.cshtml b/source/CPDLCServer/Web/Pages/Shared/_Branding.cshtml new file mode 100644 index 0000000..617b8c5 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Shared/_Branding.cshtml @@ -0,0 +1,15 @@ +@model CPDLCServer.Settings.BrandingInfo + +@* The banner or the server name, then the message of the day. The sidebar and the login page show it. *@ + + @if (Model.HasBanner) + { + @Model.ServerName + } + else + { + @Model.ServerName + } + + + diff --git a/source/CPDLCServer/Web/Pages/Shared/_CenteredLayout.cshtml b/source/CPDLCServer/Web/Pages/Shared/_CenteredLayout.cshtml new file mode 100644 index 0000000..6e47d0e --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Shared/_CenteredLayout.cshtml @@ -0,0 +1,34 @@ +@inject IServerSettingsProvider SettingsProvider +@{ + var branding = await SettingsProvider.LoadBranding(Context.RequestAborted); +} +@* For the pages without the sidebar: login, setup and plugin authorization *@ + + + + + + @ViewData["Title"] - @branding.ServerName + + + +
+
+ @* A page with much text, for example the privacy policy, sets ViewData["Wide"] *@ +
+
+ +
+
+
+ @RenderBody() +
+
+
+ +
+
+
+
+ + diff --git a/source/CPDLCServer/Web/Pages/Shared/_Disclaimer.cshtml b/source/CPDLCServer/Web/Pages/Shared/_Disclaimer.cshtml new file mode 100644 index 0000000..96df7eb --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Shared/_Disclaimer.cshtml @@ -0,0 +1,5 @@ +@* The VATSIM disclaimer and the link to the privacy policy. It shows on each page. *@ +

+ This server is a third-party service. It is not provided, operated or endorsed by VATSIM. + Privacy policy +

diff --git a/source/CPDLCServer/Web/Pages/Shared/_Layout.cshtml b/source/CPDLCServer/Web/Pages/Shared/_Layout.cshtml new file mode 100644 index 0000000..5f8674b --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Shared/_Layout.cshtml @@ -0,0 +1,99 @@ +@using Microsoft.AspNetCore.Authorization +@inject IServerSettingsProvider SettingsProvider +@inject IAuthorizationService AuthorizationService +@{ + var branding = await SettingsProvider.LoadBranding(Context.RequestAborted); + var isAdministrator = (await AuthorizationService.AuthorizeAsync(User, AdministratorRequirement.PolicyName)).Succeeded; + var path = Context.Request.Path; + + // "exact" is for a page that has sub-pages in a different menu item + string NavLink(string href, bool exact = false) + { + var isActive = exact + ? string.Equals(path.Value?.TrimEnd('/'), href, StringComparison.OrdinalIgnoreCase) + : path.StartsWithSegments(href, StringComparison.OrdinalIgnoreCase); + return isActive ? "nav-link active" : "nav-link link-body-emphasis"; + } +} + + + + + + @ViewData["Title"] - @branding.ServerName + + + +
+ + +
+
+ + @branding.ServerName +
+ +
+ @RenderBody() +
+
+
+ + + @await RenderSectionAsync("Scripts", required: false) + + diff --git a/source/CPDLCServer/Web/Pages/Shared/_MessageTable.cshtml b/source/CPDLCServer/Web/Pages/Shared/_MessageTable.cshtml new file mode 100644 index 0000000..51ce03d --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Shared/_MessageTable.cshtml @@ -0,0 +1,55 @@ +@model IEnumerable + +@{ + string GetAlertBadgeClass(string alertType) => alertType switch + { + "High" => "text-bg-danger", + "Medium" => "text-bg-warning", + "Low" => "text-bg-info", + _ => "text-bg-light" + }; +} + +@if (!Model.Any()) +{ +

No messages.

+} +else +{ +
+ + + + + + + + + + + + + + + + @foreach (var msg in Model) + { + + + + + + + + + + + + } + +
TimeSenderReceiverContentResponseAlertDialogueACARS connection
@msg.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")@(msg.IsUplink ? "↑" : "↓")@msg.Sender@msg.Receiver@msg.Content@msg.ResponseType@msg.AlertType + @msg.DialogueId.ToString()[..8] + @(msg.IsClosed ? "Closed" : "Open") + @msg.AcarsNetwork
+
+} diff --git a/source/CPDLCServer/Web/Pages/Shared/_Motd.cshtml b/source/CPDLCServer/Web/Pages/Shared/_Motd.cshtml new file mode 100644 index 0000000..d45b7e5 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Shared/_Motd.cshtml @@ -0,0 +1,12 @@ +@model string? + +@* Shows each line of the message of the day on its own line *@ +@if (!string.IsNullOrWhiteSpace(Model)) +{ +
+ @foreach (var line in Model.ReplaceLineEndings("\n").Split('\n')) + { + @line
+ } +
+} diff --git a/source/CPDLCServer/Web/Pages/Shared/_Pagination.cshtml b/source/CPDLCServer/Web/Pages/Shared/_Pagination.cshtml new file mode 100644 index 0000000..95d3d90 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Shared/_Pagination.cshtml @@ -0,0 +1,44 @@ +@model CPDLCServer.Web.Pages.ViewModels.PaginationViewModel + +@if (Model.TotalPages > 1) +{ + var startPage = Math.Max(1, Model.CurrentPage - 2); + var endPage = Math.Min(Model.TotalPages, Model.CurrentPage + 2); + + +} diff --git a/source/CPDLCServer/Web/Pages/ViewModels/MessageRowViewModel.cs b/source/CPDLCServer/Web/Pages/ViewModels/MessageRowViewModel.cs new file mode 100644 index 0000000..781df8f --- /dev/null +++ b/source/CPDLCServer/Web/Pages/ViewModels/MessageRowViewModel.cs @@ -0,0 +1,58 @@ +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; + +namespace CPDLCServer.Web.Pages.ViewModels; + +public record MessageRowViewModel( + Guid DialogueId, + DateTimeOffset Timestamp, + string AcarsNetwork, + bool IsUplink, + string Sender, + string Receiver, + string AlertType, + string ResponseType, + string Content, + bool IsClosed) +{ + public static MessageRowViewModel From( + CPDLCServer.Cpdlc.Dialogues.Dialogue dialogue, + CpdlcMessage message, + Dictionary aircraftLookup) + { + var aircraft = aircraftLookup.GetValueOrDefault(dialogue.AircraftCallsign); + var acarsNetwork = aircraft?.AcarsConnectionId ?? "Unknown"; + var stationId = aircraft?.StationId ?? "Unknown"; + + return message switch + { + UplinkMessage uplink => new MessageRowViewModel( + DialogueId: dialogue.Id, + Timestamp: uplink.Sent, + AcarsNetwork: acarsNetwork, + IsUplink: true, + Sender: $"{stationId} ({uplink.SenderCallsign})", + Receiver: uplink.Recipient, + AlertType: uplink.AlertType.ToString(), + ResponseType: uplink.ResponseType.ToString(), + Content: uplink.Content, + IsClosed: uplink.IsClosed), + + DownlinkMessage downlink => new MessageRowViewModel( + DialogueId: dialogue.Id, + Timestamp: downlink.Received, + AcarsNetwork: acarsNetwork, + IsUplink: false, + Sender: downlink.Sender, + Receiver: stationId, + AlertType: downlink.AlertType.ToString(), + ResponseType: downlink.ResponseType.ToString(), + Content: downlink.Content, + IsClosed: downlink.IsClosed), + + _ => throw new InvalidOperationException("Unknown message type") + }; + } +} diff --git a/source/CPDLCServer/Web/Pages/ViewModels/PaginationViewModel.cs b/source/CPDLCServer/Web/Pages/ViewModels/PaginationViewModel.cs new file mode 100644 index 0000000..096f22e --- /dev/null +++ b/source/CPDLCServer/Web/Pages/ViewModels/PaginationViewModel.cs @@ -0,0 +1,7 @@ +namespace CPDLCServer.Web.Pages.ViewModels; + +// The page links below a table. The path is the page URL without the query string. +public record PaginationViewModel(string Path, int CurrentPage, int TotalPages) +{ + public string Url(int pageNumber) => $"{Path}?pageNumber={pageNumber}"; +} diff --git a/source/CPDLCServer/Web/Pages/_ViewImports.cshtml b/source/CPDLCServer/Web/Pages/_ViewImports.cshtml new file mode 100644 index 0000000..e6a451c --- /dev/null +++ b/source/CPDLCServer/Web/Pages/_ViewImports.cshtml @@ -0,0 +1,4 @@ +@namespace CPDLCServer.Web.Pages +@using CPDLCServer.Auth +@using CPDLCServer.Settings +@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers diff --git a/source/CPDLCServer/Pages/_ViewStart.cshtml b/source/CPDLCServer/Web/Pages/_ViewStart.cshtml similarity index 100% rename from source/CPDLCServer/Pages/_ViewStart.cshtml rename to source/CPDLCServer/Web/Pages/_ViewStart.cshtml diff --git a/source/CPDLCServer/Web/WebServiceCollectionExtensions.cs b/source/CPDLCServer/Web/WebServiceCollectionExtensions.cs new file mode 100644 index 0000000..a75cd6b --- /dev/null +++ b/source/CPDLCServer/Web/WebServiceCollectionExtensions.cs @@ -0,0 +1,27 @@ +using CPDLCServer.Auth; + +namespace CPDLCServer.Web; + +public static class WebServiceCollectionExtensions +{ + public static IServiceCollection AddWeb(this IServiceCollection services) + { + services.AddSignalR().AddJsonProtocol(); + services.AddRazorPages(options => + { + options.RootDirectory = "/Web/Pages"; + + // Any VATSIM user that is logged in can open the pages + options.Conventions.AuthorizeFolder("/"); + options.Conventions.AllowAnonymousToPage("/Account/Login"); + options.Conventions.AllowAnonymousToPage("/Account/Logout"); + options.Conventions.AllowAnonymousToPage("/Setup/Index"); + options.Conventions.AllowAnonymousToPage("/Privacy"); + + // Only an administrator can open the Configuration area + options.Conventions.AuthorizeFolder("/Configuration", AdministratorRequirement.PolicyName); + }); + + return services; + } +}