From e9927528e99d6a6a10ad64b022923cdba9c2dbbd Mon Sep 17 00:00:00 2001 From: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Sat, 2 Mar 2024 19:10:14 +0100 Subject: [PATCH] Initial commit --- .gitattributes | 2 + .gitignore | 398 ++++++++++++++++++ LICENSE | 21 + README.md | 2 + .../Program.cs | 63 +++ .../StoneRed.NetificationApi.Example.csproj | 14 + src/StoneRed.NetificationApi.sln | 31 ++ .../Client/Models/NotificationReceivedData.cs | 11 + .../Models/NotificationsReceivedEventArgs.cs | 6 + .../Client/NotificationApiClient.cs | 97 +++++ .../Payloads/NotificationsReceivedPayload.cs | 8 + .../Client/WebsocketMessage.cs | 39 ++ .../Server/IdentifyUser/IdentifyUserData.cs | 28 ++ .../IdentifyUser/NotificationPushProviders.cs | 7 + .../IdentifyUser/NotificationPushToken.cs | 22 + .../NotificationPushTokenDevice.cs | 30 ++ .../IdentifyUser/NotificationWebPushToken.cs | 18 + .../NotificationWebPushTokenKeys.cs | 20 + .../NotificationWebPushTokenSub.cs | 20 + .../Server/NotificationApiServer.cs | 82 ++++ .../Server/Retract/RetractNotificationData.cs | 23 + .../Server/Send/NotificationApnOptions.cs | 18 + .../Send/NotificationEmailAttachments.cs | 21 + .../Server/Send/NotificationEmailOptions.cs | 12 + .../Send/NotificationFcmAndroidOptions.cs | 10 + .../Server/Send/NotificationFcmOptions.cs | 6 + .../Server/Send/NotificationOptions.cs | 8 + .../Server/Send/NotificationUser.cs | 24 ++ .../Server/Send/SendNotificationData.cs | 30 ++ .../NotificationPreference.cs | 26 ++ .../SetUserPreferencesData.cs | 23 + .../Shared/NotificationChannels.cs | 11 + .../StoneRed.NetificationApi.csproj | 13 + .../Utilities/Configuration.cs | 18 + .../Utilities/DateTimeConverter.cs | 17 + .../Utilities/UserIdHasher.cs | 13 + .../Utilities/WebsocketMessageComparer.cs | 20 + .../Utilities/WebsocketMessageConverter.cs | 13 + 38 files changed, 1225 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 src/StoneRed.NetificationApi.Example/Program.cs create mode 100644 src/StoneRed.NetificationApi.Example/StoneRed.NetificationApi.Example.csproj create mode 100644 src/StoneRed.NetificationApi.sln create mode 100644 src/StoneRed.NetificationApi/Client/Models/NotificationReceivedData.cs create mode 100644 src/StoneRed.NetificationApi/Client/Models/NotificationsReceivedEventArgs.cs create mode 100644 src/StoneRed.NetificationApi/Client/NotificationApiClient.cs create mode 100644 src/StoneRed.NetificationApi/Client/Payloads/NotificationsReceivedPayload.cs create mode 100644 src/StoneRed.NetificationApi/Client/WebsocketMessage.cs create mode 100644 src/StoneRed.NetificationApi/Server/IdentifyUser/IdentifyUserData.cs create mode 100644 src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationPushProviders.cs create mode 100644 src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationPushToken.cs create mode 100644 src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationPushTokenDevice.cs create mode 100644 src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationWebPushToken.cs create mode 100644 src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationWebPushTokenKeys.cs create mode 100644 src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationWebPushTokenSub.cs create mode 100644 src/StoneRed.NetificationApi/Server/NotificationApiServer.cs create mode 100644 src/StoneRed.NetificationApi/Server/Retract/RetractNotificationData.cs create mode 100644 src/StoneRed.NetificationApi/Server/Send/NotificationApnOptions.cs create mode 100644 src/StoneRed.NetificationApi/Server/Send/NotificationEmailAttachments.cs create mode 100644 src/StoneRed.NetificationApi/Server/Send/NotificationEmailOptions.cs create mode 100644 src/StoneRed.NetificationApi/Server/Send/NotificationFcmAndroidOptions.cs create mode 100644 src/StoneRed.NetificationApi/Server/Send/NotificationFcmOptions.cs create mode 100644 src/StoneRed.NetificationApi/Server/Send/NotificationOptions.cs create mode 100644 src/StoneRed.NetificationApi/Server/Send/NotificationUser.cs create mode 100644 src/StoneRed.NetificationApi/Server/Send/SendNotificationData.cs create mode 100644 src/StoneRed.NetificationApi/Server/SetUserPreferences/NotificationPreference.cs create mode 100644 src/StoneRed.NetificationApi/Server/SetUserPreferences/SetUserPreferencesData.cs create mode 100644 src/StoneRed.NetificationApi/Shared/NotificationChannels.cs create mode 100644 src/StoneRed.NetificationApi/StoneRed.NetificationApi.csproj create mode 100644 src/StoneRed.NetificationApi/Utilities/Configuration.cs create mode 100644 src/StoneRed.NetificationApi/Utilities/DateTimeConverter.cs create mode 100644 src/StoneRed.NetificationApi/Utilities/UserIdHasher.cs create mode 100644 src/StoneRed.NetificationApi/Utilities/WebsocketMessageComparer.cs create mode 100644 src/StoneRed.NetificationApi/Utilities/WebsocketMessageConverter.cs diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..426d76d --- /dev/null +++ b/.gitignore @@ -0,0 +1,398 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..db33ee8 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Stone_Red + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..fcef101 --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# StoneRed.NetificationApi + A .NET librarly for NotificationAPI diff --git a/src/StoneRed.NetificationApi.Example/Program.cs b/src/StoneRed.NetificationApi.Example/Program.cs new file mode 100644 index 0000000..6d1629f --- /dev/null +++ b/src/StoneRed.NetificationApi.Example/Program.cs @@ -0,0 +1,63 @@ +using StoneRed.NetificationApi.Client; +using StoneRed.NetificationApi.Client.Models; +using StoneRed.NetificationApi.Server; +using StoneRed.NetificationApi.Server.IdentifyUser; +using StoneRed.NetificationApi.Server.Send; + +const string userId = ""; +const string notificationId = ""; +const string clientId = ""; +const string clientSecret = ""; + +Console.WriteLine("Start client"); +NotificationApiClient notificationApiClient = new NotificationApiClient("test", clientId, clientSecret, false); +await notificationApiClient.Start(); +Console.WriteLine("Client started"); + +notificationApiClient.RequestNotifications(); + +notificationApiClient.RequestedNotificationsReceived += (sender, args) => +{ + Console.WriteLine("Requested notifications received"); + foreach (NotificationReceivedData notificationReceiveData in args.Notifications) + { + Console.WriteLine($"Notification received: {notificationReceiveData.Id}"); + } +}; + +notificationApiClient.NewNotificationsReceived += (sender, args) => +{ + Console.WriteLine("New notifications received"); + foreach (NotificationReceivedData notificationReceiveData in args.Notifications) + { + Console.WriteLine($"New Notification received: {notificationReceiveData.Id}"); + } +}; + +NotificationApiServer notificationApiServer = new NotificationApiServer(clientId, clientSecret, false); + +Console.WriteLine("Identify user"); +await notificationApiServer.Identify(new IdentifyUserData +{ + UserId = userId, + Email = "kek123@stone-red.net" +}); +Console.WriteLine("User identified"); + +Console.WriteLine("Send notification"); +SendNotificationData sendNotificationData = new SendNotificationData +{ + NotificationId = notificationId, + User = new NotificationUser + { + Id = userId + } +}; + +await notificationApiServer.Send(sendNotificationData); +Console.WriteLine("Notification sent"); + +Console.ReadLine(); +Console.WriteLine("Stop client"); +await notificationApiClient.Stop(); +Console.WriteLine("Client stopped"); \ No newline at end of file diff --git a/src/StoneRed.NetificationApi.Example/StoneRed.NetificationApi.Example.csproj b/src/StoneRed.NetificationApi.Example/StoneRed.NetificationApi.Example.csproj new file mode 100644 index 0000000..ca8e26a --- /dev/null +++ b/src/StoneRed.NetificationApi.Example/StoneRed.NetificationApi.Example.csproj @@ -0,0 +1,14 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + diff --git a/src/StoneRed.NetificationApi.sln b/src/StoneRed.NetificationApi.sln new file mode 100644 index 0000000..4adf35c --- /dev/null +++ b/src/StoneRed.NetificationApi.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.9.34616.47 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StoneRed.NetificationApi", "StoneRed.NetificationApi\StoneRed.NetificationApi.csproj", "{DED64841-1673-47C9-99E4-BD0DC01C1F2E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StoneRed.NetificationApi.Example", "StoneRed.NetificationApi.Example\StoneRed.NetificationApi.Example.csproj", "{8A7CD1F7-78E4-4265-A10A-E116D6639078}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DED64841-1673-47C9-99E4-BD0DC01C1F2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DED64841-1673-47C9-99E4-BD0DC01C1F2E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DED64841-1673-47C9-99E4-BD0DC01C1F2E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DED64841-1673-47C9-99E4-BD0DC01C1F2E}.Release|Any CPU.Build.0 = Release|Any CPU + {8A7CD1F7-78E4-4265-A10A-E116D6639078}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8A7CD1F7-78E4-4265-A10A-E116D6639078}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8A7CD1F7-78E4-4265-A10A-E116D6639078}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8A7CD1F7-78E4-4265-A10A-E116D6639078}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {35AE5460-29CB-4E09-A2AA-9055E6FBEF12} + EndGlobalSection +EndGlobal diff --git a/src/StoneRed.NetificationApi/Client/Models/NotificationReceivedData.cs b/src/StoneRed.NetificationApi/Client/Models/NotificationReceivedData.cs new file mode 100644 index 0000000..bfadba8 --- /dev/null +++ b/src/StoneRed.NetificationApi/Client/Models/NotificationReceivedData.cs @@ -0,0 +1,11 @@ +namespace StoneRed.NetificationApi.Client.Models; + +public class NotificationReceivedData +{ + public required string Id { get; set; } + public required bool Seen { get; set; } + public required string Title { get; set; } + public required string RedirectURL { get; set; } + public required string ImageURL { get; set; } + public required DateTime Date { get; set; } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Client/Models/NotificationsReceivedEventArgs.cs b/src/StoneRed.NetificationApi/Client/Models/NotificationsReceivedEventArgs.cs new file mode 100644 index 0000000..6728dbd --- /dev/null +++ b/src/StoneRed.NetificationApi/Client/Models/NotificationsReceivedEventArgs.cs @@ -0,0 +1,6 @@ +namespace StoneRed.NetificationApi.Client.Models; + +public class NotificationsReceivedEventArgs(List notifications) : EventArgs +{ + public List Notifications { get; set; } = notifications; +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Client/NotificationApiClient.cs b/src/StoneRed.NetificationApi/Client/NotificationApiClient.cs new file mode 100644 index 0000000..5eeb4d1 --- /dev/null +++ b/src/StoneRed.NetificationApi/Client/NotificationApiClient.cs @@ -0,0 +1,97 @@ +using StoneRed.NetificationApi.Client.Models; +using StoneRed.NetificationApi.Client.Payloads; +using StoneRed.NetificationApi.Utilities; + +using System.Collections.Specialized; +using System.Diagnostics; +using System.Net.WebSockets; +using System.Reactive.Linq; +using System.Text.Json; +using System.Web; + +using Websocket.Client; + +namespace StoneRed.NetificationApi.Client; + +public class NotificationApiClient +{ + public event EventHandler? RequestedNotificationsReceived; + + public event EventHandler? NewNotificationsReceived; + + private readonly WebsocketClient client; + + public NotificationApiClient(string userId, string clientId, string clientSecret, bool secureMode, string baseAddress = "wss://ws.notificationapi.com") + { + UriBuilder uriBuilder = new UriBuilder(baseAddress); + + NameValueCollection query = HttpUtility.ParseQueryString(uriBuilder.Query); + query["envId"] = clientId; + query["userId"] = userId; + + if (secureMode) + { + query["userIdHash"] = UserIdHasher.Hash(userId, clientSecret); + } + + uriBuilder.Query = query.ToString(); + + client = new WebsocketClient(uriBuilder.Uri); + + _ = client.MessageReceived.Subscribe(msg => + { + Debug.WriteLine("Message:" + msg.Text); + }); + + _ = client.MessageReceived + .Where(msg => msg.Text is not null) + .Where(msg => WebsocketMessageComparer.Compare(msg.Text, "inapp_web/notifications")) + .Select(msg => WebsocketMessageConverter.ConvertWebsocketMessage(msg.Text!)) + .Subscribe(msg => + { + if (msg.Payload is null) + { + return; + } + + RequestedNotificationsReceived?.Invoke(this, new NotificationsReceivedEventArgs(msg.Payload.Notifications)); + }); + + _ = client.MessageReceived + .Where(msg => msg.Text is not null) + .Where(msg => WebsocketMessageComparer.Compare(msg.Text, "inapp_web/new_notifications")) + .Select(msg => WebsocketMessageConverter.ConvertWebsocketMessage(msg.Text!)) + .Subscribe(msg => + { + if (msg.Payload is null) + { + return; + } + + NewNotificationsReceived?.Invoke(this, new NotificationsReceivedEventArgs(msg.Payload.Notifications)); + }); + } + + public Task Start() + { + return client.StartOrFail(); + } + + public bool RequestNotifications() + { + WebsocketMessage message = new("inapp_web/notifications") + { + Payload = new + { + count = 50 + } + }; + + return client.Send(JsonSerializer.Serialize(message, Configuration.JsonSerializerOptions)); + } + + public Task Stop() + { + return client.StopOrFail(WebSocketCloseStatus.NormalClosure, "Normal closure"); + } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Client/Payloads/NotificationsReceivedPayload.cs b/src/StoneRed.NetificationApi/Client/Payloads/NotificationsReceivedPayload.cs new file mode 100644 index 0000000..adb0d1d --- /dev/null +++ b/src/StoneRed.NetificationApi/Client/Payloads/NotificationsReceivedPayload.cs @@ -0,0 +1,8 @@ +using StoneRed.NetificationApi.Client.Models; + +namespace StoneRed.NetificationApi.Client.Payloads; + +internal class NotificationsReceivedPayload +{ + public required List Notifications { get; set; } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Client/WebsocketMessage.cs b/src/StoneRed.NetificationApi/Client/WebsocketMessage.cs new file mode 100644 index 0000000..740f2f0 --- /dev/null +++ b/src/StoneRed.NetificationApi/Client/WebsocketMessage.cs @@ -0,0 +1,39 @@ +using System.Diagnostics.CodeAnalysis; + +namespace StoneRed.NetificationApi.Client; + +internal class WebsocketMessage : IWebsocketMessage +{ + public required string Route { get; set; } + + [SetsRequiredMembers] + public WebsocketMessage(string route) + { + Route = route; + } + + public WebsocketMessage() + { + } +} + +internal class WebsocketMessage : IWebsocketMessage +{ + public required string Route { get; set; } + public T? Payload { get; set; } + + [SetsRequiredMembers] + public WebsocketMessage(string route) + { + Route = route; + } + + public WebsocketMessage() + { + } +} + +internal interface IWebsocketMessage +{ + string Route { get; set; } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Server/IdentifyUser/IdentifyUserData.cs b/src/StoneRed.NetificationApi/Server/IdentifyUser/IdentifyUserData.cs new file mode 100644 index 0000000..7ce2932 --- /dev/null +++ b/src/StoneRed.NetificationApi/Server/IdentifyUser/IdentifyUserData.cs @@ -0,0 +1,28 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace StoneRed.NetificationApi.Server.IdentifyUser; + +public class IdentifyUserData +{ + [JsonIgnore] + public required string UserId { get; set; } + + public string? Email { get; set; } + + [JsonPropertyName("number")] + public string? TelephoneNumber { get; set; } + + public List? PushTokens { get; set; } + public List? WebPushTokens { get; set; } + + [SetsRequiredMembers] + public IdentifyUserData(string userId) + { + UserId = userId; + } + + public IdentifyUserData() + { + } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationPushProviders.cs b/src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationPushProviders.cs new file mode 100644 index 0000000..db6b577 --- /dev/null +++ b/src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationPushProviders.cs @@ -0,0 +1,7 @@ +namespace StoneRed.NetificationApi.Server.IdentifyUser; + +public enum NotificationPushProviders +{ + FCM, + APM +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationPushToken.cs b/src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationPushToken.cs new file mode 100644 index 0000000..39d3290 --- /dev/null +++ b/src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationPushToken.cs @@ -0,0 +1,22 @@ +using System.Diagnostics.CodeAnalysis; + +namespace StoneRed.NetificationApi.Server.IdentifyUser; + +public class NotificationPushToken +{ + public required NotificationPushProviders Type { get; set; } + public required string Token { get; set; } + public required NotificationPushTokenDevice Device { get; set; } + + [SetsRequiredMembers] + public NotificationPushToken(NotificationPushProviders type, string token, NotificationPushTokenDevice device) + { + Type = type; + Token = token; + Device = device; + } + + public NotificationPushToken() + { + } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationPushTokenDevice.cs b/src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationPushTokenDevice.cs new file mode 100644 index 0000000..08b1bd2 --- /dev/null +++ b/src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationPushTokenDevice.cs @@ -0,0 +1,30 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace StoneRed.NetificationApi.Server.IdentifyUser; + +public class NotificationPushTokenDevice +{ + [JsonPropertyName("app_id")] + public string? AppId { get; set; } + + [JsonPropertyName("ad_id")] + public string? AdId { get; set; } + + [JsonPropertyName("device_id")] + public required string DeviceId { get; set; } + + public string? Platform { get; set; } + public string? Manufacturer { get; set; } + public string? Model { get; set; } + + [SetsRequiredMembers] + public NotificationPushTokenDevice(string deviceId) + { + DeviceId = deviceId; + } + + public NotificationPushTokenDevice() + { + } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationWebPushToken.cs b/src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationWebPushToken.cs new file mode 100644 index 0000000..f91bd2d --- /dev/null +++ b/src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationWebPushToken.cs @@ -0,0 +1,18 @@ +using System.Diagnostics.CodeAnalysis; + +namespace StoneRed.NetificationApi.Server.IdentifyUser; + +public class NotificationWebPushToken +{ + public required NotificationWebPushTokenSub Sub { get; set; } + + [SetsRequiredMembers] + public NotificationWebPushToken(NotificationWebPushTokenSub sub) + { + Sub = sub; + } + + public NotificationWebPushToken() + { + } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationWebPushTokenKeys.cs b/src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationWebPushTokenKeys.cs new file mode 100644 index 0000000..c6a76a9 --- /dev/null +++ b/src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationWebPushTokenKeys.cs @@ -0,0 +1,20 @@ +using System.Diagnostics.CodeAnalysis; + +namespace StoneRed.NetificationApi.Server.IdentifyUser; + +public class NotificationWebPushTokenKeys +{ + public required string P256dh { get; set; } + public required string Auth { get; set; } + + [SetsRequiredMembers] + public NotificationWebPushTokenKeys(string p256dh, string auth) + { + P256dh = p256dh; + Auth = auth; + } + + public NotificationWebPushTokenKeys() + { + } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationWebPushTokenSub.cs b/src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationWebPushTokenSub.cs new file mode 100644 index 0000000..371c97f --- /dev/null +++ b/src/StoneRed.NetificationApi/Server/IdentifyUser/NotificationWebPushTokenSub.cs @@ -0,0 +1,20 @@ +using System.Diagnostics.CodeAnalysis; + +namespace StoneRed.NetificationApi.Server.IdentifyUser; + +public class NotificationWebPushTokenSub +{ + public required string Endpoint { get; set; } + public required NotificationWebPushTokenKeys Keys { get; set; } + + [SetsRequiredMembers] + public NotificationWebPushTokenSub(string endpoint, NotificationWebPushTokenKeys keys) + { + Endpoint = endpoint; + Keys = keys; + } + + public NotificationWebPushTokenSub() + { + } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Server/NotificationApiServer.cs b/src/StoneRed.NetificationApi/Server/NotificationApiServer.cs new file mode 100644 index 0000000..954f04a --- /dev/null +++ b/src/StoneRed.NetificationApi/Server/NotificationApiServer.cs @@ -0,0 +1,82 @@ +using StoneRed.NetificationApi.Server.IdentifyUser; +using StoneRed.NetificationApi.Server.Retract; +using StoneRed.NetificationApi.Server.Send; +using StoneRed.NetificationApi.Server.SetUserPreferences; +using StoneRed.NetificationApi.Utilities; + +using System.Net.Http.Json; +using System.Text; + +namespace StoneRed.NetificationApi.Server; + +public class NotificationApiServer +{ + private readonly string clientId; + private readonly string clientSecret; + private readonly bool secureMode; + private readonly HttpClient httpClient; + + public NotificationApiServer(string clientId, string clientSecret, bool secureMode, string baseAddress = "https://api.notificationapi.com") : this(new HttpClient(), clientId, clientSecret, secureMode, baseAddress) + { + this.clientId = clientId; + this.clientSecret = clientSecret; + } + + public NotificationApiServer(HttpClient httpClient, string clientId, string clientSecret, bool secureMode, string baseAddress = "https://api.notificationapi.com") + { + string authToken = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{clientId}:{clientSecret}")); + + httpClient.BaseAddress = new Uri(new Uri(baseAddress), $"{clientId}/"); + httpClient.DefaultRequestHeaders.Add("Authorization", $"Basic {authToken}"); + + this.clientId = clientId; + this.clientSecret = clientSecret; + this.secureMode = secureMode; + this.httpClient = httpClient; + } + + public async Task Send(SendNotificationData sendNotificationData) + { + return await httpClient.PostAsJsonAsync("sender", sendNotificationData, Configuration.JsonSerializerOptions); + } + + public async Task Retract(RetractNotificationData retractNotificationData) + { + return await httpClient.PostAsJsonAsync("sender/retract", retractNotificationData, Configuration.JsonSerializerOptions); + } + + public async Task Identify(IdentifyUserData identifyUserData) + { + string authToken; + + if (secureMode) + { + string hashedUserId = UserIdHasher.Hash(identifyUserData.UserId, clientSecret); + authToken = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{clientId}:{identifyUserData.UserId}:{hashedUserId}")); + } + else + { + authToken = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{clientId}:{identifyUserData.UserId}")); + } + + var requestData = new + { + email = identifyUserData.Email, + number = identifyUserData.TelephoneNumber, + }; + + HttpRequestMessage request = new(HttpMethod.Post, $"users/{identifyUserData.UserId}") + { + Content = JsonContent.Create(requestData, options: Configuration.JsonSerializerOptions), + }; + + request.Headers.Add("Authorization", $"Basic {authToken}"); + + return await httpClient.SendAsync(request); + } + + public async Task SetUserPreferences(SetUserPreferencesData setUserPreferencesData) + { + return await httpClient.PostAsJsonAsync($"user_preferences/{setUserPreferencesData.UserId}", setUserPreferencesData, Configuration.JsonSerializerOptions); + } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Server/Retract/RetractNotificationData.cs b/src/StoneRed.NetificationApi/Server/Retract/RetractNotificationData.cs new file mode 100644 index 0000000..55985d8 --- /dev/null +++ b/src/StoneRed.NetificationApi/Server/Retract/RetractNotificationData.cs @@ -0,0 +1,23 @@ +using System.Diagnostics.CodeAnalysis; + +namespace StoneRed.NetificationApi.Server.Retract; + +public class RetractNotificationData +{ + public required string UserId { get; set; } + + public required string NotificationId { get; set; } + + public string? SecondaryId { get; set; } + + [SetsRequiredMembers] + public RetractNotificationData(string userId, string notificationId) + { + UserId = userId; + NotificationId = notificationId; + } + + public RetractNotificationData() + { + } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Server/Send/NotificationApnOptions.cs b/src/StoneRed.NetificationApi/Server/Send/NotificationApnOptions.cs new file mode 100644 index 0000000..f4df57a --- /dev/null +++ b/src/StoneRed.NetificationApi/Server/Send/NotificationApnOptions.cs @@ -0,0 +1,18 @@ +namespace StoneRed.NetificationApi.Server.Send; + +public class NotificationApnOptions +{ + public int? Expiry { get; set; } + + public int? Priority { get; set; } + + public string? CollapseId { get; set; } + + public string? ThreadId { get; set; } + + public int? Badge { get; set; } + + public string? Sound { get; set; } + + public bool? ContentAvailable { get; set; } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Server/Send/NotificationEmailAttachments.cs b/src/StoneRed.NetificationApi/Server/Send/NotificationEmailAttachments.cs new file mode 100644 index 0000000..acab24a --- /dev/null +++ b/src/StoneRed.NetificationApi/Server/Send/NotificationEmailAttachments.cs @@ -0,0 +1,21 @@ +using System.Diagnostics.CodeAnalysis; + +namespace StoneRed.NetificationApi.Server.Send; + +internal class NotificationEmailAttachments +{ + public required string FileName { get; set; } + + public required string Url { get; set; } + + [SetsRequiredMembers] + public NotificationEmailAttachments(string fileName, string url) + { + FileName = fileName; + Url = url; + } + + public NotificationEmailAttachments() + { + } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Server/Send/NotificationEmailOptions.cs b/src/StoneRed.NetificationApi/Server/Send/NotificationEmailOptions.cs new file mode 100644 index 0000000..9136bc6 --- /dev/null +++ b/src/StoneRed.NetificationApi/Server/Send/NotificationEmailOptions.cs @@ -0,0 +1,12 @@ +namespace StoneRed.NetificationApi.Server.Send; + +public class NotificationEmailOptions +{ + public string[]? ReplyToAddresses { get; set; } + + public string[]? CcAddresses { get; set; } + + public string[]? BccAddresses { get; set; } + + public string[]? Attachments { get; set; } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Server/Send/NotificationFcmAndroidOptions.cs b/src/StoneRed.NetificationApi/Server/Send/NotificationFcmAndroidOptions.cs new file mode 100644 index 0000000..4ad5dc6 --- /dev/null +++ b/src/StoneRed.NetificationApi/Server/Send/NotificationFcmAndroidOptions.cs @@ -0,0 +1,10 @@ +namespace StoneRed.NetificationApi.Server.Send; + +internal class NotificationFcmAndroidOptions +{ + public string? CollapseKey { get; set; } + + public string? Priority { get; set; } + + public string? Ttl { get; set; } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Server/Send/NotificationFcmOptions.cs b/src/StoneRed.NetificationApi/Server/Send/NotificationFcmOptions.cs new file mode 100644 index 0000000..8c7c44e --- /dev/null +++ b/src/StoneRed.NetificationApi/Server/Send/NotificationFcmOptions.cs @@ -0,0 +1,6 @@ +namespace StoneRed.NetificationApi.Server.Send; + +internal class NotificationFcmOptions +{ + public NotificationFcmAndroidOptions? Android { get; set; } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Server/Send/NotificationOptions.cs b/src/StoneRed.NetificationApi/Server/Send/NotificationOptions.cs new file mode 100644 index 0000000..efe1fcb --- /dev/null +++ b/src/StoneRed.NetificationApi/Server/Send/NotificationOptions.cs @@ -0,0 +1,8 @@ +namespace StoneRed.NetificationApi.Server.Send; + +public class NotificationOptions +{ + public NotificationEmailOptions? Email { get; set; } + + public NotificationApnOptions? Apn { get; set; } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Server/Send/NotificationUser.cs b/src/StoneRed.NetificationApi/Server/Send/NotificationUser.cs new file mode 100644 index 0000000..bc75217 --- /dev/null +++ b/src/StoneRed.NetificationApi/Server/Send/NotificationUser.cs @@ -0,0 +1,24 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace StoneRed.NetificationApi.Server.Send; + +public class NotificationUser +{ + public required string Id { get; set; } + + public string? Email { get; set; } + + [JsonPropertyName("number")] + public string? TelephoneNumber { get; set; } + + public NotificationUser() + { + } + + [SetsRequiredMembers] + public NotificationUser(string id) + { + Id = id; + } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Server/Send/SendNotificationData.cs b/src/StoneRed.NetificationApi/Server/Send/SendNotificationData.cs new file mode 100644 index 0000000..56b8adc --- /dev/null +++ b/src/StoneRed.NetificationApi/Server/Send/SendNotificationData.cs @@ -0,0 +1,30 @@ +using System.Diagnostics.CodeAnalysis; + +namespace StoneRed.NetificationApi.Server.Send; + +public class SendNotificationData +{ + public required string NotificationId { get; set; } + + public string? SubNotificationId { get; set; } + + public string? TemplateId { get; set; } + + public required NotificationUser User { get; set; } + + public Dictionary? MergeTags { get; set; } + public Dictionary? Replace { get; set; } + + public NotificationOptions? Options { get; set; } + + [SetsRequiredMembers] + public SendNotificationData(string notificationId, NotificationUser user) + { + NotificationId = notificationId; + User = user; + } + + public SendNotificationData() + { + } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Server/SetUserPreferences/NotificationPreference.cs b/src/StoneRed.NetificationApi/Server/SetUserPreferences/NotificationPreference.cs new file mode 100644 index 0000000..2502d54 --- /dev/null +++ b/src/StoneRed.NetificationApi/Server/SetUserPreferences/NotificationPreference.cs @@ -0,0 +1,26 @@ +using StoneRed.NetificationApi.Shared; + +using System.Diagnostics.CodeAnalysis; + +namespace StoneRed.NetificationApi.Server.SetUserPreferences; + +public class NotificationPreference +{ + public required string NotificationId { get; set; } + + public required NotificationChannel Channel { get; set; } + + public required bool State { get; set; } + + [SetsRequiredMembers] + public NotificationPreference(string notificationId, NotificationChannel channel, bool state) + { + NotificationId = notificationId; + Channel = channel; + State = state; + } + + public NotificationPreference() + { + } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Server/SetUserPreferences/SetUserPreferencesData.cs b/src/StoneRed.NetificationApi/Server/SetUserPreferences/SetUserPreferencesData.cs new file mode 100644 index 0000000..951a02d --- /dev/null +++ b/src/StoneRed.NetificationApi/Server/SetUserPreferences/SetUserPreferencesData.cs @@ -0,0 +1,23 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace StoneRed.NetificationApi.Server.SetUserPreferences; + +public class SetUserPreferencesData +{ + [JsonIgnore] + public required string UserId { get; set; } + + public required List Preferences { get; set; } + + [SetsRequiredMembers] + public SetUserPreferencesData(string userId, List preferences) + { + UserId = userId; + Preferences = preferences; + } + + public SetUserPreferencesData() + { + } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Shared/NotificationChannels.cs b/src/StoneRed.NetificationApi/Shared/NotificationChannels.cs new file mode 100644 index 0000000..0a067c4 --- /dev/null +++ b/src/StoneRed.NetificationApi/Shared/NotificationChannels.cs @@ -0,0 +1,11 @@ +namespace StoneRed.NetificationApi.Shared; + +public enum NotificationChannel +{ + EMAIL, + INAPP_WEB, + WEB_PUSH, + SMS, + PUSH, + CALL +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/StoneRed.NetificationApi.csproj b/src/StoneRed.NetificationApi/StoneRed.NetificationApi.csproj new file mode 100644 index 0000000..114f131 --- /dev/null +++ b/src/StoneRed.NetificationApi/StoneRed.NetificationApi.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + enable + enable + + + + + + + diff --git a/src/StoneRed.NetificationApi/Utilities/Configuration.cs b/src/StoneRed.NetificationApi/Utilities/Configuration.cs new file mode 100644 index 0000000..d09e91c --- /dev/null +++ b/src/StoneRed.NetificationApi/Utilities/Configuration.cs @@ -0,0 +1,18 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace StoneRed.NetificationApi.Utilities; + +internal static class Configuration +{ + public static JsonSerializerOptions JsonSerializerOptions { get; } = new JsonSerializerOptions() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + Converters = + { + new JsonStringEnumConverter(), + new DateTimeConverter(), + } + }; +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Utilities/DateTimeConverter.cs b/src/StoneRed.NetificationApi/Utilities/DateTimeConverter.cs new file mode 100644 index 0000000..5a4e55a --- /dev/null +++ b/src/StoneRed.NetificationApi/Utilities/DateTimeConverter.cs @@ -0,0 +1,17 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace StoneRed.NetificationApi.Utilities; + +internal class DateTimeConverter : JsonConverter +{ + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetDateTime().ToUniversalTime(); + } + + public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) + { + writer.WriteStringValue(value.ToUniversalTime()); + } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Utilities/UserIdHasher.cs b/src/StoneRed.NetificationApi/Utilities/UserIdHasher.cs new file mode 100644 index 0000000..0318524 --- /dev/null +++ b/src/StoneRed.NetificationApi/Utilities/UserIdHasher.cs @@ -0,0 +1,13 @@ +using System.Security.Cryptography; +using System.Text; + +namespace StoneRed.NetificationApi.Utilities; + +internal static class UserIdHasher +{ + public static string Hash(string userId, string clientSecret) + { + using HMACSHA256 hmac = new HMACSHA256(Encoding.ASCII.GetBytes(clientSecret)); + return Convert.ToBase64String(hmac.ComputeHash(Encoding.ASCII.GetBytes(userId))); + } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Utilities/WebsocketMessageComparer.cs b/src/StoneRed.NetificationApi/Utilities/WebsocketMessageComparer.cs new file mode 100644 index 0000000..9d5cb16 --- /dev/null +++ b/src/StoneRed.NetificationApi/Utilities/WebsocketMessageComparer.cs @@ -0,0 +1,20 @@ +using StoneRed.NetificationApi.Client; + +using System.Text.Json; + +namespace StoneRed.NetificationApi.Utilities; + +internal static class WebsocketMessageComparer +{ + public static bool Compare(string? message, string route) + { + if (message is null) + { + return false; + } + + WebsocketMessage? websocketMessage = JsonSerializer.Deserialize(message, Configuration.JsonSerializerOptions); + + return websocketMessage?.Route == route; + } +} \ No newline at end of file diff --git a/src/StoneRed.NetificationApi/Utilities/WebsocketMessageConverter.cs b/src/StoneRed.NetificationApi/Utilities/WebsocketMessageConverter.cs new file mode 100644 index 0000000..09b6629 --- /dev/null +++ b/src/StoneRed.NetificationApi/Utilities/WebsocketMessageConverter.cs @@ -0,0 +1,13 @@ +using StoneRed.NetificationApi.Client; + +using System.Text.Json; + +namespace StoneRed.NetificationApi.Utilities; + +internal static class WebsocketMessageConverter +{ + public static WebsocketMessage ConvertWebsocketMessage(string message) + { + return JsonSerializer.Deserialize>(message, Configuration.JsonSerializerOptions) ?? throw new InvalidOperationException("Failed to deserialize websocket message."); + } +} \ No newline at end of file