├── .gitignore ├── ANSApplePusher ├── ANSApplePusher.csproj ├── AdamantApnsNotification.cs ├── ApplePusher.cs ├── Payload.cs └── PayloadContent.cs ├── ANSApplePusher_PushSharp ├── ANSApplePusher_PushSharp.csproj ├── Payload.cs ├── PayloadContent.cs └── Pusher.cs ├── ANSCore ├── ANSCore.csproj ├── IPusher.cs └── Models │ ├── Device.cs │ ├── ServiceState.cs │ └── StartupMode.cs ├── ANSDataContext ├── ANSContext.cs ├── ANSDataContext.csproj ├── Migrations │ ├── 20180511150347_InitialCreate.Designer.cs │ ├── 20180511150347_InitialCreate.cs │ ├── 20180611083124_Provider.Designer.cs │ ├── 20180611083124_Provider.cs │ ├── 20180626144847_ServiceState.Designer.cs │ ├── 20180626144847_ServiceState.cs │ ├── 20180626152910_DeviceTransactionDate.Designer.cs │ ├── 20180626152910_DeviceTransactionDate.cs │ └── DevicesContextModelSnapshot.cs └── Program.cs ├── ANSPollingWorker ├── ANSPollingWorker.csproj ├── ChatPollingWorker.cs ├── Program.cs ├── TransactionsPollingWorkerBase.cs └── TransferPollingWorker.cs ├── ANSShared ├── ANSShared.csproj └── PollingWorkerBase.cs ├── ANSSignalsRegistration ├── ANSSignalsRegistration.csproj ├── DeviceInfo.cs ├── Program.cs ├── SignalAction.cs └── SignalsPoller.cs ├── AdamantApi ├── AdamantApi.cs ├── AdamantApi.csproj ├── Responses │ └── TransactionsResponse.cs └── ServerDescription.cs ├── AdamantCore.Tests ├── AdamantCore.Tests.csproj └── UtilitiesTests.cs ├── AdamantCore ├── AdamantCore.csproj ├── Models │ ├── ChatAsset.cs │ ├── ChatType.cs │ ├── Transaction.cs │ ├── TransactionAsset.cs │ └── TransactionType.cs └── Utilities.cs ├── AdamantEncryption.Tests ├── AdamantEncryption.Tests.csproj └── EncryptionTests.cs ├── AdamantEncryption ├── AdamantEncryption.csproj └── Encryption.cs ├── AdamantUtilities ├── AdamantUtilities.csproj └── ConfigurationLoader.cs ├── LICENSE ├── README.md ├── SharpPusher ├── ApnsEnvironment.cs ├── ApnsNotification.cs ├── ApnsPusher.cs ├── ApnsResponse.cs ├── ApnsResult.cs ├── IPusher.cs └── SharpPusher.csproj ├── SharpPusherSample ├── NLog.config ├── Program.cs └── SharpPusherSample.csproj ├── SharpPusherTests ├── ApnsTests.cs └── SharpPusherTests.csproj ├── adamant-notificationService.sln ├── adamant-notificationService.sublime-project ├── config.json ├── global.json └── nlog.config /.gitignore: -------------------------------------------------------------------------------- 1 | ### Custom 2 | # Folder with development resources, like certificates, configs, anime porn, quake3 3 | dev/ 4 | 5 | 6 | # Created by https://www.gitignore.io/api/aspnetcore,sublimetext,visualstudio 7 | 8 | ### ASPNETCore ### 9 | ## Ignore Visual Studio temporary files, build results, and 10 | ## files generated by popular Visual Studio add-ons. 11 | 12 | # User-specific files 13 | *.suo 14 | *.user 15 | *.userosscache 16 | *.sln.docstates 17 | 18 | # User-specific files (MonoDevelop/Xamarin Studio) 19 | *.userprefs 20 | 21 | # Build results 22 | [Dd]ebug/ 23 | [Dd]ebugPublic/ 24 | [Rr]elease/ 25 | [Rr]eleases/ 26 | x64/ 27 | x86/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | 33 | # Visual Studio 2015 cache/options directory 34 | .vs/ 35 | # Uncomment if you have tasks that create the project's static files in wwwroot 36 | #wwwroot/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # DNX 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | 56 | *_i.c 57 | *_p.c 58 | *_i.h 59 | *.ilk 60 | *.meta 61 | *.obj 62 | *.pch 63 | *.pdb 64 | *.pgc 65 | *.pgd 66 | *.rsp 67 | *.sbr 68 | *.tlb 69 | *.tli 70 | *.tlh 71 | *.tmp 72 | *.tmp_proj 73 | *.log 74 | *.vspscc 75 | *.vssscc 76 | .builds 77 | *.pidb 78 | *.svclog 79 | *.scc 80 | 81 | # Chutzpah Test files 82 | _Chutzpah* 83 | 84 | # Visual C++ cache files 85 | ipch/ 86 | *.aps 87 | *.ncb 88 | *.opendb 89 | *.opensdf 90 | *.sdf 91 | *.cachefile 92 | *.VC.db 93 | *.VC.VC.opendb 94 | 95 | # Visual Studio profiler 96 | *.psess 97 | *.vsp 98 | *.vspx 99 | *.sap 100 | 101 | # TFS 2012 Local Workspace 102 | $tf/ 103 | 104 | # Guidance Automation Toolkit 105 | *.gpState 106 | 107 | # ReSharper is a .NET coding add-in 108 | _ReSharper*/ 109 | *.[Rr]e[Ss]harper 110 | *.DotSettings.user 111 | 112 | # JustCode is a .NET coding add-in 113 | .JustCode 114 | 115 | # TeamCity is a build add-in 116 | _TeamCity* 117 | 118 | # DotCover is a Code Coverage Tool 119 | *.dotCover 120 | 121 | # Visual Studio code coverage results 122 | *.coverage 123 | *.coveragexml 124 | 125 | # NCrunch 126 | _NCrunch_* 127 | .*crunch*.local.xml 128 | nCrunchTemp_* 129 | 130 | # MightyMoose 131 | *.mm.* 132 | AutoTest.Net/ 133 | 134 | # Web workbench (sass) 135 | .sass-cache/ 136 | 137 | # Installshield output folder 138 | [Ee]xpress/ 139 | 140 | # DocProject is a documentation generator add-in 141 | DocProject/buildhelp/ 142 | DocProject/Help/*.HxT 143 | DocProject/Help/*.HxC 144 | DocProject/Help/*.hhc 145 | DocProject/Help/*.hhk 146 | DocProject/Help/*.hhp 147 | DocProject/Help/Html2 148 | DocProject/Help/html 149 | 150 | # Click-Once directory 151 | publish/ 152 | 153 | # Publish Web Output 154 | *.[Pp]ublish.xml 155 | *.azurePubxml 156 | # TODO: Comment the next line if you want to checkin your web deploy settings 157 | # but database connection strings (with potential passwords) will be unencrypted 158 | *.pubxml 159 | *.publishproj 160 | 161 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 162 | # checkin your Azure Web App publish settings, but sensitive information contained 163 | # in these scripts will be unencrypted 164 | PublishScripts/ 165 | 166 | # NuGet Packages 167 | *.nupkg 168 | # The packages folder can be ignored because of Package Restore 169 | **/packages/* 170 | # except build/, which is used as an MSBuild target. 171 | !**/packages/build/ 172 | # Uncomment if necessary however generally it will be regenerated when needed 173 | #!**/packages/repositories.config 174 | # NuGet v3's project.json files produces more ignoreable files 175 | *.nuget.props 176 | *.nuget.targets 177 | 178 | # Microsoft Azure Build Output 179 | csx/ 180 | *.build.csdef 181 | 182 | # Microsoft Azure Emulator 183 | ecf/ 184 | rcf/ 185 | 186 | # Windows Store app package directories and files 187 | AppPackages/ 188 | BundleArtifacts/ 189 | Package.StoreAssociation.xml 190 | _pkginfo.txt 191 | 192 | # Visual Studio cache files 193 | # files ending in .cache can be ignored 194 | *.[Cc]ache 195 | # but keep track of directories ending in .cache 196 | !*.[Cc]ache/ 197 | 198 | # Others 199 | ClientBin/ 200 | ~$* 201 | *~ 202 | *.dbmdl 203 | *.dbproj.schemaview 204 | *.jfm 205 | *.pfx 206 | *.publishsettings 207 | node_modules/ 208 | orleans.codegen.cs 209 | 210 | # Since there are multiple workflows, uncomment next line to ignore bower_components 211 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 212 | #bower_components/ 213 | 214 | # RIA/Silverlight projects 215 | Generated_Code/ 216 | 217 | # Backup & report files from converting an old project file 218 | # to a newer Visual Studio version. Backup files are not needed, 219 | # because we have git ;-) 220 | _UpgradeReport_Files/ 221 | Backup*/ 222 | UpgradeLog*.XML 223 | UpgradeLog*.htm 224 | 225 | # SQL Server files 226 | *.mdf 227 | *.ldf 228 | 229 | # Business Intelligence projects 230 | *.rdl.data 231 | *.bim.layout 232 | *.bim_*.settings 233 | 234 | # Microsoft Fakes 235 | FakesAssemblies/ 236 | 237 | # GhostDoc plugin setting file 238 | *.GhostDoc.xml 239 | 240 | # Node.js Tools for Visual Studio 241 | .ntvs_analysis.dat 242 | 243 | # Visual Studio 6 build log 244 | *.plg 245 | 246 | # Visual Studio 6 workspace options file 247 | *.opt 248 | 249 | # Visual Studio LightSwitch build output 250 | **/*.HTMLClient/GeneratedArtifacts 251 | **/*.DesktopClient/GeneratedArtifacts 252 | **/*.DesktopClient/ModelManifest.xml 253 | **/*.Server/GeneratedArtifacts 254 | **/*.Server/ModelManifest.xml 255 | _Pvt_Extensions 256 | 257 | # Paket dependency manager 258 | .paket/paket.exe 259 | paket-files/ 260 | 261 | # FAKE - F# Make 262 | .fake/ 263 | 264 | # JetBrains Rider 265 | .idea/ 266 | *.sln.iml 267 | 268 | # CodeRush 269 | .cr/ 270 | 271 | # Python Tools for Visual Studio (PTVS) 272 | __pycache__/ 273 | *.pyc 274 | 275 | # Cake - Uncomment if you are using it 276 | # tools/ 277 | 278 | ### SublimeText ### 279 | # cache files for sublime text 280 | *.tmlanguage.cache 281 | *.tmPreferences.cache 282 | *.stTheme.cache 283 | 284 | # workspace files are user-specific 285 | *.sublime-workspace 286 | 287 | # project files should be checked into the repository, unless a significant 288 | # proportion of contributors will probably not be using SublimeText 289 | # *.sublime-project 290 | 291 | # sftp configuration file 292 | sftp-config.json 293 | 294 | # Package control specific files 295 | Package Control.last-run 296 | Package Control.ca-list 297 | Package Control.ca-bundle 298 | Package Control.system-ca-bundle 299 | Package Control.cache/ 300 | Package Control.ca-certs/ 301 | Package Control.merged-ca-bundle 302 | Package Control.user-ca-bundle 303 | oscrypto-ca-bundle.crt 304 | bh_unicode_properties.cache 305 | 306 | # Sublime-github package stores a github token in this file 307 | # https://packagecontrol.io/packages/sublime-github 308 | GitHub.sublime-settings 309 | 310 | ### VisualStudio ### 311 | ## Ignore Visual Studio temporary files, build results, and 312 | ## files generated by popular Visual Studio add-ons. 313 | ## 314 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 315 | 316 | # User-specific files 317 | 318 | # User-specific files (MonoDevelop/Xamarin Studio) 319 | 320 | # Build results 321 | 322 | # Visual Studio 2015 cache/options directory 323 | # Uncomment if you have tasks that create the project's static files in wwwroot 324 | #wwwroot/ 325 | 326 | # MSTest test Results 327 | 328 | # NUNIT 329 | 330 | # Build Results of an ATL Project 331 | 332 | # .NET Core 333 | **/Properties/launchSettings.json 334 | 335 | 336 | # Chutzpah Test files 337 | 338 | # Visual C++ cache files 339 | 340 | # Visual Studio profiler 341 | 342 | # TFS 2012 Local Workspace 343 | 344 | # Guidance Automation Toolkit 345 | 346 | # ReSharper is a .NET coding add-in 347 | 348 | # JustCode is a .NET coding add-in 349 | 350 | # TeamCity is a build add-in 351 | 352 | # DotCover is a Code Coverage Tool 353 | 354 | # Visual Studio code coverage results 355 | 356 | # NCrunch 357 | 358 | # MightyMoose 359 | 360 | # Web workbench (sass) 361 | 362 | # Installshield output folder 363 | 364 | # DocProject is a documentation generator add-in 365 | 366 | # Click-Once directory 367 | 368 | # Publish Web Output 369 | # TODO: Uncomment the next line to ignore your web deploy settings. 370 | # By default, sensitive information, such as encrypted password 371 | # should be stored in the .pubxml.user file. 372 | #*.pubxml 373 | *.pubxml.user 374 | 375 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 376 | # checkin your Azure Web App publish settings, but sensitive information contained 377 | # in these scripts will be unencrypted 378 | 379 | # NuGet Packages 380 | # The packages folder can be ignored because of Package Restore 381 | # except build/, which is used as an MSBuild target. 382 | # Uncomment if necessary however generally it will be regenerated when needed 383 | #!**/packages/repositories.config 384 | # NuGet v3's project.json files produces more ignorable files 385 | 386 | # Microsoft Azure Build Output 387 | 388 | # Microsoft Azure Emulator 389 | 390 | # Windows Store app package directories and files 391 | 392 | # Visual Studio cache files 393 | # files ending in .cache can be ignored 394 | # but keep track of directories ending in .cache 395 | 396 | # Others 397 | 398 | # Since there are multiple workflows, uncomment next line to ignore bower_components 399 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 400 | #bower_components/ 401 | 402 | # RIA/Silverlight projects 403 | 404 | # Backup & report files from converting an old project file 405 | # to a newer Visual Studio version. Backup files are not needed, 406 | # because we have git ;-) 407 | 408 | # SQL Server files 409 | *.ndf 410 | 411 | # Business Intelligence projects 412 | 413 | # Microsoft Fakes 414 | 415 | # GhostDoc plugin setting file 416 | 417 | # Node.js Tools for Visual Studio 418 | 419 | # Typescript v1 declaration files 420 | typings/ 421 | 422 | # Visual Studio 6 build log 423 | 424 | # Visual Studio 6 workspace options file 425 | 426 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 427 | *.vbw 428 | 429 | # Visual Studio LightSwitch build output 430 | 431 | # Paket dependency manager 432 | 433 | # FAKE - F# Make 434 | 435 | # JetBrains Rider 436 | 437 | # CodeRush 438 | 439 | # Python Tools for Visual Studio (PTVS) 440 | 441 | # Cake - Uncomment if you are using it 442 | # tools/** 443 | # !tools/packages.config 444 | 445 | # Telerik's JustMock configuration file 446 | *.jmconfig 447 | 448 | # BizTalk build output 449 | *.btp.cs 450 | *.btm.cs 451 | *.odx.cs 452 | *.xsd.cs 453 | 454 | ### VisualStudio Patch ### 455 | # By default, sensitive information, such as encrypted password 456 | # should be stored in the .pubxml.user file. 457 | 458 | 459 | # End of https://www.gitignore.io/api/aspnetcore,sublimetext,visualstudio -------------------------------------------------------------------------------- /ANSApplePusher/ANSApplePusher.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.0 5 | 0.4.1 6 | Adamant.NotificationService.ApplePusher 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /ANSApplePusher/AdamantApnsNotification.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using SharpPusher; 3 | 4 | namespace Adamant.NotificationService.ApplePusher 5 | { 6 | internal class AdamantApnsNotification: ApnsNotification 7 | { 8 | [JsonProperty("push-recipient")] 9 | public string PushRecipient { get; set; } 10 | 11 | [JsonProperty("txn-id")] 12 | public string TxnId { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /ANSApplePusher/ApplePusher.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Adamant.Models; 4 | using Adamant.NotificationService.Models; 5 | using SharpPusher; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.Logging; 8 | using System.Linq; 9 | 10 | namespace Adamant.NotificationService.ApplePusher 11 | { 12 | public class ApplePusher: IPusher 13 | { 14 | #region Properties 15 | 16 | private readonly ILogger _logger; 17 | private readonly IConfiguration _configuration; 18 | 19 | private ApnsPusher pusher; 20 | private Dictionary _contents; 21 | 22 | public event InvalidTokenHandler OnInvalidToken; 23 | 24 | #endregion 25 | 26 | 27 | #region Ctor 28 | 29 | public ApplePusher(ILogger logger, ILogger internalLogger, IConfiguration configuration) 30 | { 31 | _logger = logger; 32 | _configuration = configuration; 33 | 34 | Func getRequiredParam = (key, config) => 35 | { 36 | var value = config[key]; 37 | if (value == null) 38 | throw new ArgumentException($"Can't get {key}"); 39 | 40 | return value; 41 | }; 42 | 43 | _contents = LoadPayloadContent(_configuration); 44 | 45 | var keyId = getRequiredParam("ApplePusher:Keys:keyId", configuration); 46 | var teamId = getRequiredParam("ApplePusher:Keys:teamId", configuration); 47 | var bundleAppId = getRequiredParam("ApplePusher:Keys:bundleAppId", configuration); 48 | var pfxPath = Utilities.HandleUnixHomeDirectory(getRequiredParam("ApplePusher:Keys:pfxPath", configuration)); 49 | var pfxPassword = getRequiredParam("ApplePusher:Keys:pfxPassword", configuration); 50 | 51 | 52 | pusher = new ApnsPusher(internalLogger, keyId, teamId, bundleAppId, pfxPath, pfxPassword, ApnsEnvironment.Production); 53 | pusher.OnNotificationSuccess += Pusher_OnNotificationSuccess; 54 | pusher.OnNotificationFailed += Pusher_OnNotificationFailed; 55 | } 56 | 57 | #endregion 58 | 59 | 60 | public void Start() 61 | { 62 | } 63 | 64 | public void Stop() 65 | { 66 | } 67 | 68 | public void NotifyDevice(Device device, IEnumerable transactions) 69 | { 70 | if (device == null) 71 | throw new NullReferenceException("device"); 72 | 73 | if (string.IsNullOrEmpty(device.Token)) 74 | throw new ArgumentException("device.token"); 75 | 76 | if (transactions == null || !transactions.Any()) 77 | return; 78 | 79 | var notifications = new List<(ApnsNotification notification, string token)>(); 80 | 81 | // Get transaction type, check if we have payload content for this type 82 | 83 | foreach (var trs in transactions) 84 | { 85 | if (!_contents.ContainsKey(trs.Type)) 86 | continue; 87 | 88 | var content = _contents[trs.Type]; 89 | 90 | // Make payload 91 | var notification = new AdamantApnsNotification 92 | { 93 | Payload = new ApnsPayload 94 | { 95 | Alert = new ApnsNotificationAlert(), 96 | Badge = 1, 97 | MutableContent = 1 98 | }, 99 | PushRecipient = device.Address, 100 | TxnId = trs.Id 101 | }; 102 | 103 | if (!string.IsNullOrEmpty(content.Sound)) 104 | notification.Payload.Sound = content.Sound; 105 | 106 | if (!string.IsNullOrEmpty(content.Body)) 107 | notification.Payload.Alert.BodyLocalizationKey = content.Body; 108 | 109 | if (!string.IsNullOrEmpty(content.Title)) 110 | notification.Payload.Alert.TitleLocalizationKey = content.Title; 111 | 112 | notifications.Add((notification, device.Token)); 113 | } 114 | 115 | pusher.SendNotificationsAsync(notifications); 116 | } 117 | 118 | 119 | #region Events 120 | 121 | void Pusher_OnNotificationSuccess(object sender, NotificationSuccessEventArgs args) 122 | { 123 | _logger.LogDebug("Notification success, token: {0}", args.Token); 124 | } 125 | 126 | void Pusher_OnNotificationFailed(object sender, NotificationFailedEventArgs args) 127 | { 128 | _logger.LogError(args.Exception, "Notification failed. Code: {0}, reason: {1}", args.ResultCode, args.Reason); 129 | 130 | switch (args.ResultCode) 131 | { 132 | case ApnsResult.BadRequest: 133 | if (args.Reason.Equals("BadDeviceToken")) 134 | OnInvalidToken?.Invoke(this, new InvalidTokenEventArgs(args.Token)); 135 | 136 | break; 137 | 138 | case ApnsResult.TokenExpired: 139 | OnInvalidToken?.Invoke(this, new InvalidTokenEventArgs(args.Token)); 140 | break; 141 | } 142 | } 143 | 144 | 145 | #endregion 146 | 147 | 148 | #region Tools 149 | 150 | private static Dictionary LoadPayloadContent(IConfiguration configuration) 151 | { 152 | var contents = new Dictionary(); 153 | 154 | foreach (var content in configuration.GetSection("ApplePusher").GetSection("Payload").GetChildren()) 155 | { 156 | var typeRaw = content["transactionType"]; 157 | 158 | TransactionType type; 159 | 160 | if (!Enum.TryParse(typeRaw, out type)) 161 | continue; 162 | 163 | var title = content["title"]; 164 | var body = content["body"]; 165 | var sound = content["sound"]; 166 | 167 | contents.Add(type, new PayloadContent(title, body, sound)); 168 | } 169 | 170 | return contents; 171 | } 172 | 173 | #endregion 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /ANSApplePusher/Payload.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Newtonsoft.Json.Linq; 4 | 5 | namespace Adamant.NotificationService.ApplePusher 6 | { 7 | internal class Payload 8 | { 9 | #region Properties 10 | 11 | /// 12 | /// Body localisation key. Required. 13 | /// 14 | public string Body { get; set; } 15 | 16 | /// 17 | /// Notification title localisation key. Optional. 18 | /// 19 | public string Title { get; set; } 20 | 21 | /// 22 | /// Badge number. Optional. '0' removes badge from app icon. 23 | /// 24 | public int? Badge { get; set; } 25 | 26 | /// 27 | /// Notification sound filename on device. Optional, if not specified - plays default iOS sound. 28 | /// 29 | public string Sound { get; set; } 30 | 31 | #endregion 32 | 33 | #region ctor 34 | 35 | public Payload() {} 36 | 37 | public Payload(string title, string body, int? badge = null, string sound = null) 38 | { 39 | Title = title; 40 | Body = body; 41 | Badge = badge; 42 | Sound = sound; 43 | } 44 | 45 | #endregion 46 | 47 | #region Utilities 48 | 49 | public JObject ToJObject() 50 | { 51 | var root = new Dictionary(); 52 | var aps = new Dictionary(); 53 | var alert = new Dictionary(); 54 | 55 | root.Add("aps", aps); 56 | aps.Add("alert", alert); 57 | 58 | alert["loc-key"] = Body; 59 | 60 | if (!string.IsNullOrEmpty(Title)) 61 | alert["title-loc-key"] = Title; 62 | 63 | if (Badge.HasValue) 64 | aps["badge"] = Badge.Value; 65 | 66 | if (!string.IsNullOrEmpty(Sound)) 67 | aps["sound"] = Sound; 68 | 69 | return JObject.FromObject(root); 70 | } 71 | 72 | #endregion 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /ANSApplePusher/PayloadContent.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Adamant.NotificationService.ApplePusher 4 | { 5 | internal struct PayloadContent 6 | { 7 | public string Title { get; } 8 | public string Body { get; } 9 | public string Sound { get; } 10 | 11 | public PayloadContent(string title, string body, string sound) 12 | { 13 | Title = title; 14 | Body = body; 15 | Sound = sound; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /ANSApplePusher_PushSharp/ANSApplePusher_PushSharp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.0 5 | Adamant.NotificationService.ApplePusher 6 | 0.3 7 | 8 | 9 | 10 | Default 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /ANSApplePusher_PushSharp/Payload.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Newtonsoft.Json.Linq; 4 | 5 | namespace Adamant.NotificationService.ApplePusher 6 | { 7 | internal class Payload 8 | { 9 | #region Properties 10 | 11 | /// 12 | /// Body localisation key. Required. 13 | /// 14 | public string Body { get; set; } 15 | 16 | /// 17 | /// Notification title localisation key. Optional. 18 | /// 19 | public string Title { get; set; } 20 | 21 | /// 22 | /// Badge number. Optional. '0' removes badge from app icon. 23 | /// 24 | public int? Badge { get; set; } 25 | 26 | /// 27 | /// Notification sound filename on device. Optional, if not specified - plays default iOS sound. 28 | /// 29 | public string Sound { get; set; } 30 | 31 | #endregion 32 | 33 | #region ctor 34 | 35 | public Payload() {} 36 | 37 | public Payload(string title, string body, int? badge = null, string sound = null) 38 | { 39 | Title = title; 40 | Body = body; 41 | Badge = badge; 42 | Sound = sound; 43 | } 44 | 45 | #endregion 46 | 47 | #region Utilities 48 | 49 | public JObject ToJObject() 50 | { 51 | var root = new Dictionary(); 52 | var aps = new Dictionary(); 53 | var alert = new Dictionary(); 54 | 55 | root.Add("aps", aps); 56 | aps.Add("alert", alert); 57 | 58 | alert["loc-key"] = Body; 59 | 60 | if (!string.IsNullOrEmpty(Title)) 61 | alert["title-loc-key"] = Title; 62 | 63 | if (Badge.HasValue) 64 | aps["badge"] = Badge.Value; 65 | 66 | if (!string.IsNullOrEmpty(Sound)) 67 | aps["sound"] = Sound; 68 | 69 | return JObject.FromObject(root); 70 | } 71 | 72 | #endregion 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /ANSApplePusher_PushSharp/PayloadContent.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Adamant.NotificationService.ApplePusher 4 | { 5 | internal struct PayloadContent 6 | { 7 | public string Title { get; } 8 | public string Body { get; } 9 | public string Sound { get; } 10 | 11 | public PayloadContent(string title, string body, string sound) 12 | { 13 | Title = title; 14 | Body = body; 15 | Sound = sound; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /ANSApplePusher_PushSharp/Pusher.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Adamant.Models; 5 | using Adamant.NotificationService.Models; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.Logging; 8 | using PushSharp.Apple; 9 | 10 | namespace Adamant.NotificationService.ApplePusher 11 | { 12 | public class Pusher : IPusher 13 | { 14 | #region Properties 15 | 16 | private readonly ILogger _logger; 17 | private readonly IConfiguration _configuration; 18 | 19 | private ApnsServiceBroker _broker; 20 | private Dictionary _contents; 21 | 22 | public event InvalidTokenHandler OnInvalidToken; 23 | 24 | #endregion 25 | 26 | #region Ctor 27 | 28 | public Pusher(ILogger logger, IConfiguration configuration) 29 | { 30 | _logger = logger; 31 | _configuration = configuration; 32 | } 33 | 34 | #endregion 35 | 36 | #region IPusher 37 | 38 | public void Start() 39 | { 40 | _contents = LoadPayloadContent(_configuration); 41 | _broker = CreateBroker(_configuration); 42 | 43 | if (_broker == null) 44 | throw new Exception("Can't create APNs broker"); 45 | 46 | _broker.OnNotificationFailed += OnNotificationFailed; 47 | _broker.OnNotificationSucceeded += OnNotificationSucceeded; 48 | 49 | _broker.Start(); 50 | 51 | // TODO: Start feedback poller 52 | } 53 | 54 | public void Stop() 55 | { 56 | _broker.Stop(); 57 | 58 | _broker.OnNotificationFailed -= OnNotificationFailed; 59 | _broker.OnNotificationSucceeded -= OnNotificationSucceeded; 60 | _broker = null; 61 | _contents = null; 62 | } 63 | 64 | public void NotifyDevice(Device device, IEnumerable transactions) 65 | { 66 | if (device == null) 67 | throw new NullReferenceException("device"); 68 | 69 | if (string.IsNullOrEmpty(device.Token)) 70 | throw new ArgumentException("device.token"); 71 | 72 | if (transactions == null || !transactions.Any()) 73 | return; 74 | 75 | 76 | // Get transaction type, check if we have payload content for this type 77 | 78 | var type = transactions.First().Type; 79 | 80 | if (!_contents.ContainsKey(type)) 81 | return; 82 | 83 | var content = _contents[type]; 84 | 85 | 86 | // Make payload and notification 87 | 88 | var payload = new Payload 89 | { 90 | Sound = content.Sound, 91 | Badge = 1 92 | }; 93 | 94 | if (!string.IsNullOrEmpty(content.Body)) 95 | payload.Body = content.Body; 96 | 97 | if (!string.IsNullOrEmpty(content.Title)) 98 | payload.Title = content.Title; 99 | 100 | var notification = new ApnsNotification 101 | { 102 | DeviceToken = device.Token, 103 | Payload = payload.ToJObject() 104 | }; 105 | 106 | 107 | // Send it 108 | 109 | _broker.QueueNotification(notification); 110 | } 111 | 112 | #endregion 113 | 114 | #region Logging 115 | 116 | private void OnNotificationSucceeded(ApnsNotification notification) 117 | { 118 | _logger.LogDebug("Apple Notification Sent. Device: {0}. Payload: {1}", notification.DeviceToken, notification.Payload); 119 | } 120 | 121 | private void OnNotificationFailed(ApnsNotification notification, AggregateException aggregateEx) 122 | { 123 | aggregateEx.Handle(ex => 124 | { 125 | if (ex is ApnsNotificationException notificationException) 126 | { 127 | var apnsNotification = notificationException.Notification; 128 | var statusCode = notificationException.ErrorStatusCode; 129 | _logger.LogError(notificationException, "Apple Notification Failed: ID={0}, Code={1}, Token={2}, Payload={3}", apnsNotification.Identifier, statusCode, notification.DeviceToken, notification.Payload); 130 | 131 | switch (statusCode) 132 | { 133 | case ApnsNotificationErrorStatusCode.InvalidTokenSize: 134 | case ApnsNotificationErrorStatusCode.InvalidToken: 135 | OnInvalidToken(this, new InvalidTokenEventArgs(notification.DeviceToken)); 136 | break; 137 | } 138 | } 139 | else 140 | { 141 | _logger.LogError(ex.InnerException, "Apple Notification Failed for some unknown reason, Token={0}, Payload={1}", notification.DeviceToken, notification.Payload); 142 | } 143 | 144 | return true; 145 | }); 146 | } 147 | 148 | #endregion 149 | 150 | #region Tools 151 | 152 | private static ApnsServiceBroker CreateBroker(IConfiguration configuration) 153 | { 154 | if (configuration == null) 155 | throw new NullReferenceException("configuration"); 156 | 157 | var certName = Utilities.HandleUnixHomeDirectory(configuration["ApplePusher:Certificate:path"]); 158 | var certPass = configuration["ApplePusher:Certificate:pass"] ?? ""; 159 | 160 | if (string.IsNullOrEmpty(certName)) 161 | throw new Exception("Can't get certerficate filename from configuration"); 162 | 163 | var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, certName, certPass); 164 | 165 | return new ApnsServiceBroker(config); 166 | } 167 | 168 | private static Dictionary LoadPayloadContent(IConfiguration configuration) 169 | { 170 | var contents = new Dictionary(); 171 | 172 | foreach (var content in configuration.GetSection("ApplePusher").GetSection("Payload").GetChildren()) 173 | { 174 | var typeRaw = content["transactionType"]; 175 | 176 | TransactionType type; 177 | 178 | if (!Enum.TryParse(typeRaw, out type)) 179 | continue; 180 | 181 | var title = content["title"]; 182 | var body = content["body"]; 183 | var sound = content["sound"]; 184 | 185 | contents.Add(type, new PayloadContent(title, body, sound)); 186 | } 187 | 188 | return contents; 189 | } 190 | 191 | #endregion 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /ANSCore/ANSCore.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.0 5 | Adamant.NotificationService 6 | 0.4.1 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /ANSCore/IPusher.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Adamant.Models; 4 | using Adamant.NotificationService.Models; 5 | 6 | namespace Adamant.NotificationService 7 | { 8 | public interface IPusher 9 | { 10 | void NotifyDevice(Device device, IEnumerable transactions); 11 | 12 | void Start(); 13 | void Stop(); 14 | 15 | event InvalidTokenHandler OnInvalidToken; 16 | } 17 | 18 | public class InvalidTokenEventArgs: EventArgs 19 | { 20 | public string Token { get; } 21 | 22 | public InvalidTokenEventArgs(string token) 23 | { 24 | Token = token; 25 | } 26 | } 27 | 28 | public delegate void InvalidTokenHandler(IPusher sender, InvalidTokenEventArgs eventArgs); 29 | } 30 | -------------------------------------------------------------------------------- /ANSCore/Models/Device.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Adamant.NotificationService.Models 4 | { 5 | public class Device 6 | { 7 | public int ID { get; set; } 8 | public string Address { get; set; } 9 | public string Token { get; set; } 10 | public string Provider { get; set; } 11 | public DateTime TransactionDate { get; set; } 12 | public DateTime RegistrationDate { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /ANSCore/Models/ServiceState.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace Adamant.NotificationService.Models 3 | { 4 | public class ServiceState 5 | { 6 | public int ID { get; set; } 7 | public string Service { get; set; } 8 | public int LastHeight { get; set; } 9 | public DateTime Date { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /ANSCore/Models/StartupMode.cs: -------------------------------------------------------------------------------- 1 | namespace Adamant.NotificationService.Models 2 | { 3 | /// 4 | /// Startup mode 5 | /// 6 | public enum StartupMode 7 | { 8 | /// 9 | /// Start from 0. 10 | /// 11 | initial, 12 | 13 | /// 14 | /// Get current network height. If fails - start from 0. 15 | /// 16 | network, 17 | 18 | /// 19 | /// Get saved last height from database. Otherwise - warmup. 20 | /// 21 | database 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /ANSDataContext/ANSContext.cs: -------------------------------------------------------------------------------- 1 | using Adamant.NotificationService.Models; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Design; 4 | 5 | namespace Adamant.NotificationService.DataContext 6 | { 7 | public class ANSContext: DbContext, IDesignTimeDbContextFactory 8 | { 9 | private readonly string designConnectionString = ""; 10 | 11 | public DbSet Devices { get; set; } 12 | public DbSet ServiceStates { get; set; } 13 | 14 | #region Ctor 15 | 16 | public ANSContext(DbContextOptions options) : base(options) 17 | { 18 | } 19 | 20 | public ANSContext(string connectionString, string provider): base(OptionsWithConnectionString(connectionString, provider)) 21 | { 22 | } 23 | 24 | public ANSContext() : base() 25 | {} 26 | 27 | public ANSContext CreateDbContext(string[] args) 28 | { 29 | var optionsBuilder = new DbContextOptionsBuilder(); 30 | optionsBuilder.UseMySQL(designConnectionString); 31 | return new ANSContext(optionsBuilder.Options); 32 | } 33 | 34 | protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 35 | { 36 | if (!optionsBuilder.IsConfigured) 37 | { 38 | optionsBuilder.UseMySQL(designConnectionString); 39 | } 40 | } 41 | 42 | #endregion 43 | 44 | #region Internal 45 | 46 | protected static DbContextOptions OptionsWithConnectionString(string connectionString, string provider) 47 | { 48 | var optionsBuilder = new DbContextOptionsBuilder(); 49 | 50 | switch (provider?.ToLower()) 51 | { 52 | case null: 53 | case "mysql": 54 | optionsBuilder.UseMySQL(connectionString); 55 | break; 56 | 57 | case "sqlite": 58 | optionsBuilder.UseSqlite(connectionString); 59 | break; 60 | } 61 | 62 | return optionsBuilder.Options; 63 | } 64 | 65 | #endregion 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /ANSDataContext/ANSDataContext.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp3.0 6 | Adamant.NotificationService.DataContext 7 | 0.4.1 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /ANSDataContext/Migrations/20180511150347_InitialCreate.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Adamant.NotificationService.DataContext; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using MySql.Data.EntityFrameworkCore.Storage.Internal; 8 | using System; 9 | 10 | namespace Adamant.NotificationService.DataContext.Migrations 11 | { 12 | [DbContext(typeof(ANSContext))] 13 | [Migration("20180511150347_InitialCreate")] 14 | partial class InitialCreate 15 | { 16 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("ProductVersion", "2.0.3-rtm-10026"); 21 | 22 | modelBuilder.Entity("Adamant.NotificationService.Models.Device", b => 23 | { 24 | b.Property("ID") 25 | .ValueGeneratedOnAdd(); 26 | 27 | b.Property("Address"); 28 | 29 | b.Property("RegistrationDate"); 30 | 31 | b.Property("Token"); 32 | 33 | b.HasKey("ID"); 34 | 35 | b.ToTable("Devices"); 36 | }); 37 | #pragma warning restore 612, 618 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /ANSDataContext/Migrations/20180511150347_InitialCreate.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | using System; 3 | using System.Collections.Generic; 4 | 5 | namespace Adamant.NotificationService.DataContext.Migrations 6 | { 7 | public partial class InitialCreate : Migration 8 | { 9 | protected override void Up(MigrationBuilder migrationBuilder) 10 | { 11 | migrationBuilder.CreateTable( 12 | name: "Devices", 13 | columns: table => new 14 | { 15 | ID = table.Column(nullable: false) 16 | .Annotation("MySQL:AutoIncrement", true), 17 | Address = table.Column(nullable: true), 18 | RegistrationDate = table.Column(nullable: false), 19 | Token = table.Column(nullable: true) 20 | }, 21 | constraints: table => 22 | { 23 | table.PrimaryKey("PK_Devices", x => x.ID); 24 | }); 25 | } 26 | 27 | protected override void Down(MigrationBuilder migrationBuilder) 28 | { 29 | migrationBuilder.DropTable( 30 | name: "Devices"); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /ANSDataContext/Migrations/20180611083124_Provider.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Adamant.NotificationService.DataContext; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using MySql.Data.EntityFrameworkCore.Storage.Internal; 8 | using System; 9 | 10 | namespace Adamant.NotificationService.DataContext.Migrations 11 | { 12 | [DbContext(typeof(ANSContext))] 13 | [Migration("20180611083124_Provider")] 14 | partial class Provider 15 | { 16 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("ProductVersion", "2.0.3-rtm-10026"); 21 | 22 | modelBuilder.Entity("Adamant.NotificationService.Models.Device", b => 23 | { 24 | b.Property("ID") 25 | .ValueGeneratedOnAdd(); 26 | 27 | b.Property("Address"); 28 | 29 | b.Property("Provider"); 30 | 31 | b.Property("RegistrationDate"); 32 | 33 | b.Property("Token"); 34 | 35 | b.HasKey("ID"); 36 | 37 | b.ToTable("Devices"); 38 | }); 39 | #pragma warning restore 612, 618 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /ANSDataContext/Migrations/20180611083124_Provider.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | using System; 3 | using System.Collections.Generic; 4 | 5 | namespace Adamant.NotificationService.DataContext.Migrations 6 | { 7 | public partial class Provider : Migration 8 | { 9 | protected override void Up(MigrationBuilder migrationBuilder) 10 | { 11 | migrationBuilder.AddColumn( 12 | name: "Provider", 13 | table: "Devices", 14 | nullable: true); 15 | } 16 | 17 | protected override void Down(MigrationBuilder migrationBuilder) 18 | { 19 | migrationBuilder.DropColumn( 20 | name: "Provider", 21 | table: "Devices"); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /ANSDataContext/Migrations/20180626144847_ServiceState.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Adamant.NotificationService.DataContext; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using MySql.Data.EntityFrameworkCore.Storage.Internal; 8 | using System; 9 | 10 | namespace Adamant.NotificationService.DataContext.Migrations 11 | { 12 | [DbContext(typeof(ANSContext))] 13 | [Migration("20180626144847_ServiceState")] 14 | partial class ServiceState 15 | { 16 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("ProductVersion", "2.0.3-rtm-10026"); 21 | 22 | modelBuilder.Entity("Adamant.NotificationService.Models.Device", b => 23 | { 24 | b.Property("ID") 25 | .ValueGeneratedOnAdd(); 26 | 27 | b.Property("Address"); 28 | 29 | b.Property("Provider"); 30 | 31 | b.Property("RegistrationDate"); 32 | 33 | b.Property("Token"); 34 | 35 | b.HasKey("ID"); 36 | 37 | b.ToTable("Devices"); 38 | }); 39 | 40 | modelBuilder.Entity("Adamant.NotificationService.Models.ServiceState", b => 41 | { 42 | b.Property("ID") 43 | .ValueGeneratedOnAdd(); 44 | 45 | b.Property("Date"); 46 | 47 | b.Property("LastHeight"); 48 | 49 | b.Property("Service"); 50 | 51 | b.HasKey("ID"); 52 | 53 | b.ToTable("ServiceStates"); 54 | }); 55 | #pragma warning restore 612, 618 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /ANSDataContext/Migrations/20180626144847_ServiceState.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | using System; 3 | using System.Collections.Generic; 4 | 5 | namespace Adamant.NotificationService.DataContext.Migrations 6 | { 7 | public partial class ServiceState : Migration 8 | { 9 | protected override void Up(MigrationBuilder migrationBuilder) 10 | { 11 | migrationBuilder.CreateTable( 12 | name: "ServiceStates", 13 | columns: table => new 14 | { 15 | ID = table.Column(nullable: false) 16 | .Annotation("MySQL:AutoIncrement", true), 17 | Date = table.Column(nullable: false), 18 | LastHeight = table.Column(nullable: false), 19 | Service = table.Column(nullable: true) 20 | }, 21 | constraints: table => 22 | { 23 | table.PrimaryKey("PK_ServiceStates", x => x.ID); 24 | }); 25 | } 26 | 27 | protected override void Down(MigrationBuilder migrationBuilder) 28 | { 29 | migrationBuilder.DropTable( 30 | name: "ServiceStates"); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /ANSDataContext/Migrations/20180626152910_DeviceTransactionDate.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Adamant.NotificationService.DataContext; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using MySql.Data.EntityFrameworkCore.Storage.Internal; 8 | using System; 9 | 10 | namespace Adamant.NotificationService.DataContext.Migrations 11 | { 12 | [DbContext(typeof(ANSContext))] 13 | [Migration("20180626152910_DeviceTransactionDate")] 14 | partial class DeviceTransactionDate 15 | { 16 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("ProductVersion", "2.0.3-rtm-10026"); 21 | 22 | modelBuilder.Entity("Adamant.NotificationService.Models.Device", b => 23 | { 24 | b.Property("ID") 25 | .ValueGeneratedOnAdd(); 26 | 27 | b.Property("Address"); 28 | 29 | b.Property("Provider"); 30 | 31 | b.Property("RegistrationDate"); 32 | 33 | b.Property("Token"); 34 | 35 | b.Property("TransactionDate"); 36 | 37 | b.HasKey("ID"); 38 | 39 | b.ToTable("Devices"); 40 | }); 41 | 42 | modelBuilder.Entity("Adamant.NotificationService.Models.ServiceState", b => 43 | { 44 | b.Property("ID") 45 | .ValueGeneratedOnAdd(); 46 | 47 | b.Property("Date"); 48 | 49 | b.Property("LastHeight"); 50 | 51 | b.Property("Service"); 52 | 53 | b.HasKey("ID"); 54 | 55 | b.ToTable("ServiceStates"); 56 | }); 57 | #pragma warning restore 612, 618 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /ANSDataContext/Migrations/20180626152910_DeviceTransactionDate.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | using System; 3 | using System.Collections.Generic; 4 | 5 | namespace Adamant.NotificationService.DataContext.Migrations 6 | { 7 | public partial class DeviceTransactionDate : Migration 8 | { 9 | protected override void Up(MigrationBuilder migrationBuilder) 10 | { 11 | migrationBuilder.AddColumn( 12 | name: "TransactionDate", 13 | table: "Devices", 14 | nullable: false, 15 | defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); 16 | } 17 | 18 | protected override void Down(MigrationBuilder migrationBuilder) 19 | { 20 | migrationBuilder.DropColumn( 21 | name: "TransactionDate", 22 | table: "Devices"); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /ANSDataContext/Migrations/DevicesContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Adamant.NotificationService.DataContext; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using MySql.Data.EntityFrameworkCore.Storage.Internal; 8 | using System; 9 | 10 | namespace Adamant.NotificationService.DataContext.Migrations 11 | { 12 | [DbContext(typeof(ANSContext))] 13 | partial class DevicesContextModelSnapshot : ModelSnapshot 14 | { 15 | protected override void BuildModel(ModelBuilder modelBuilder) 16 | { 17 | #pragma warning disable 612, 618 18 | modelBuilder 19 | .HasAnnotation("ProductVersion", "2.0.3-rtm-10026"); 20 | 21 | modelBuilder.Entity("Adamant.NotificationService.Models.Device", b => 22 | { 23 | b.Property("ID") 24 | .ValueGeneratedOnAdd(); 25 | 26 | b.Property("Address"); 27 | 28 | b.Property("Provider"); 29 | 30 | b.Property("RegistrationDate"); 31 | 32 | b.Property("Token"); 33 | 34 | b.Property("TransactionDate"); 35 | 36 | b.HasKey("ID"); 37 | 38 | b.ToTable("Devices"); 39 | }); 40 | 41 | modelBuilder.Entity("Adamant.NotificationService.Models.ServiceState", b => 42 | { 43 | b.Property("ID") 44 | .ValueGeneratedOnAdd(); 45 | 46 | b.Property("Date"); 47 | 48 | b.Property("LastHeight"); 49 | 50 | b.Property("Service"); 51 | 52 | b.HasKey("ID"); 53 | 54 | b.ToTable("ServiceStates"); 55 | }); 56 | #pragma warning restore 612, 618 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /ANSDataContext/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using Microsoft.EntityFrameworkCore; 4 | 5 | namespace Adamant.NotificationService.DataContext 6 | { 7 | class Program 8 | { 9 | static void Main(string[] args) 10 | { 11 | var connectionString = ""; 12 | 13 | var optionsBuilder = new DbContextOptionsBuilder(); 14 | optionsBuilder.UseMySQL(connectionString); 15 | 16 | var context = new ANSContext(optionsBuilder.Options); 17 | context.Database.Migrate(); 18 | Console.WriteLine("Total registered devices: {0}", context.Devices.Count()); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /ANSPollingWorker/ANSPollingWorker.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp3.0 6 | Adamant.NotificationService.PollingWorker 7 | ANSPollingWorker 8 | 0.4.1 9 | 10 | 11 | 12 | Latest 13 | 14 | 15 | Latest 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /ANSPollingWorker/ChatPollingWorker.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Threading.Tasks; 4 | using Adamant.Api; 5 | using Adamant.Models; 6 | using Adamant.NotificationService.DataContext; 7 | using Microsoft.Extensions.Logging; 8 | 9 | namespace Adamant.NotificationService.PollingWorker 10 | { 11 | public class ChatPollingWorker: TransactionsPollingWorkerBase 12 | { 13 | public override string ServiceName { get; } = "ChatPoller"; 14 | 15 | public ChatPollingWorker(ILogger logger, 16 | AdamantApi api, 17 | IPusher pusher, 18 | ANSContext context) : base(logger, api, pusher, context) 19 | { 20 | } 21 | 22 | protected override async Task> GetNewTransactions(int height, int offset = 0) 23 | { 24 | return await Api.GetChatTransactions(height, offset); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /ANSPollingWorker/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Threading.Tasks; 4 | using Adamant.Api; 5 | using Adamant.NotificationService.ApplePusher; 6 | using Adamant.NotificationService.DataContext; 7 | using Adamant.NotificationService.Models; 8 | using Microsoft.EntityFrameworkCore; 9 | using Microsoft.Extensions.Configuration; 10 | using Microsoft.Extensions.DependencyInjection; 11 | using Microsoft.Extensions.Logging; 12 | using NLog.Extensions.Logging; 13 | 14 | namespace Adamant.NotificationService.PollingWorker 15 | { 16 | class Program 17 | { 18 | #region Properties 19 | 20 | private static NLog.ILogger _logger; 21 | private static ANSContext _context; 22 | 23 | #endregion 24 | 25 | static void Main() 26 | { 27 | AppDomain.CurrentDomain.UnhandledException += Global_UnhandledException; 28 | 29 | #region Config 30 | 31 | var configuration = ConfigurationLoader.GetConfiguration(); 32 | 33 | var provider = configuration["Database:Provider"]; 34 | var connectionName = configuration["Database:ConnectionString"] ?? "devices"; 35 | var connectionString = configuration.GetConnectionString(connectionName); 36 | 37 | if (!int.TryParse(configuration["PollingWorker:Delay"], out int delay)) 38 | delay = 2000; 39 | 40 | if (!Enum.TryParse(configuration["PollingWorker:Startup"], out StartupMode startupMode)) 41 | startupMode = StartupMode.database; 42 | 43 | #endregion 44 | 45 | #region Services 46 | 47 | // Data context 48 | _context = new ANSContext(connectionString, provider); 49 | _context.Database.Migrate(); 50 | 51 | // API 52 | var api = new AdamantApi(configuration); 53 | 54 | #endregion 55 | 56 | #region DI & NLog 57 | 58 | var nLogConfig = configuration["PollingWorker:NlogConfig"]; 59 | if (String.IsNullOrEmpty(nLogConfig)) 60 | nLogConfig = "nlog.config"; 61 | else 62 | nLogConfig = Utilities.HandleUnixHomeDirectory(nLogConfig); 63 | 64 | _logger = NLog.LogManager.LoadConfiguration(nLogConfig).GetCurrentClassLogger(); 65 | 66 | var services = new ServiceCollection(); 67 | 68 | // Application services 69 | 70 | services.AddSingleton(configuration); 71 | services.AddSingleton(); 72 | services.AddSingleton(typeof(IPusher), typeof(ApplePusher.ApplePusher)); 73 | services.AddSingleton(_context); 74 | 75 | // Polling workers 76 | services.AddSingleton(); 77 | services.AddSingleton(); 78 | 79 | // Other 80 | services.AddSingleton(); 81 | services.AddSingleton(typeof(ILogger<>), typeof(Logger<>)); 82 | services.AddLogging(b => b.SetMinimumLevel(LogLevel.Trace)); 83 | 84 | var serviceProvider = services.BuildServiceProvider(); 85 | 86 | var loggerFactory = serviceProvider.GetRequiredService(); 87 | 88 | loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true }); 89 | 90 | #endregion 91 | 92 | var totalDevices = _context.Devices.Count(); 93 | _logger.Info("Database initialized. Total devices in db: {0}", totalDevices); 94 | _logger.Info("Starting polling. Delay: {0}ms.", delay); 95 | 96 | var applePusher = serviceProvider.GetRequiredService(); 97 | applePusher.OnInvalidToken += ApplePusher_OnInvalidToken; 98 | applePusher.Start(); 99 | 100 | var chatWorker = serviceProvider.GetRequiredService(); 101 | chatWorker.Delay = TimeSpan.FromMilliseconds(delay); 102 | chatWorker.StartPolling(startupMode); 103 | 104 | var transferWorker = serviceProvider.GetRequiredService(); 105 | transferWorker.Delay = TimeSpan.FromMilliseconds(delay); 106 | transferWorker.StartPolling(startupMode); 107 | 108 | Task.WaitAll(chatWorker.PollingTask, transferWorker.PollingTask); 109 | } 110 | 111 | // Log all unhandled exceptions 112 | static void Global_UnhandledException(object sender, UnhandledExceptionEventArgs e) 113 | { 114 | _logger.Fatal(e.ExceptionObject); 115 | } 116 | 117 | static void ApplePusher_OnInvalidToken(IPusher sender, InvalidTokenEventArgs eventArgs) 118 | { 119 | var device = _context.Devices.FirstOrDefault(d => d.Token.Equals(eventArgs.Token)); 120 | 121 | if (device != null) 122 | { 123 | _logger.Info("Removing invalid/expired token: {0}", eventArgs.Token); 124 | _context.Devices.Remove(device); 125 | _context.SaveChanges(); 126 | } 127 | } 128 | 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /ANSPollingWorker/TransactionsPollingWorkerBase.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using Adamant.Api; 4 | using Adamant.Models; 5 | using Adamant.NotificationService.DataContext; 6 | using Adamant.NotificationService.Models; 7 | using Microsoft.Extensions.Logging; 8 | 9 | namespace Adamant.NotificationService.PollingWorker 10 | { 11 | public abstract class TransactionsPollingWorkerBase : PollingWorkerBase 12 | { 13 | #region Dependencies 14 | 15 | protected readonly IPusher _pusher; 16 | 17 | #endregion 18 | 19 | public TransactionsPollingWorkerBase(ILogger> logger, 20 | AdamantApi api, 21 | IPusher pusher, 22 | ANSContext context) : base(api, context, logger) 23 | { 24 | _pusher = pusher; 25 | } 26 | 27 | protected override void ProcessNewTransactions(IEnumerable transactions) 28 | { 29 | var count = transactions.Count(); 30 | if (count == 0) 31 | { 32 | Logger.LogWarning("Requested to process 0 transactions"); 33 | return; 34 | } 35 | 36 | Logger.LogInformation("Processing {0} transactions.", count); 37 | 38 | var recipients = transactions.GroupBy(t => t.RecipientId); 39 | var devicesToNotify = new List<(Device device, IEnumerable transactions)>(); 40 | 41 | foreach (var recipient in recipients) 42 | { 43 | var address = recipient.Key; 44 | 45 | if (string.IsNullOrEmpty(address)) 46 | continue; 47 | 48 | var registeredDevices = Context.Devices.Where(d => d.Address.Equals(address)); 49 | 50 | foreach (var device in registeredDevices) 51 | devicesToNotify.Add((device, recipient.AsEnumerable())); 52 | } 53 | 54 | Logger.LogInformation("Notifying {0} devices.", devicesToNotify.Count); 55 | 56 | foreach (var d in devicesToNotify) 57 | { 58 | _pusher.NotifyDevice(d.device, d.transactions); 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /ANSPollingWorker/TransferPollingWorker.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using Adamant.Api; 4 | using Adamant.Models; 5 | using Adamant.NotificationService.DataContext; 6 | using Microsoft.Extensions.Logging; 7 | 8 | namespace Adamant.NotificationService.PollingWorker 9 | { 10 | public class TransferPollingWorker: TransactionsPollingWorkerBase 11 | { 12 | public override string ServiceName { get; } = "TransferPoller"; 13 | 14 | public TransferPollingWorker(ILogger logger, 15 | AdamantApi api, 16 | IPusher pusher, 17 | ANSContext context) : base(logger, api, pusher, context) 18 | { 19 | } 20 | 21 | protected override async Task> GetNewTransactions(int height, int offset = 0) 22 | { 23 | return await Api.GetTransactions(height, offset, TransactionType.Send); 24 | } 25 | 26 | protected override int GetLastHeight(IEnumerable transactions) 27 | { 28 | // Last height. API returns transactions with height >= lastHeight. So +1. 29 | return base.GetLastHeight(transactions) + 1; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /ANSShared/ANSShared.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.0 5 | 0.4.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /ANSShared/PollingWorkerBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using Adamant.Api; 7 | using Adamant.Models; 8 | using Adamant.NotificationService.DataContext; 9 | using Adamant.NotificationService.Models; 10 | using Microsoft.Extensions.Logging; 11 | 12 | namespace Adamant.NotificationService 13 | { 14 | public abstract class PollingWorkerBase where T: Transaction 15 | { 16 | #region Dependencies 17 | 18 | protected ILogger> Logger { get; } 19 | protected ANSContext Context { get; } 20 | protected AdamantApi Api { get; } 21 | 22 | #endregion 23 | 24 | #region Properties 25 | 26 | public abstract string ServiceName { get; } 27 | 28 | private CancellationTokenSource _tokenSource; 29 | 30 | public Task PollingTask { get; private set; } 31 | 32 | public int LastHeight { get; private set; } 33 | 34 | /// 35 | /// Amount of transactions for every request. Not all API's provides support for this param. 36 | /// 37 | public int TransactionsLimit { get; } = 100; 38 | public TimeSpan Delay { get; set; } 39 | 40 | public bool IsWorking { get; private set; } 41 | 42 | #endregion 43 | 44 | #region Ctor 45 | 46 | protected PollingWorkerBase(AdamantApi api, ANSContext context, ILogger> logger) 47 | { 48 | Api = api; 49 | Context = context; 50 | Logger = logger; 51 | } 52 | 53 | #endregion 54 | 55 | #region Public API 56 | 57 | public void StartPolling(StartupMode startupMode) 58 | { 59 | if (IsWorking) 60 | return; 61 | 62 | IsWorking = true; 63 | 64 | Logger.LogInformation("Start polling"); 65 | 66 | _tokenSource = new CancellationTokenSource(); 67 | PollingTask = UpdateTransactionsLoop(startupMode, _tokenSource.Token); 68 | } 69 | 70 | public void StopPolling() 71 | { 72 | if (!IsWorking) 73 | return; 74 | 75 | Logger.LogInformation("Stop polling"); 76 | _tokenSource?.Cancel(); 77 | 78 | IsWorking = false; 79 | } 80 | 81 | #endregion 82 | 83 | #region Logic 84 | 85 | private async Task UpdateTransactionsLoop(StartupMode startupMode, CancellationToken token) 86 | { 87 | switch (startupMode) 88 | { 89 | case StartupMode.database: 90 | Logger.LogInformation("Getting stored height from databse..."); 91 | LastHeight = GetStoredLastHeight(); 92 | 93 | if (LastHeight == 0) 94 | { 95 | Logger.LogInformation("No stored height, warming up from network."); 96 | LastHeight = await GetNetworkCurrentLastHeight(); 97 | } 98 | 99 | break; 100 | 101 | case StartupMode.network: 102 | Logger.LogInformation("Warming up, getting current top height."); 103 | LastHeight = await GetNetworkCurrentLastHeight(); 104 | break; 105 | 106 | case StartupMode.initial: 107 | break; 108 | } 109 | 110 | Logger.LogInformation("Begin polling from {0}", LastHeight); 111 | 112 | while (!token.IsCancellationRequested) 113 | { 114 | Logger.LogDebug("Updating from height: {0}", LastHeight); 115 | 116 | var transactions = await GetTransactions(LastHeight); 117 | 118 | if (transactions != null && transactions.Count > 0) 119 | { 120 | Logger.LogInformation("Got {0} new transactions, processing", transactions.Count); 121 | ProcessNewTransactions(transactions); 122 | LastHeight = GetLastHeight(transactions); 123 | Logger.LogInformation("New lastHeight: {0}", LastHeight); 124 | StoreLastHeight(); 125 | } 126 | else 127 | Logger.LogDebug("Got 0, delay."); 128 | 129 | await Task.Delay(Delay); 130 | } 131 | } 132 | 133 | private async Task> GetTransactions(int height, int offset = 0) 134 | { 135 | var transactions = await GetNewTransactions(height, offset); 136 | var list = new List(transactions); 137 | 138 | var count = transactions.Count(); 139 | if (count >= TransactionsLimit) 140 | { 141 | Logger.LogDebug("Received {0} transactions. Requesting more. (h: {1}, o: {2})", count, height, offset); 142 | var more = await GetTransactions(height, offset + TransactionsLimit); 143 | list.AddRange(more); 144 | } 145 | 146 | return list; 147 | } 148 | 149 | #endregion 150 | 151 | #region Abstract 152 | 153 | /// 154 | /// Processes received new transactions. This method should return new last height. 155 | /// 156 | /// New transactions. 157 | /// Last height 158 | protected abstract void ProcessNewTransactions(IEnumerable transactions); 159 | 160 | /// 161 | /// Gets the new transactions from API. 162 | /// 163 | /// New transactions. 164 | /// Height. 165 | /// Offset. 166 | protected abstract Task> GetNewTransactions(int height, int offset = 0); 167 | 168 | /// 169 | /// Get current Blockchain latest height. 170 | /// 171 | protected virtual async Task GetNetworkCurrentLastHeight() 172 | { 173 | var transactions = await Api.GetTransactions(0, 0, null, 1); 174 | return transactions?.FirstOrDefault()?.Height ?? 0; 175 | } 176 | 177 | /// 178 | /// Gets stored last height from dabatase. 179 | /// 180 | protected virtual int GetStoredLastHeight() 181 | { 182 | return Context.ServiceStates.FirstOrDefault(ss => ss.Service.Equals(ServiceName))?.LastHeight ?? 0; 183 | } 184 | 185 | protected virtual void StoreLastHeight() 186 | { 187 | var serviceState = Context.ServiceStates.FirstOrDefault(ss => ss.Service.Equals(ServiceName)); 188 | if (serviceState == null) 189 | { 190 | serviceState = new ServiceState { Service = ServiceName }; 191 | Context.ServiceStates.Add(serviceState); 192 | } 193 | 194 | serviceState.LastHeight = LastHeight; 195 | serviceState.Date = DateTime.UtcNow; 196 | Context.SaveChanges(); 197 | } 198 | 199 | /// 200 | /// Calculate last height 201 | /// 202 | /// Last height 203 | protected virtual int GetLastHeight(IEnumerable transactions) 204 | { 205 | return transactions.OrderByDescending(t => t.Height).First().Height; 206 | } 207 | 208 | #endregion 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /ANSSignalsRegistration/ANSSignalsRegistration.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp3.0 6 | Adamant.NotificationService.SignalsRegistration 7 | ANSSignalPollingWorker 8 | 0.4.1 9 | 10 | 11 | 12 | 7.1 13 | 14 | 15 | 7.1 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /ANSSignalsRegistration/DeviceInfo.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace Adamant.NotificationService.SignalsRegistration 4 | { 5 | public class DeviceInfo 6 | { 7 | [JsonProperty("token")] 8 | public string Token { get; set; } 9 | 10 | [JsonProperty("provider")] 11 | public string Provider { get; set; } 12 | 13 | /// 14 | /// // "add" - enable push notification, "remove" - disable notification for specific token and address 15 | /// 16 | [JsonProperty(PropertyName = "action", Required = Required.Default)] 17 | [JsonConverter(typeof(SignalActionConverter))] 18 | public SignalAction Action { get; set; } = SignalAction.add; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /ANSSignalsRegistration/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Threading.Tasks; 4 | using Adamant.Api; 5 | using Adamant.NotificationService.DataContext; 6 | using Adamant.NotificationService.Models; 7 | using Microsoft.EntityFrameworkCore; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.DependencyInjection; 10 | using Microsoft.Extensions.Logging; 11 | using NLog.Extensions.Logging; 12 | 13 | namespace Adamant.NotificationService.SignalsRegistration 14 | { 15 | class Program 16 | { 17 | #region Properties 18 | 19 | private static NLog.ILogger _logger; 20 | 21 | #endregion 22 | 23 | static async Task Main(string[] args) 24 | { 25 | AppDomain.CurrentDomain.UnhandledException += Global_UnhandledException; 26 | 27 | #region Config 28 | 29 | var configuration = ConfigurationLoader.GetConfiguration(); 30 | 31 | var provider = configuration["Database:Provider"]; 32 | var connectionName = configuration["Database:ConnectionString"] ?? "devices"; 33 | var connectionString = configuration.GetConnectionString(connectionName); 34 | 35 | if (!int.TryParse(configuration["SignalsRegistration:Delay"], out int delay)) 36 | delay = 2000; 37 | 38 | if (!Enum.TryParse(configuration["SignalsRegistration:Startup"], out StartupMode startupMode)) 39 | startupMode = StartupMode.database; 40 | 41 | #endregion 42 | 43 | #region Services 44 | 45 | // Data context 46 | var context = new ANSContext(connectionString, provider); 47 | context.Database.Migrate(); 48 | 49 | // API 50 | var api = new AdamantApi(configuration); 51 | 52 | #endregion 53 | 54 | #region DI & NLog 55 | 56 | var nLogConfig = configuration["SignalsRegistration:NlogConfig"]; 57 | if (String.IsNullOrEmpty(nLogConfig)) 58 | nLogConfig = "nlog.config"; 59 | 60 | else 61 | nLogConfig = Utilities.HandleUnixHomeDirectory(nLogConfig); 62 | 63 | _logger = NLog.LogManager.LoadConfiguration(nLogConfig).GetCurrentClassLogger(); 64 | 65 | var services = new ServiceCollection(); 66 | 67 | // Application services 68 | 69 | services.AddSingleton(configuration); 70 | services.AddSingleton(); 71 | services.AddSingleton(context); 72 | 73 | services.AddSingleton(); 74 | 75 | // Other 76 | services.AddSingleton(); 77 | services.AddSingleton(typeof(ILogger<>), typeof(Logger<>)); 78 | services.AddLogging(b => b.SetMinimumLevel(LogLevel.Trace)); 79 | 80 | var serviceProvider = services.BuildServiceProvider(); 81 | 82 | var loggerFactory = serviceProvider.GetRequiredService(); 83 | 84 | loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true }); 85 | 86 | #endregion 87 | 88 | var totalDevices = context.Devices.Count(); 89 | _logger.Info("Database initialized. Total devices in db: {0}", totalDevices); 90 | _logger.Info("Starting polling. Delay: {0}ms.", delay); 91 | 92 | var address = configuration["SignalsRegistration:Address"]; 93 | if (string.IsNullOrEmpty(address)) 94 | throw new Exception("ANS account address is required"); 95 | 96 | var privateKey = configuration["SignalsRegistration:PrivateKey"]; 97 | if (string.IsNullOrEmpty(privateKey)) 98 | throw new Exception("ANS account private key is required"); 99 | 100 | var worker = serviceProvider.GetRequiredService(); 101 | worker.Delay = TimeSpan.FromMilliseconds(delay); 102 | worker.Address = address; 103 | worker.PrivateKey = privateKey; 104 | worker.StartPolling(startupMode); 105 | 106 | if (worker.PollingTask != null) 107 | { 108 | await worker.PollingTask; 109 | } 110 | else 111 | { 112 | throw new Exception("Can't await worker"); 113 | } 114 | } 115 | 116 | // Log all unhandled exceptions 117 | static void Global_UnhandledException(object sender, UnhandledExceptionEventArgs e) 118 | { 119 | _logger.Fatal(e.ExceptionObject); 120 | } 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /ANSSignalsRegistration/SignalAction.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Newtonsoft.Json; 3 | 4 | namespace Adamant.NotificationService.SignalsRegistration 5 | { 6 | public enum SignalAction { add, remove } 7 | 8 | internal class SignalActionConverter : JsonConverter 9 | { 10 | public override bool CanConvert(Type objectType) 11 | { 12 | return objectType == typeof(string); 13 | } 14 | 15 | public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 16 | { 17 | var enumString = (string)reader.Value; 18 | 19 | try 20 | { 21 | return Enum.Parse(typeof(SignalAction), enumString, true); 22 | } 23 | catch 24 | { 25 | return SignalAction.add; 26 | } 27 | } 28 | 29 | public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 30 | { 31 | var action = (SignalAction)value; 32 | 33 | switch (action) 34 | { 35 | case SignalAction.add: 36 | writer.WriteValue("add"); 37 | break; 38 | 39 | case SignalAction.remove: 40 | writer.WriteValue("remove"); 41 | break; 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /ANSSignalsRegistration/SignalsPoller.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Adamant.Api; 6 | using Adamant.Models; 7 | using Microsoft.Extensions.Logging; 8 | using Newtonsoft.Json; 9 | using Adamant.NotificationService.Models; 10 | using System.Security.Cryptography; 11 | using Adamant.NotificationService.DataContext; 12 | 13 | namespace Adamant.NotificationService.SignalsRegistration 14 | { 15 | public class SignalsPoller: PollingWorkerBase 16 | { 17 | #region Properties 18 | 19 | public override string ServiceName { get; } = "SignalsPoller"; 20 | 21 | public string Address { get; set; } 22 | public string PrivateKey { get; set; } 23 | 24 | #endregion 25 | 26 | #region Ctor 27 | 28 | public SignalsPoller(ILogger> logger, 29 | AdamantApi api, 30 | ANSContext context) : base(api, context, logger) 31 | { 32 | } 33 | 34 | #endregion 35 | 36 | protected override async Task> GetNewTransactions(int height, int offset = 0) 37 | { 38 | var transactions = await Api.GetChatTransactions(height, offset, ChatType.signal, Address); 39 | return transactions.Where(t => t.RecipientId.Equals(Address)); 40 | } 41 | 42 | protected override void ProcessNewTransactions(IEnumerable transactions) 43 | { 44 | if (transactions == null) 45 | { 46 | Logger.LogError("Requested to process null transactions"); 47 | return; 48 | } 49 | 50 | var count = transactions.Count(); 51 | if (count == 0) { 52 | Logger.LogWarning("Requested to process 0 transactions"); 53 | return; 54 | } 55 | 56 | var devices = new List(); 57 | var devicesToRemove = new List(); 58 | 59 | foreach (var trs in transactions) 60 | { 61 | var chat = trs.Asset?.Chat; 62 | if (chat == null || chat.Type != ChatType.signal) 63 | { 64 | Logger.LogError("Processing: got transaction with wrong ChatAsset. TransactionId: {0}", trs.Id); 65 | continue; 66 | } 67 | 68 | String message = null; 69 | 70 | try { 71 | message = Encryption.DecodeMessage(chat.Message, chat.Nonce, trs.SenderPublicKey, PrivateKey); 72 | var deviceInfo = JsonConvert.DeserializeObject(message); 73 | var device = new Device 74 | { 75 | Address = trs.SenderId, 76 | Token = deviceInfo.Token, 77 | Provider = deviceInfo.Provider, 78 | TransactionDate = trs.Timestamp.ToDateTime(), 79 | RegistrationDate = DateTime.UtcNow 80 | }; 81 | 82 | switch (deviceInfo.Action) 83 | { 84 | case SignalAction.add: 85 | devices.Add(device); 86 | break; 87 | 88 | case SignalAction.remove: 89 | devicesToRemove.Add(device); 90 | break; 91 | } 92 | } catch (CryptographicException e) { 93 | Logger.LogError(e, 94 | "Failed to decode message.\nTransactionId: {0}\nMessage: {1}\nNonce: {2}, PublicKey: {3}, SecretKey: {4}", 95 | trs.Id, 96 | chat.Message, 97 | chat.Nonce, 98 | trs.SenderPublicKey, 99 | ""); 100 | continue; 101 | } catch (JsonException e) { 102 | Logger.LogError(e, "Failed to deserialize device info. TransactionId: {0}, message: {1}", trs.Id, message); 103 | continue; 104 | } catch (Exception e) { 105 | Logger.LogError(e, "Failed to read device info from message. TransactionId: {0}, message: {1}", trs.Id, message); 106 | continue; 107 | } 108 | } 109 | 110 | Logger.LogInformation("Processed {0} devices.", devices.Count); 111 | 112 | var duplicates = new List(); 113 | foreach (var device in devices) { 114 | var baseDevice = Context.Devices.FirstOrDefault(d => d.Token == device.Token && 115 | d.Address == device.Address && 116 | d.Provider == device.Provider); 117 | 118 | if (baseDevice != null) 119 | duplicates.Add(device); 120 | } 121 | 122 | if (duplicates.Count > 0) { 123 | 124 | duplicates.ForEach(d => devices.Remove(d)); 125 | 126 | if (devices.Count == 0) { 127 | Logger.LogInformation("Found {0} duplicates, nothing to save.", duplicates.Count); 128 | return; 129 | } 130 | } 131 | 132 | try { 133 | Context.AddRange(devices); 134 | Context.SaveChanges(); 135 | } catch (Exception e) { 136 | Logger.LogCritical(e, "Failed to save context"); 137 | } 138 | 139 | // Remove Unsubscribed devices 140 | if (devicesToRemove.Count > 0) { 141 | 142 | foreach (var device in devicesToRemove) 143 | { 144 | Context.RemoveRange(Context.Devices.Where(d => d.Token == device.Token && 145 | d.Address == device.Address)); 146 | } 147 | 148 | try 149 | { 150 | Context.SaveChanges(); 151 | Logger.LogInformation("Unsubscribe {0} devices.", devicesToRemove.Count); 152 | } 153 | catch (Exception e) 154 | { 155 | Logger.LogCritical(e, "Failed to save context"); 156 | } 157 | } 158 | } 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /AdamantApi/AdamantApi.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net.Http; 4 | using System.Net.Http.Headers; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using Adamant.Api.Responses; 8 | using Adamant.Models; 9 | using Microsoft.Extensions.Configuration; 10 | using Newtonsoft.Json; 11 | 12 | namespace Adamant.Api 13 | { 14 | public class AdamantApi 15 | { 16 | #region Properties 17 | 18 | public IConfiguration Configuration { get; } 19 | 20 | public ServerDescription CurrentServer { get; private set; } 21 | public IEnumerable Servers { get => ServersList; } 22 | private List ServersList; 23 | 24 | private static string getTransactions = "api/transactions"; 25 | private static string getChatTransactions = "api/chats/get"; 26 | 27 | private static Random rnd = new Random(); 28 | 29 | #endregion 30 | 31 | #region ctor 32 | 33 | public AdamantApi(IConfiguration configuration) 34 | { 35 | Configuration = configuration; 36 | var endpointsRaw = configuration.GetSection("Api").GetSection("Server").GetChildren(); 37 | 38 | if (endpointsRaw != null) 39 | { 40 | var endpoints = new List(); 41 | 42 | foreach (var raw in endpointsRaw) 43 | { 44 | int? port = null; 45 | if (int.TryParse(raw["port"], out var p)) 46 | port = p; 47 | 48 | endpoints.Add(new ServerDescription(raw["ip"], raw["protocol"], port)); 49 | } 50 | 51 | ServersList = endpoints; 52 | } 53 | 54 | if (Servers == null) 55 | throw new Exception("Can't get endpoint addresses from config"); 56 | 57 | SelectNextEndpoint(); 58 | } 59 | 60 | #endregion 61 | 62 | #region Public Methods 63 | 64 | public async Task> GetTransactions(int height, int offset, TransactionType? type, int? limit = null) 65 | { 66 | var query = new Dictionary 67 | { 68 | { "orderBy", "timestamp:desc" } 69 | }; 70 | 71 | if (type.HasValue) 72 | query.Add("type", ((int)type.Value).ToString()); 73 | 74 | if (height > 0) 75 | query.Add("and:fromHeight", height.ToString()); 76 | 77 | if (offset > 0) 78 | query.Add("offset", offset.ToString()); 79 | 80 | if (limit.HasValue) 81 | query.Add("limit", limit.Value.ToString()); 82 | 83 | var endpoint = BuildEndpoint(CurrentServer, getTransactions, query); 84 | 85 | var results = await GetResponse(endpoint); 86 | return results.Transactions; 87 | } 88 | 89 | public async Task> GetChatTransactions(int height, int offset, ChatType? chatType = null, string address = null) 90 | { 91 | var query = new Dictionary 92 | { 93 | { "orderBy", "timestamp:desc" } 94 | }; 95 | 96 | if (!string.IsNullOrEmpty(address)) 97 | query.Add("isIn", address); 98 | 99 | if (chatType.HasValue) 100 | query.Add("type", ((int)chatType.Value).ToString()); 101 | 102 | if (height > 0) 103 | query.Add("fromHeight", height.ToString()); 104 | 105 | if (offset > 0) 106 | query.Add("offset", offset.ToString()); 107 | 108 | var endpoint = BuildEndpoint(CurrentServer, getChatTransactions, query); 109 | 110 | var results = await GetResponse(endpoint); 111 | return results.Transactions; 112 | } 113 | 114 | #endregion 115 | 116 | #region Internal logic 117 | 118 | public void SelectNextEndpoint() 119 | { 120 | if (ServersList == null) 121 | return; 122 | 123 | CurrentServer = ServersList[rnd.Next(ServersList.Count)]; 124 | } 125 | 126 | public static string BuildEndpoint(ServerDescription server, string function, Dictionary query) 127 | { 128 | var builder = new StringBuilder(server.Url); 129 | builder.Append('/'); 130 | builder.Append(function); 131 | 132 | if (query != null && query.Count > 0) 133 | { 134 | var enumerator = query.GetEnumerator(); 135 | if (enumerator.MoveNext()) 136 | builder.AppendFormat("?{0}={1}", enumerator.Current.Key, enumerator.Current.Value); 137 | 138 | while (enumerator.MoveNext()) 139 | builder.AppendFormat("&{0}={1}", enumerator.Current.Key, enumerator.Current.Value); 140 | } 141 | 142 | return builder.ToString(); 143 | } 144 | 145 | private string BuildEndpointt(string url, int? type, int offset, int height) 146 | { 147 | var builder = new StringBuilder(url); 148 | builder.Append("?orderBy=timestamp:desc"); 149 | 150 | if (type.HasValue) 151 | builder.AppendFormat("&type={0}", type.Value); 152 | 153 | if (offset > 0) 154 | builder.AppendFormat("&offset={0}", offset); 155 | 156 | if (height > 0) 157 | builder.AppendFormat("&fromHeight={0}", height); 158 | 159 | return builder.ToString(); 160 | } 161 | 162 | private async Task GetResponse(string endpoint) 163 | { 164 | if (string.IsNullOrEmpty(endpoint)) 165 | { 166 | throw new ArgumentException("endpoint"); 167 | } 168 | 169 | try 170 | { 171 | var client = new HttpClient(); 172 | client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 173 | 174 | var raw = await client.GetStringAsync(endpoint); 175 | return JsonConvert.DeserializeObject(raw); 176 | } 177 | catch (Exception ex) 178 | { 179 | Console.WriteLine(ex); 180 | throw ex; 181 | } 182 | } 183 | 184 | #endregion 185 | } 186 | } 187 | -------------------------------------------------------------------------------- /AdamantApi/AdamantApi.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.0 5 | Adamant.Api 6 | 0.4.1 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /AdamantApi/Responses/TransactionsResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Adamant.Models; 4 | using Newtonsoft.Json; 5 | 6 | namespace Adamant.Api.Responses 7 | { 8 | internal class TransactionsResponse 9 | { 10 | [JsonProperty("success")] 11 | public bool Success { get; set; } 12 | 13 | [JsonProperty("transactions")] 14 | public IEnumerable Transactions { get; set; } 15 | 16 | [JsonProperty("count")] 17 | public string Count { get; set; } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /AdamantApi/ServerDescription.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | 4 | namespace Adamant.Api 5 | { 6 | public class ServerDescription: IEquatable 7 | { 8 | public string Ip { get; } 9 | public string Protocol { get; } 10 | public int? Port { get; } 11 | 12 | public string Url { get; } 13 | 14 | private ServerDescription() {} 15 | 16 | public ServerDescription(string ip, string protocol, int? port) 17 | { 18 | Ip = ip; 19 | Protocol = protocol; 20 | Port = port; 21 | 22 | Url = BuildUrl(this); 23 | } 24 | 25 | public bool Equals(ServerDescription other) 26 | { 27 | return Ip == other.Ip && 28 | Protocol == other.Protocol && 29 | Port == other.Port; 30 | } 31 | 32 | private static string BuildUrl(ServerDescription server) 33 | { 34 | var sb = new StringBuilder(); 35 | 36 | if (string.IsNullOrEmpty(server.Protocol)) 37 | sb.Append("https://"); 38 | else 39 | sb.AppendFormat("{0}://", server.Protocol); 40 | 41 | sb.Append(server.Ip); 42 | 43 | if (server.Port.HasValue) 44 | sb.AppendFormat(":{0}", server.Port.Value); 45 | 46 | return sb.ToString(); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /AdamantCore.Tests/AdamantCore.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.0 5 | 6 | false 7 | Adamant.Tests 8 | 0.4.1 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /AdamantCore.Tests/UtilitiesTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Xunit; 3 | 4 | namespace Adamant.Tests 5 | { 6 | public class UtilitiesTests 7 | { 8 | [Theory] 9 | [InlineData("~", "{home}")] 10 | [InlineData("~/.ans", "{home}/.ans")] 11 | [InlineData("blabla/~/~/", "blabla/~/~/")] 12 | [InlineData("", "")] 13 | [InlineData(" ", " ")] 14 | [InlineData(null, null)] 15 | [InlineData("/usr/local/", "/usr/local/")] 16 | public void HandleUnixHomedirectory(string path, string expected) 17 | { 18 | String expectedParsed; 19 | if (!string.IsNullOrEmpty(expected)) 20 | expectedParsed = expected.Replace("{home}", Environment.GetFolderPath(Environment.SpecialFolder.Personal)); 21 | else 22 | expectedParsed = expected; 23 | 24 | var handled = Utilities.HandleUnixHomeDirectory(path); 25 | 26 | Assert.Equal(expectedParsed, handled); 27 | } 28 | 29 | [Theory] 30 | [InlineData("U1234567890123456", true)] 31 | [InlineData("U123456", true)] 32 | [InlineData("U12345", false)] 33 | [InlineData("U12345678901234567890123", false)] 34 | [InlineData("B12345678910", false)] 35 | [InlineData("1U2345678910", false)] 36 | [InlineData("12345678910", false)] 37 | [InlineData("U12345d67890", false)] 38 | [InlineData("U12345d7890_", false)] 39 | [InlineData("u12345d67890", false)] 40 | [InlineData(" U12345d67890", false)] 41 | [InlineData("U12345d67890 ", false)] 42 | [InlineData("", false)] 43 | [InlineData(null, false)] 44 | [InlineData(" ", false)] 45 | public void ValidateAdamantAddress(string address, bool expected) 46 | { 47 | var valid = Utilities.IsValidAdamantAddress(address); 48 | Assert.Equal(expected, valid); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /AdamantCore/AdamantCore.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.0 5 | Adamant 6 | 0.4.1 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /AdamantCore/Models/ChatAsset.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace Adamant.Models 4 | { 5 | public class ChatAsset 6 | { 7 | [JsonProperty("message")] 8 | public string Message { get; set; } 9 | 10 | [JsonProperty("own_message")] 11 | public string Nonce { get; set; } 12 | 13 | [JsonProperty("type")] 14 | public ChatType Type { get; set; } 15 | } 16 | } 17 | 18 | /* 19 | "chat": { 20 | "message": "eb331fd5492b6d7bf20867bee77a41713966aaf460593596c3c99879d752696594ca80725f3a1ce739cd686fc4edbf0a0e5698c320a8e73ff8b3f64fb3e535cb647f305a1c180cfe949502c5bed4324b27a7d79a2bb29d908da4303dd58e5755f8a846cf7e52a1799adb63c5a009539c5df0f9a47245fea515dfcd16b068ae58cadf22b7335cbf6a8a07173c5a276b94e2050a700a72bb56c83e8926ee29bfae9187395790d7990bc0ae5505df4e1f52ff276609b3267c854d", 21 | "own_message": "91db73baa96edf533776fcdda017f03bb22bc5090c7255b5", 22 | "type": 1 23 | } 24 | */ -------------------------------------------------------------------------------- /AdamantCore/Models/ChatType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace Adamant.Models 3 | { 4 | public enum ChatType : int 5 | { 6 | messageOld = 0, 7 | message = 1, 8 | signal = 3 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /AdamantCore/Models/Transaction.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Newtonsoft.Json; 4 | 5 | namespace Adamant.Models 6 | { 7 | public class Transaction 8 | { 9 | [JsonProperty("id")] 10 | public string Id { get; set; } 11 | 12 | [JsonProperty("height")] 13 | public int Height { get; set; } 14 | 15 | [JsonProperty("blockId")] 16 | public string BlockId { get; set; } 17 | 18 | [JsonProperty("type")] 19 | public TransactionType Type { get; set; } 20 | 21 | [JsonProperty("timestamp")] 22 | public double Timestamp { get; set; } 23 | 24 | [JsonProperty("senderPublicKey")] 25 | public string SenderPublicKey { get; set; } 26 | 27 | [JsonProperty("requesterPublicKey")] 28 | public string RequesterPublicKey { get; set; } 29 | 30 | [JsonProperty("senderId")] 31 | public string SenderId { get; set; } 32 | 33 | [JsonProperty("recipientId")] 34 | public string RecipientId { get; set; } 35 | 36 | [JsonProperty("recipientPublicKey")] 37 | public string RecipientPublicKey { get; set; } 38 | 39 | [JsonProperty("amount")] 40 | public decimal Amount { get; set; } 41 | 42 | [JsonProperty("fee")] 43 | public decimal Fee { get; set; } 44 | 45 | [JsonProperty("signature")] 46 | public string Signature { get; set; } 47 | 48 | [JsonProperty("signSignature")] 49 | public string SignSignature { get; set; } 50 | 51 | [JsonProperty("signatures")] 52 | public List Signatures { get; set; } 53 | 54 | [JsonProperty("confirmations")] 55 | public UInt32? Confirmations { get; set; } 56 | 57 | [JsonProperty("asset")] 58 | public TransactionAsset Asset { get; set; } 59 | 60 | } 61 | } 62 | 63 | /* Raw JSON 64 | { 65 | "id": "9356000252801394663", 66 | "height": 1, 67 | "blockId": "13096746075322409574", 68 | "type": 0, 69 | "timestamp": 0, 70 | "senderPublicKey": "2efef768fc41949aaf5124d7a3663ae843fec87c930494ce37a54d83383b634d", 71 | "senderId": "U13113937065479682572", 72 | "recipientId": "U2065436277795836384", 73 | "recipientPublicKey": null, 74 | "amount": 392000000000000, 75 | "fee": 0, 76 | "signature": "d61793303db6c1daa813903a4473f10d0b2f5ab965d2da4b6416bfd3a4482777645bdbca04d3ba89e0e21f96bb01bdf443c354b53991c7a1542626e4b345e804", 77 | "signatures": [ 78 | ], 79 | "confirmations": 2448056, 80 | "asset": { 81 | } 82 | } 83 | */ 84 | 85 | /* Chat raw JSON 86 | { 87 | "id": "8564574931493759812", 88 | "height": 2738150, 89 | "blockId": "10228493037174337765", 90 | "type": 8, 91 | "timestamp": 20705948, 92 | "senderPublicKey": "926a4842a7a0cadebcb131b9402f82edff06959c3358441772d9ec53c6f1d03f", 93 | "requesterPublicKey": null, 94 | "senderId": "U14399712535055444887", 95 | "recipientId": "U6714409511125668607", 96 | "recipientPublicKey": null, 97 | "amount": 0, 98 | "fee": 100000, 99 | "signature": "9e749f704bdeeb041ef89962e488f26b17ea5f2ec087a163f14e3749b742e447ba3486348442422b43905bb05bbcfbb0b36147c92149713194c33e7a80bd220e", 100 | "signSignature": null, 101 | "signatures": [ 102 | ], 103 | "confirmations": null, 104 | "asset": { 105 | "chat": { 106 | "message": "16326d3b48defaa145c02c5c3789b7ac35970648e3a3def4f9462babe766281f05713007f626509bfca40337e0b77a561f089676b694b1c141386ed06214aeb3bfcfd1ea7e6116ad53", 107 | "own_message": "a3a3a700722cee019f332d00c371d158fe7d260a016aacc3", 108 | "type": 1 109 | } 110 | } 111 | } 112 | */ 113 | -------------------------------------------------------------------------------- /AdamantCore/Models/TransactionAsset.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace Adamant.Models 4 | { 5 | public class TransactionAsset 6 | { 7 | [JsonProperty("chat")] 8 | public ChatAsset Chat { get; set; } 9 | } 10 | } 11 | 12 | /* 13 | "asset": { 14 | "chat": { 15 | "message": "eb331fd5492b6d7bf20867bee77a41713966aaf460593596c3c99879d752696594ca80725f3a1ce739cd686fc4edbf0a0e5698c320a8e73ff8b3f64fb3e535cb647f305a1c180cfe949502c5bed4324b27a7d79a2bb29d908da4303dd58e5755f8a846cf7e52a1799adb63c5a009539c5df0f9a47245fea515dfcd16b068ae58cadf22b7335cbf6a8a07173c5a276b94e2050a700a72bb56c83e8926ee29bfae9187395790d7990bc0ae5505df4e1f52ff276609b3267c854d", 16 | "own_message": "91db73baa96edf533776fcdda017f03bb22bc5090c7255b5", 17 | "type": 1 18 | } 19 | } 20 | */ -------------------------------------------------------------------------------- /AdamantCore/Models/TransactionType.cs: -------------------------------------------------------------------------------- 1 | namespace Adamant.Models 2 | { 3 | public enum TransactionType: int 4 | { 5 | Send, 6 | Signature, 7 | Delegate, 8 | Vote, 9 | Multi, 10 | Dapp, 11 | InTransfer, 12 | OutTransfer, 13 | ChatMessage, 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /AdamantCore/Utilities.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text.RegularExpressions; 3 | 4 | namespace Adamant 5 | { 6 | public static class Utilities 7 | { 8 | static DateTime MagicAdamantDate = new DateTime(2017, 9, 2, 17, 0, 0, DateTimeKind.Utc); 9 | static String AddressRegex = "^U([0-9]{6,20})$"; 10 | 11 | public static bool IsValidAdamantAddress(string address) 12 | { 13 | if (string.IsNullOrEmpty(address)) 14 | return false; 15 | 16 | return Regex.IsMatch(address, AddressRegex); 17 | } 18 | 19 | /// 20 | /// Convert unix '~' symbol to user homedirectory 21 | /// 22 | /// The unix home directory. 23 | /// Path. 24 | public static string HandleUnixHomeDirectory(string path) 25 | { 26 | if (string.IsNullOrEmpty(path)) 27 | return path; 28 | 29 | if (path[0] == '~') 30 | { 31 | if (path.Length > 0) 32 | return Environment.GetFolderPath(Environment.SpecialFolder.Personal) + path.Substring(1); 33 | 34 | else 35 | Environment.GetFolderPath(Environment.SpecialFolder.Personal); 36 | } 37 | 38 | return path; 39 | } 40 | 41 | public static DateTime ToDateTime(this double timestamp) 42 | { 43 | return MagicAdamantDate.AddSeconds(timestamp); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /AdamantEncryption.Tests/AdamantEncryption.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.0 5 | 6 | false 7 | Adamant.Tests 8 | 0.4.1 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /AdamantEncryption.Tests/EncryptionTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace Adamant.Tests 4 | { 5 | public class EncryptionTests 6 | { 7 | //[Theory] 8 | //[InlineData( 9 | // /* Message */ "common", 10 | // /* senderPublicKey */ "8007a01493bb4b21ec67265769898eb19514d9427bd7b701f96bc9880a6e209f", 11 | // /* senderPrivateKey */ "9001490b166816af75a15a3e2b0174bfe3be3dfaa63147b4f780ed3ab90ffeab8007a01493bb4b21ec67265769898eb19514d9427bd7b701f96bc9880a6e209f", 12 | // /* recipientPublicKey */ "9f895a201fd92cc60ef02d2117d53f00dc2981903cb64b2f214777269b882209", 13 | // /* recipientPrivateKey */ "e91ee8e6a23ac5ff9452a15a3fbd14098dc2c6a5abf6b12464b09eb033580b6d9f895a201fd92cc60ef02d2117d53f00dc2981903cb64b2f214777269b882209" 14 | //)] 15 | //public void Encode(string raw, string senderPublicKey, string senderPrivateKey, string recipientPublicKey, string recipientPrivateKey) 16 | //{ 17 | // var encoded = Encryption.EncodeString(raw, senderPublicKey, recipientPrivateKey); 18 | 19 | // Assert.NotNull(encoded); 20 | // Assert.NotNull(encoded.message); 21 | // Assert.NotNull(encoded.nonce); 22 | 23 | // //var decoded = Encryption.DecodeMessage(encoded.message, encoded.nonce, senderPublicKey, recipientPrivateKey); 24 | 25 | // //Assert.Equal(raw, decoded); 26 | //} 27 | 28 | [Theory] 29 | [InlineData( 30 | "09af1ce7e5ed484ddca3c6d1410cbf4f793ea19210e7", // encoded message 31 | "31caaee2d35dcbd8b614e9d6bf6095393cb5baed259e7e37", // nonce 32 | "9f895a201fd92cc60ef02d2117d53f00dc2981903cb64b2f214777269b882209", // sender public key 33 | "9001490b166816af75a15a3e2b0174bfe3be3dfaa63147b4f780ed3ab90ffeab8007a01493bb4b21ec67265769898eb19514d9427bd7b701f96bc9880a6e209f", // recipient private 34 | "common" // decoded expected 35 | )] 36 | public void Decode(string encoded, string nonce, string senderPublicKey, string recipientPrivateKey, string decodedExpected) 37 | { 38 | var decoded = Encryption.DecodeMessage(encoded, nonce, senderPublicKey, recipientPrivateKey); 39 | 40 | Assert.Equal(decodedExpected, decoded); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /AdamantEncryption/AdamantEncryption.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.0 5 | Adamant 6 | 0.4.1 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /AdamantEncryption/Encryption.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Sodium; 3 | using Nacl; 4 | using System.Security.Cryptography; 5 | using System.Text; 6 | 7 | namespace Adamant 8 | { 9 | public static class Encryption 10 | { 11 | /* 12 | public static byte[] GenerateNonce(int length) 13 | { 14 | var provider = new RNGCryptoServiceProvider(); 15 | var bytes = new byte[length]; 16 | provider.GetBytes(bytes); 17 | 18 | return bytes; 19 | } 20 | 21 | public static (string message, string nonce) EncodeMessage(string message, string recipientPublicKey, string senderPrivateKey) 22 | { 23 | var messageBytes = Encoding.UTF8.GetBytes(message); 24 | var publicKey = Utilities.HexToBinary(recipientPublicKey); 25 | var secretKey = Utilities.HexToBinary(senderPrivateKey); 26 | 27 | var encoded = EncodeMessage(messageBytes, publicKey, secretKey); 28 | 29 | return (Utilities.BinaryToHex(encoded.message), Utilities.BinaryToHex(encoded.nonce)); 30 | } 31 | 32 | public static (byte[] message, byte[] nonce) EncodeMessage(byte[] message, byte[] recipientPublicKey, byte[] senderPrivateKey) 33 | { 34 | var nonce = GenerateNonce(24); 35 | var publicKey = PublicKeyAuth.ConvertEd25519PublicKeyToCurve25519PublicKey(recipientPublicKey); 36 | var secretKey = PublicKeyAuth.ConvertEd25519SecretKeyToCurve25519SecretKey(senderPrivateKey); 37 | 38 | var encodedMessage = TweetNaCl.CryptoBox(message, nonce, recipientPublicKey, senderPrivateKey); 39 | 40 | return (encodedMessage, nonce); 41 | } 42 | */ 43 | 44 | public static string DecodeMessage(string message, string nonce, string senderPublicKey, string recipientPrivateKey) 45 | { 46 | var messageBytes = Utilities.HexToBinary(message); 47 | var nonceBytes = Utilities.HexToBinary(nonce); 48 | var publicKey = Utilities.HexToBinary(senderPublicKey); 49 | var secretKey = Utilities.HexToBinary(recipientPrivateKey); 50 | 51 | var decoded = DecodeMessage(messageBytes, nonceBytes, publicKey, secretKey); 52 | 53 | return Encoding.UTF8.GetString(decoded); 54 | } 55 | 56 | public static byte[] DecodeMessage(byte[] message, byte[] nonce, byte[] senderPublicKey, byte[] recipientPrivateKey) 57 | { 58 | var curvePublicKey = PublicKeyAuth.ConvertEd25519PublicKeyToCurve25519PublicKey(senderPublicKey); 59 | var curveSecretKey = PublicKeyAuth.ConvertEd25519SecretKeyToCurve25519SecretKey(recipientPrivateKey); 60 | 61 | return TweetNaCl.CryptoBoxOpen(message, nonce, curvePublicKey, curveSecretKey); 62 | } 63 | 64 | #region Tools 65 | 66 | public static byte[] HexToBytes(string hex) 67 | { 68 | return Utilities.HexToBinary(hex); 69 | } 70 | 71 | public static string BytesToHex(byte[] bytes){ 72 | return Utilities.BinaryToHex(bytes); 73 | } 74 | 75 | #endregion 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /AdamantUtilities/AdamantUtilities.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.0 5 | Adamant 6 | 0.4.1 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /AdamantUtilities/ConfigurationLoader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.Extensions.Configuration; 3 | 4 | namespace Adamant 5 | { 6 | public static class ConfigurationLoader 7 | { 8 | /// 9 | /// Loads Configuration from '~/.ans' 10 | /// 11 | /// The default configuration. 12 | public static IConfigurationRoot GetConfiguration() 13 | { 14 | var builder = new ConfigurationBuilder() 15 | .SetBasePath(Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "/.ans/") 16 | .AddJsonFile("config.json", false, true); 17 | 18 | return builder.Build(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ADAMANT Notification Service (ANS) 2 | 3 | The first of [ADAMANT Services](https://medium.com/adamant-im/adamant-is-working-on-blockchain-messaging-platform-and-push-notifications-service-765972cce50e), implemented to make secure instant notifications for ADAMANT iOS application. 4 | 5 | Note: ADAMANT Blockchain and Messenger apps are fully functional without ANS and other Services. The goal of ADAMANT Services and ANS is to provide features that can not be implemented on the Blockchain. More on [adamant.im](https://adamant.im). 6 | 7 | ## How it works 8 | 9 | To deliver notification **privately and secure**, 4 parties are involved: 10 | 11 | 1. User's device (i. e., iPhone) 12 | 2. ADAMANT's blockchain 13 | 3. Apple Push Notification Service (APNS) 14 | 4. This application, ADAMANT Notification Service (ANS) 15 | 16 | A workflow runs as: 17 | 18 | - User sends an encrypted signal message with a unique token to an ADAMANT blockchain node. Recipient is ANS's ADAMANT address. See [AIP-6: Signal Messages](https://aips.adamant.im/AIPS/aip-6). 19 | - ANS polls the blockchain and decrypts the user's token 20 | - ANS polls the blockchain and filter transactions, where user's ADM address is the recipient. ANS asks APNS to deliver these transactions (they holds encrypted messages) to a user's device, specified by unique token. 21 | - APNS notifies a user's device 22 | - User's device has a secret key and decrypts messages 23 | 24 | This way a user's device never communicate with ANS, and ANS don't know its IP or other identities. They communicate through a blockchain nodes. 25 | 26 | ## ANS application 27 | 28 | This application, ANS, consists of two main parts: 29 | 30 | **ANSSignalsRegistration** — console application that polls ADAMANT blockchain nodes for new service signals to get device tokens. Message payload must be serialized in JSON and encrypted as other chat transactions. 31 | 32 | Payload format: 33 | 34 | ```json 35 | { 36 | "token": "DeviceToken", 37 | "provider": "apns", 38 | "action": "add" 39 | } 40 | ``` 41 | 42 | - `token`: user's device token 43 | - `provider`: push service provider 44 | - apns: for release builds 45 | - apns-sandbox: for debug builds (not yet supported) 46 | - `action` (optional): signal action 47 | - add (default): register new devise 48 | - remove: unregister device 49 | 50 | **ANSPollingWorker** — console application that polls ADAMANT nodes for new transactions and checks for registered devices of receivers. If there is a registered device for the recipient of the transaction—sends a notification. 51 | 52 | ## QA 53 | 54 | ### Device token? What about security? 55 | 56 | You can read about Apple Push Notification Service (APNS) and security on [Apple's docs](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html). 57 | 58 | In short: 59 | 60 | - We do not use third party services to send notifications. Your tokens and addresses doesn't fly around the Internet. 61 | - It's technically impossible to read a message contents from a transaction for ANS and it is impossible to include decrypted message into push contents. To decrypt a message, secret key is needed. And only user device holds it. 62 | - Starting from version 0.4, ANS includes `txn-id` param in the push content with the transaction id. A client app can get the transaction from a blockchain node and decrypt the message on the device, using a locally stored secret key. This is handled by [NotificationServiceExtension](https://developer.apple.com/documentation/usernotifications/unnotificationserviceextension), and a passphrase (secret key) is stored securely in a [Keychain](https://developer.apple.com/documentation/security/keychain_services). 63 | - Your device token is unique for each application on your device. We can't find your facebook page with your device token, generated for the ADAMANT app. 64 | - New device token is generated each time you reinstall an app, or just re-enable notifications. You can just disable notifications for ADAMANT app, and the device token in ANS database becomes useless. Next time ANS will try to send a push notification, Apple will say the token is broken. 65 | 66 | ### iOS App Badge? 67 | 68 | In iOS, app's badge number is sent to you by a server as a part of a push notification, it's not handled by an application, as application can be even terminated and unloaded from memory at the moment. ANS doesn't know how many messages you haven't read. That's why ANS shows `1` badge, if there any unread messages. Alternative solution is to handle it locally on a device by the NotificationServiceExtension—an app extension, that can modify notification content. 69 | 70 | ## Installation 71 | 72 | ### .NET Core version 73 | 74 | APNS requires HTTP/2 connection. dotnet core 2.1 and 2.2 **does not support it**. 75 | The app is build with is 3.0.100-preview5-011568, and it supports HTTP/2. You can create a self-contained build for a machine without 3.0 runtime on a machine with 3.0 SDK. 76 | 77 | `dotnet publish -c Release -r linux-64 -o {output path} -f netcoreapp3.0` 78 | 79 | [more](https://docs.microsoft.com/ru-ru/dotnet/core/rid-catalog) about -r, [more](https://docs.microsoft.com/ru-ru/dotnet/standard/frameworks) about -f, [download](https://dotnet.microsoft.com/download) dotnet core SDK. 80 | 81 | ### Want to try it out? 82 | 83 | 1. You gonna need a dotnet.core runtime to launch ANS. Go to [Microsoft.com](https://www.microsoft.com/net/learn/get-started) and download SDK for your platform. 84 | 2. Clone or download this repository 85 | 3. Open terminal/console/cmd and type `dotnet restore` in the Solution's folder, or just open the Solution in [Visual Studio](https://www.visualstudio.com). VS will automatically restore NuGet dependencies. 86 | 4. Grab sample config file at Solution's root, edit your connection strings, nodes, delays, certificates, and save it to `{UserHomeDirectory}/.ans/config.json`. See [Configuration](#configuration). 87 | 5. At first launch, the application will auto-upgrade your database. 88 | 6. To launch **ANSPollingWorker**, you need your Apple Push certificate, you can grab it from Apple Developer's center. Place it in `{UserHomeDirectory}/.ans/`, make sure you've specified correct path and certificate's password in the config. Go to terminal, `cd ANSPollingWorker`, `dotnet run`. 89 | 7. To launch **ANSRegistrationService**, type in your ANS account in the config. Go to terminal, `cd ANSRegistrationService`, `dotnet run`. 90 | 8. You can run `dotnet publish -c Release` to create compiled archives. More about dotnet core, and what to do with this 'compiled archives' you can read on [Microsoft.com](https://docs.microsoft.com/ru-ru/dotnet/core/tools/dotnet-publish). 91 | 92 | *You will need a certificate to send a push notifications to APNS, which you can get from your Apple Developer account.* 93 | 94 | ## My own iOS app and ANS server 95 | 96 | If you are building your own iOS ADAMANT application and want to use your own ANS server, you will need to: 97 | 98 | 1. Register ADAMANT account for ANS. Just a regular 'U' account. 99 | 2. In iOS source code, type your ANS account's address and public key in `AdamantResources` struct. 100 | 3. In ANS config, type in your ANS's ADM account address and private key. See [Configuration](#configuration). 101 | 4. To create .pfx certificate with ECDSA private key. First, create a key and download it from your [Apple Developer page](https://developer.apple.com/account/ios/authkey/). Put it in some folder. Open Terminal, navigate to this folder, and type: 102 | 103 | ```bash 104 | openssl req -new -x509 -key key.p8 -out selfsigned.cer 105 | openssl pkcs12 -export -in selfsigned.cer -inkey key.p8 -out cert.pfx 106 | ``` 107 | 108 | Put the .pfx certificate in `~/.ans`, and update the config. 109 | 110 | 5. Done. iOS application will send device tokens to your ANS ADM account, **ANSRegistrationService** will poll signal transactions and register tokens, and **ANSPollingService** will poll new messages/transactions and notify registered devices. 111 | 112 | ## Configuration 113 | 114 | Sample configuration file is located in the Solution's root directory. Both Polling ans Signal registration services loads config from `~/.ans/config.json`, so you have one config file for ANS. 115 | 116 | ### Config sections 117 | 118 | - `Database` (optional): Section for database configuration. Params: 119 | - `ConnectionString` (optional, default: `devices`). ConnectionString name. Strings is specified in `ConnectionStrings` section, see bellow. 120 | - `Provider` (optional): Database connection provider. Two providers are supported: 121 | - `sqlite` 122 | - `mysql` (default) 123 | 124 | - `ConnectionStrings`: a standard dotnet section for connection strings. Active connection string name specified in `Database:ConnectionString` param, default is `devices`. 125 | 126 | - `Api`: ADAMANT node settings. 127 | - `Server[]`: node addresses. Properties: 128 | - `ip` (string): node address (or ip) 129 | - `protocol` (string, optional, default: `https`) 130 | - `port` (int, optional) 131 | 132 | - `PollingWorker`: Polling settings. Properties: 133 | - `Delay` (milliseconds as int, optional, default: `2000`): interval between two requests to retrieve new messages 134 | - `NlogConfig` (string, optional, default: `nlog.config`): path to NLog configuration file 135 | - `Startup` (enum, optional, default: `database`): Startup mode. Options: 136 | - `database`: Try to load saved last blockchain height from database, and start from this value. If failed or no value saved, switch to `network` mode. 137 | - `network`: Try to get last transaction from network and use its height as last height value. If failed or no transaction received, go to `initial` mode. 138 | - `initial`: Start from blockchain height 0. 139 | 140 | - `SignalsRegistration`: Signals polling & registration settings. Properties: 141 | - `Delay` (milliseconds as int, optional, default: 2000): interval between two requests to retrieve new signal transactions 142 | - `NlogConfig` (string, optional, default: `nlog.config`): path to NLog configuration file 143 | - `Address` (string, required): ANS's ADM account address to poll signals 144 | - `PrivateKey` (string, required): ANS's ADM account private key to decrypt signal transactions 145 | - `Startup` (enum, optional, default: `database`): Startup mode. Same options as for `PollingWorker:Startup`. 146 | 147 | - `ApplePusher`: APNS settings. Sections: 148 | - `Keys`. Properties: 149 | - `keyId` (string): Your developer key id. Created and obtained at your [Auth Keys page](https://developer.apple.com/account/ios/authkey/). 150 | - `teamId` (string): Your app developer team id. Obtained at your Apple Dev [Membership Details](developer.apple.com/account/#/membership/). 151 | - `bundleAppId` (string): Your application bundle id 152 | - `pfxPath` (string): Path to self-signed *.pfx certificate. Certificate must contain ECDSA private key 153 | - `pfxPassword` (string): Certificate's password 154 | - `Certificate`. Properties: 155 | - `path` (string): Path to APNS *.p12 certificate 156 | - `pass` (string): Certificate's password 157 | - `Payload[]`. Apple push notifications payload. Properties: 158 | - `transactionType`: `0` for ADM token transfer, `8` for chat transactions and coin transfers 159 | - `title` 160 | - `body` 161 | - `sound` 162 | -------------------------------------------------------------------------------- /SharpPusher/ApnsEnvironment.cs: -------------------------------------------------------------------------------- 1 | namespace SharpPusher 2 | { 3 | public enum ApnsEnvironment 4 | { 5 | Sandbox, Production 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /SharpPusher/ApnsNotification.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Newtonsoft.Json; 3 | 4 | namespace SharpPusher 5 | { 6 | public class ApnsNotification 7 | { 8 | /// 9 | /// Contains Apple-defined keys and is used to determine how the system receiving the notification should alert the user, if at all. 10 | /// 11 | [JsonProperty("aps")] 12 | public ApnsPayload Payload { get; set; } 13 | } 14 | 15 | public class ApnsPayload 16 | { 17 | /// 18 | /// Include this key when you want the system to display a standard alert or a banner. 19 | /// The notification settings for your app on the user’s device determine whether an alert or banner is displayed. 20 | /// 21 | [JsonProperty("alert")] 22 | public ApnsNotificationAlert Alert { get; set; } 23 | 24 | /// 25 | /// Include this key when you want the system to modify the badge of your app icon. 26 | /// If this key is not included in the dictionary, the badge is not changed. 27 | /// To remove the badge, set the value of this key to 0. 28 | /// 29 | [JsonProperty("badge")] 30 | public int? Badge { get; set; } 31 | 32 | /// 33 | /// Include this key when you want the system to play a sound. 34 | /// The value of this key is the name of a sound file in your app’s main bundle or in the Library/Sounds folder of your app’s data container. If the sound file cannot be found, or if you specify defaultfor the value, the system plays the default alert sound. 35 | /// 36 | [JsonProperty("sound")] 37 | public string Sound { get; set; } 38 | 39 | /// 40 | /// Include this key with a value of 1 to configure a background update notification. 41 | /// When this key is present, the system wakes up your app in the background and delivers the notification to its app delegate. 42 | /// 43 | [JsonProperty("content-available")] 44 | public int? ContentAvailable { get; set; } 45 | 46 | /// 47 | /// Provide this key with a string value that represents the notification’s type. 48 | /// This value corresponds to the value in the identifier property of one of your app’s registered categories. 49 | /// 50 | public string Category { get; set; } 51 | 52 | /// 53 | /// Provide this key with a string value that represents the app-specific identifier for grouping notifications. 54 | /// If you provide a Notification Content app extension, you can use this value to group your notifications together. For local notifications, this key corresponds to the threadIdentifier property of the UNNotificationContent object. 55 | /// 56 | [JsonProperty("thread-id")] 57 | public string ThreadId { get; set; } 58 | 59 | /// 60 | /// Provide this key with a value of 1 to configure a mutable notification content on client side with NotificationServiceExtension. 61 | /// 62 | [JsonProperty("mutable-content")] 63 | public int? MutableContent { get; set; } 64 | } 65 | 66 | public class ApnsNotificationAlert 67 | { 68 | /// 69 | /// A short string describing the purpose of the notification. 70 | /// Apple Watch displays this string as part of the notification interface. 71 | /// This string is displayed only briefly and should be crafted so that it can be understood quickly. 72 | /// 73 | [JsonProperty("title")] 74 | public string Title { get; set; } 75 | /// 76 | /// The text of the alert message. 77 | /// 78 | [JsonProperty("body")] 79 | public string Body { get; set; } 80 | 81 | /// 82 | /// The key to a title string in the Localizable.strings file for the current localization. 83 | /// The key string can be formatted with %@ and %n$@ specifiers to take the variables specified in the title-loc-args array. 84 | /// 85 | [JsonProperty("title-loc-key")] 86 | public string TitleLocalizationKey { get; set; } 87 | /// 88 | /// Variable string values to appear in place of the format specifiers in title-loc-key. 89 | /// 90 | [JsonProperty("title-loc-args")] 91 | public string[] TitleLocalizationArgs { get; set; } 92 | 93 | /// 94 | /// A key to an alert-message string in a Localizable.strings file for the current localization (which is set by the user’s language preference). 95 | /// The key string can be formatted with %@ and %n$@ specifiers to take the variables specified in the loc-args array. 96 | /// 97 | [JsonProperty("loc-key")] 98 | public string BodyLocalizationKey { get; set; } 99 | /// 100 | /// Variable string values to appear in place of the format specifiers in loc-key. 101 | /// 102 | [JsonProperty("loc-args")] 103 | public string[] BodyLocalizationArgs { get; set; } 104 | 105 | /// 106 | /// If a string is specified, the system displays an alert that includes the Close and View buttons. 107 | /// The string is used as a key to get a localized string in the current localization to use for the right button’s title instead of “View”. 108 | /// 109 | [JsonProperty("action-loc-key")] 110 | public string ActionLocalizationKey { get; set; } 111 | 112 | /// 113 | /// The filename of an image file in the app bundle, with or without the filename extension. 114 | /// The image is used as the launch image when users tap the action button or move the action slider. 115 | /// If this property is not specified, the system either uses the previous snapshot, uses the image identified by the UILaunchImageFile key in the app’s Info.plist file, or falls back to Default.png. 116 | /// 117 | [JsonProperty("launch-image")] 118 | public string LaunchImage { get; set; } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /SharpPusher/ApnsPusher.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using System.Collections.Generic; 4 | using System.Security.Cryptography; 5 | using System.Security.Cryptography.X509Certificates; 6 | using Jose; 7 | using Newtonsoft.Json; 8 | using System.Net.Http; 9 | using System.Threading.Tasks; 10 | using Microsoft.Extensions.Logging; 11 | 12 | namespace SharpPusher 13 | { 14 | public class ApnsPusher: IPusher 15 | { 16 | #region Const 17 | 18 | public readonly string ProductionUrl = "https://api.push.apple.com"; 19 | public readonly string SandboxUrl = "https://api.development.push.apple.com"; 20 | 21 | public readonly JwsAlgorithm Algorithm = JwsAlgorithm.ES256; 22 | private readonly string AlgorithmAsString = "ES256"; 23 | 24 | public event NotificationSuccessHandler OnNotificationSuccess; 25 | public event NotificationFailedHandler OnNotificationFailed; 26 | 27 | private JsonSerializerSettings _jsonSettings; 28 | 29 | #endregion 30 | 31 | 32 | #region Properties 33 | 34 | public ApnsEnvironment Environment { get; } 35 | public string Host { get; private set; } 36 | 37 | public string KeyId { get; } 38 | public string TeamId { get; } 39 | public string BundleAppId { get; } 40 | 41 | public ECDsa PrivateKey { get; } 42 | 43 | public string JwtToken { get; private set; } 44 | public DateTime JwtTokenDate { get; private set; } 45 | 46 | private readonly ILogger _logger; 47 | 48 | #endregion 49 | 50 | 51 | #region Ctor 52 | 53 | public ApnsPusher(ILogger logger, string keyId, string teamId, string bundleAppId, string certificatePath, string certificatePassword, ApnsEnvironment environment, int port = 443) 54 | { 55 | _logger = logger; 56 | Environment = environment; 57 | KeyId = keyId; 58 | TeamId = teamId; 59 | BundleAppId = bundleAppId; 60 | 61 | switch (Environment) 62 | { 63 | case ApnsEnvironment.Production: 64 | Host = $"{ProductionUrl}:{port}/3/device/"; 65 | break; 66 | 67 | case ApnsEnvironment.Sandbox: 68 | Host = $"{SandboxUrl}:{port}/3/device/"; 69 | break; 70 | } 71 | 72 | try 73 | { 74 | var certificate = new X509Certificate2(certificatePath, certificatePassword); 75 | PrivateKey = certificate.GetECDsaPrivateKey(); 76 | } 77 | catch (Exception e) 78 | { 79 | _logger.LogCritical(e, $"Failed to load certeficate at {certificatePath} with password {certificatePassword}\n"); 80 | throw; 81 | } 82 | 83 | if (PrivateKey == null) 84 | throw new ArgumentException("Certificate does not contains ECDsa private key."); 85 | 86 | _jsonSettings = new JsonSerializerSettings 87 | { 88 | Formatting = Formatting.None, 89 | NullValueHandling = NullValueHandling.Ignore 90 | }; 91 | } 92 | 93 | #endregion 94 | 95 | 96 | #region Logic 97 | 98 | private readonly object jwtLock = new object(); 99 | 100 | /// 101 | /// Packet send 102 | /// 103 | public void SendNotificationsAsync(IEnumerable<(ApnsNotification notification, string token)> notifications) { 104 | lock (jwtLock) 105 | { 106 | if (DateTime.Now.Subtract(JwtTokenDate).TotalHours > 1) 107 | { 108 | JwtToken = GenerateNewJwtToken(); 109 | JwtTokenDate = DateTime.Now; 110 | } 111 | } 112 | 113 | foreach (var (notification, token) in notifications) 114 | { 115 | Task.Run(() => SendNotificationInternal(notification, token)); 116 | } 117 | } 118 | 119 | /// 120 | /// Send single notification 121 | /// 122 | public void SendNotificationAsync(ApnsNotification notification, string deviceToken) 123 | { 124 | lock (jwtLock) 125 | { 126 | if (DateTime.Now.Subtract(JwtTokenDate).TotalHours > 1) 127 | { 128 | JwtToken = GenerateNewJwtToken(); 129 | JwtTokenDate = DateTime.Now; 130 | } 131 | } 132 | 133 | Task.Run(() => SendNotificationInternal(notification, deviceToken)); 134 | } 135 | 136 | private async Task SendNotificationInternal(ApnsNotification notification, string deviceToken) 137 | { 138 | var payload = JsonConvert.SerializeObject(notification, _jsonSettings); 139 | var payloadBytes = new ByteArrayContent(Encoding.UTF8.GetBytes(payload)); 140 | 141 | var uri = new Uri(Host + deviceToken); 142 | 143 | AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); 144 | 145 | try { 146 | using (var client = new HttpClient()) 147 | { 148 | // Prepare HTTP Request 149 | var request = new HttpRequestMessage(HttpMethod.Post, uri); 150 | request.Headers.Add("apns-id", Guid.NewGuid().ToString()); 151 | request.Headers.Add("apns-expiration", "0"); 152 | request.Headers.Add("apns-priority", "10"); 153 | request.Headers.Add("apns-topic", BundleAppId); 154 | request.Content = payloadBytes; 155 | 156 | request.Version = new Version(2, 0); 157 | 158 | lock (jwtLock) { 159 | request.Headers.Add("authorization", $"bearer {JwtToken}"); 160 | } 161 | 162 | _logger.LogDebug($"Push URI: {uri}\nPayload content: {payload}\nHeaders: {request.Headers.ToString()}"); 163 | 164 | // Send request 165 | var response = await client.SendAsync(request); 166 | 167 | _logger.LogDebug($"Response: {response.ToString()}"); 168 | 169 | // Handle response 170 | var apnsResult = (ApnsResult)response.StatusCode; 171 | 172 | if (apnsResult == ApnsResult.Success) 173 | { 174 | var args = new NotificationSuccessEventArgs(deviceToken, notification); 175 | OnNotificationSuccess?.Invoke(this, args); 176 | } 177 | else 178 | { 179 | var bodyRaw = await response.Content.ReadAsStringAsync(); 180 | var body = JsonConvert.DeserializeObject(bodyRaw); 181 | var args = new NotificationFailedEventArgs(deviceToken, notification, apnsResult, body.Reason, null); 182 | OnNotificationFailed?.Invoke(this, args); 183 | } 184 | } 185 | } catch (Exception e) { 186 | var args = new NotificationFailedEventArgs(deviceToken, notification, ApnsResult.UnknownError, null, e); 187 | OnNotificationFailed?.Invoke(this, args); 188 | } 189 | } 190 | 191 | #endregion 192 | 193 | 194 | #region Tools 195 | 196 | /// 197 | /// Convert DateTime to Unix epoch. 198 | /// 199 | private long ToUnixEpochDate(DateTime date) 200 | { 201 | return (long)Math.Round((date.ToUniversalTime() - new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero)).TotalSeconds); 202 | } 203 | 204 | private string GenerateNewJwtToken() 205 | { 206 | var payload = new Dictionary 207 | { 208 | { "iss", TeamId }, 209 | { "iat", ToUnixEpochDate(DateTime.UtcNow) } 210 | }; 211 | var header = new Dictionary 212 | { 213 | { "alg", AlgorithmAsString }, 214 | { "kid", KeyId } 215 | }; 216 | 217 | _logger.LogDebug("Renewed JWT token"); 218 | 219 | return JWT.Encode(payload, PrivateKey, Algorithm, header); 220 | 221 | } 222 | 223 | #endregion 224 | } 225 | } 226 | -------------------------------------------------------------------------------- /SharpPusher/ApnsResponse.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace SharpPusher 4 | { 5 | internal class ApnsResponse 6 | { 7 | [JsonProperty("reason")] 8 | public string Reason { get; set; } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /SharpPusher/ApnsResult.cs: -------------------------------------------------------------------------------- 1 | namespace SharpPusher 2 | { 3 | public enum ApnsResult 4 | { 5 | /// 6 | /// Unknown error. 7 | /// 8 | UnknownError = 0, 9 | 10 | /// 11 | /// Success. 12 | /// 13 | Success = 200, 14 | 15 | /// 16 | /// Bad request. 17 | /// 18 | BadRequest = 400, 19 | 20 | /// 21 | /// There was an error with the certificate or with the provider authentication token. 22 | /// 23 | NotAuthorized = 403, 24 | 25 | /// 26 | /// The request used a bad :method value. Only POST requests are supported. 27 | /// 28 | BadMethod = 405, 29 | 30 | /// 31 | /// The device token is no longer active for the topic. 32 | /// 33 | TokenExpired = 410, 34 | 35 | /// 36 | /// The notification payload was too large. 37 | /// 38 | PayloadTooLarge = 413, 39 | 40 | /// 41 | /// The server received too many requests for the same device token. 42 | /// 43 | TooManyRequests = 429, 44 | 45 | /// 46 | /// Internal server error. 47 | /// 48 | InternalServerError = 500, 49 | 50 | /// 51 | /// The server is shutting down and unavailable. 52 | /// 53 | ServerShuttingDown = 503 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /SharpPusher/IPusher.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace SharpPusher 5 | { 6 | /// 7 | /// Pusher. 8 | /// T for Notification type; 9 | /// U for Resut code type; 10 | /// 11 | public interface IPusher 12 | { 13 | /// 14 | /// Sends the notification on backgroun thread. 15 | /// 16 | void SendNotificationAsync(T notification, string deviceToken); 17 | 18 | /// 19 | /// Sends the notifications on backgroun thread. 20 | /// 21 | void SendNotificationsAsync(IEnumerable<(ApnsNotification notification, string token)> notifications); 22 | 23 | 24 | event NotificationSuccessHandler OnNotificationSuccess; 25 | event NotificationFailedHandler OnNotificationFailed; 26 | } 27 | 28 | public delegate void NotificationSuccessHandler(object sender, NotificationSuccessEventArgs args); 29 | public delegate void NotificationFailedHandler(object sender, NotificationFailedEventArgs args); 30 | 31 | public class NotificationSuccessEventArgs: EventArgs 32 | { 33 | public string Token { get; } 34 | public T Notification { get; } 35 | 36 | public NotificationSuccessEventArgs(string token, T notification) 37 | { 38 | Token = token; 39 | Notification = notification; 40 | } 41 | 42 | } 43 | 44 | public class NotificationFailedEventArgs : EventArgs 45 | { 46 | public string Token { get; } 47 | public T Notification { get; } 48 | public U ResultCode { get; } 49 | public string Reason { get; } 50 | public Exception Exception { get; } 51 | 52 | public NotificationFailedEventArgs(string token, T notification, U resultCode, string reason, Exception exception) 53 | { 54 | Token = token; 55 | Notification = notification; 56 | ResultCode = resultCode; 57 | Reason = reason; 58 | Exception = exception; 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /SharpPusher/SharpPusher.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.0 5 | SharpPusher 6 | 0.1.1 7 | RealBonus 8 | https://github.com/RealBonus/SharpPusher 9 | push;apns;core 10 | 0.4.1 11 | https://github.com/RealBonus/SharpPusher 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /SharpPusherSample/NLog.config: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /SharpPusherSample/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.Extensions.Logging; 3 | using Newtonsoft.Json; 4 | using NLog; 5 | using NLog.Extensions.Logging; 6 | using SharpPusher; 7 | 8 | namespace SharpPusherSample 9 | { 10 | class ExtendedApnsNotification : ApnsNotification 11 | { 12 | [JsonProperty("txn-id")] 13 | public string TxnId { get; set; } 14 | 15 | [JsonProperty("push-recipient")] 16 | public string PushRecipient { get; set; } 17 | } 18 | 19 | class Program 20 | { 21 | static void Main(string[] args) 22 | { 23 | var keyId = ""; 24 | var teamId = ""; 25 | var bundleAppId = ""; 26 | var keyPath = ""; 27 | var keyPassword = ""; 28 | 29 | var deviceToken = ""; 30 | 31 | NLog.LogManager.LoadConfiguration("NLog.config"); 32 | var loggerFactory = new LoggerFactory(); 33 | loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true }); 34 | var logger = loggerFactory.CreateLogger(); 35 | 36 | var pusher = new ApnsPusher(logger, keyId, teamId, bundleAppId, keyPath, keyPassword, ApnsEnvironment.Production); 37 | 38 | var notification = new ExtendedApnsNotification 39 | { 40 | Payload = new ApnsPayload 41 | { 42 | Alert = new ApnsNotificationAlert 43 | { 44 | TitleLocalizationKey = "NotificationsService.NewMessage.Title", 45 | BodyLocalizationKey = "NotificationsService.NewMessage.BodySingle" 46 | }, 47 | Badge = 7, 48 | MutableContent = 1 49 | }, 50 | TxnId = "", 51 | PushRecipient = "" 52 | }; 53 | 54 | pusher.OnNotificationSuccess += OnNotificationSuccess; 55 | pusher.OnNotificationFailed += OnNotificationFailed; 56 | 57 | Console.WriteLine("Sending notification..."); 58 | pusher.SendNotificationAsync(notification, deviceToken); 59 | Console.ReadKey(); 60 | } 61 | 62 | static void OnNotificationSuccess(object sender, NotificationSuccessEventArgs args) 63 | { 64 | Console.WriteLine("Notification success"); 65 | } 66 | 67 | static void OnNotificationFailed(object sender, NotificationFailedEventArgs args) 68 | { 69 | Console.WriteLine("Notification failed. Code: {0}, Reason: {1}", args.ResultCode, args.Reason); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /SharpPusherSample/SharpPusherSample.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp3.0 6 | 0.4.1 7 | 8 | 9 | 10 | Latest 11 | 12 | 13 | Latest 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | PreserveNewest 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /SharpPusherTests/ApnsTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Newtonsoft.Json; 3 | using SharpPusher; 4 | using Xunit; 5 | 6 | namespace SharpPusherTests 7 | { 8 | public class UnitTest1 9 | { 10 | [Fact] 11 | public void ApnsSerialization() 12 | { 13 | var notification = new ApnsNotification 14 | { 15 | Payload = new ApnsPayload 16 | { 17 | Alert = new ApnsNotificationAlert 18 | { 19 | BodyLocalizationKey = "GAME_PLAY_REQUEST_FORMAT", 20 | BodyLocalizationArgs = new string[] { "Jenna", "Frank" } 21 | }, 22 | Sound = "chime.aiff" 23 | } 24 | }; 25 | var expected = "{\"aps\":{\"alert\":{\"loc-key\":\"GAME_PLAY_REQUEST_FORMAT\",\"loc-args\":[\"Jenna\",\"Frank\"]},\"sound\":\"chime.aiff\"}}"; 26 | 27 | var serialized = JsonConvert.SerializeObject(notification, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); 28 | Assert.Equal(expected, serialized); 29 | } 30 | 31 | [Fact] 32 | public void ApnsSerializationMutableContent() 33 | { 34 | var notification = new ApnsNotification 35 | { 36 | Payload = new ApnsPayload 37 | { 38 | Alert = new ApnsNotificationAlert 39 | { 40 | BodyLocalizationKey = "GAME_PLAY_REQUEST_FORMAT", 41 | BodyLocalizationArgs = new string[] { "Jenna", "Frank" } 42 | }, 43 | Sound = "chime.aiff", 44 | MutableContent = 1 45 | } 46 | }; 47 | var expected = "{\"aps\":{\"alert\":{\"loc-key\":\"GAME_PLAY_REQUEST_FORMAT\",\"loc-args\":[\"Jenna\",\"Frank\"]},\"sound\":\"chime.aiff\",\"mutable-content\":1}}"; 48 | 49 | var serialized = JsonConvert.SerializeObject(notification, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); 50 | Assert.Equal(expected, serialized); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /SharpPusherTests/SharpPusherTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.0 5 | 6 | false 7 | 0.4.1 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /adamant-notificationService.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2012 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ANSPollingWorker", "ANSPollingWorker\ANSPollingWorker.csproj", "{AAC036DE-835F-40D4-A252-3FE32D224F68}" 5 | EndProject 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ANSCore", "ANSCore\ANSCore.csproj", "{E20C92AF-3D3F-42BB-BEC3-E8072DE5DA71}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdamantApi", "AdamantApi\AdamantApi.csproj", "{C8B1A3CD-9BA7-49DF-91FA-2A150EA92FE8}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdamantCore", "AdamantCore\AdamantCore.csproj", "{8713FA51-BF01-4C72-8E82-C102F8E04E16}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Adamant", "Adamant", "{CBAAEC9A-47E4-479C-BB79-F2B8962561FB}" 13 | EndProject 14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NotificationService", "NotificationService", "{05ED861E-7905-46D4-843E-8CEB5356A676}" 15 | EndProject 16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ANSDataContext", "ANSDataContext\ANSDataContext.csproj", "{D97E604C-DF2C-4AF3-9AF2-2D0766A8E7ED}" 17 | EndProject 18 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ANSSignalsRegistration", "ANSSignalsRegistration\ANSSignalsRegistration.csproj", "{F16F2B33-34E7-4F15-9587-72B91D39024E}" 19 | EndProject 20 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdamantEncryption.Tests", "AdamantEncryption.Tests\AdamantEncryption.Tests.csproj", "{B73F2526-3D5B-418E-9110-C8068B8E7C97}" 21 | EndProject 22 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdamantEncryption", "AdamantEncryption\AdamantEncryption.csproj", "{79286D2B-E96A-4D24-8148-6B8A696A665B}" 23 | EndProject 24 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdamantUtilities", "AdamantUtilities\AdamantUtilities.csproj", "{FCF99C51-6A1E-4329-8B90-24833FC5FB4C}" 25 | EndProject 26 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdamantCore.Tests", "AdamantCore.Tests\AdamantCore.Tests.csproj", "{43539A4E-BB9F-4677-9572-6BCBBA695F6D}" 27 | EndProject 28 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ANSShared", "ANSShared\ANSShared.csproj", "{9AC7F8FF-8066-4590-BF48-73464CE9C87E}" 29 | EndProject 30 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ANSApplePusher", "ANSApplePusher\ANSApplePusher.csproj", "{2444EAA1-E489-4C2D-B2BC-99EF2C6CC545}" 31 | EndProject 32 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SharpPusher", "SharpPusher", "{90213200-D176-4FEF-8F7F-8519FB24E2BE}" 33 | EndProject 34 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpPusherTests", "SharpPusherTests\SharpPusherTests.csproj", "{19127688-1EF5-4AC8-92EE-BC9919B006B8}" 35 | EndProject 36 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpPusher", "SharpPusher\SharpPusher.csproj", "{E8508322-AA63-4BEE-A6B1-F5B27FB226BE}" 37 | EndProject 38 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpPusherSample", "SharpPusherSample\SharpPusherSample.csproj", "{569D8850-4F64-4858-AAB9-6ECECF0F2644}" 39 | EndProject 40 | Global 41 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 42 | Debug|Any CPU = Debug|Any CPU 43 | Release|Any CPU = Release|Any CPU 44 | EndGlobalSection 45 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 46 | {AAC036DE-835F-40D4-A252-3FE32D224F68}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 47 | {AAC036DE-835F-40D4-A252-3FE32D224F68}.Debug|Any CPU.Build.0 = Debug|Any CPU 48 | {AAC036DE-835F-40D4-A252-3FE32D224F68}.Release|Any CPU.ActiveCfg = Release|Any CPU 49 | {AAC036DE-835F-40D4-A252-3FE32D224F68}.Release|Any CPU.Build.0 = Release|Any CPU 50 | {E20C92AF-3D3F-42BB-BEC3-E8072DE5DA71}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 51 | {E20C92AF-3D3F-42BB-BEC3-E8072DE5DA71}.Debug|Any CPU.Build.0 = Debug|Any CPU 52 | {E20C92AF-3D3F-42BB-BEC3-E8072DE5DA71}.Release|Any CPU.ActiveCfg = Release|Any CPU 53 | {E20C92AF-3D3F-42BB-BEC3-E8072DE5DA71}.Release|Any CPU.Build.0 = Release|Any CPU 54 | {C8B1A3CD-9BA7-49DF-91FA-2A150EA92FE8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 55 | {C8B1A3CD-9BA7-49DF-91FA-2A150EA92FE8}.Debug|Any CPU.Build.0 = Debug|Any CPU 56 | {C8B1A3CD-9BA7-49DF-91FA-2A150EA92FE8}.Release|Any CPU.ActiveCfg = Release|Any CPU 57 | {C8B1A3CD-9BA7-49DF-91FA-2A150EA92FE8}.Release|Any CPU.Build.0 = Release|Any CPU 58 | {8713FA51-BF01-4C72-8E82-C102F8E04E16}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 59 | {8713FA51-BF01-4C72-8E82-C102F8E04E16}.Debug|Any CPU.Build.0 = Debug|Any CPU 60 | {8713FA51-BF01-4C72-8E82-C102F8E04E16}.Release|Any CPU.ActiveCfg = Release|Any CPU 61 | {8713FA51-BF01-4C72-8E82-C102F8E04E16}.Release|Any CPU.Build.0 = Release|Any CPU 62 | {D97E604C-DF2C-4AF3-9AF2-2D0766A8E7ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 63 | {D97E604C-DF2C-4AF3-9AF2-2D0766A8E7ED}.Debug|Any CPU.Build.0 = Debug|Any CPU 64 | {D97E604C-DF2C-4AF3-9AF2-2D0766A8E7ED}.Release|Any CPU.ActiveCfg = Release|Any CPU 65 | {D97E604C-DF2C-4AF3-9AF2-2D0766A8E7ED}.Release|Any CPU.Build.0 = Release|Any CPU 66 | {F16F2B33-34E7-4F15-9587-72B91D39024E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 67 | {F16F2B33-34E7-4F15-9587-72B91D39024E}.Debug|Any CPU.Build.0 = Debug|Any CPU 68 | {F16F2B33-34E7-4F15-9587-72B91D39024E}.Release|Any CPU.ActiveCfg = Release|Any CPU 69 | {F16F2B33-34E7-4F15-9587-72B91D39024E}.Release|Any CPU.Build.0 = Release|Any CPU 70 | {B73F2526-3D5B-418E-9110-C8068B8E7C97}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 71 | {B73F2526-3D5B-418E-9110-C8068B8E7C97}.Debug|Any CPU.Build.0 = Debug|Any CPU 72 | {B73F2526-3D5B-418E-9110-C8068B8E7C97}.Release|Any CPU.ActiveCfg = Release|Any CPU 73 | {B73F2526-3D5B-418E-9110-C8068B8E7C97}.Release|Any CPU.Build.0 = Release|Any CPU 74 | {79286D2B-E96A-4D24-8148-6B8A696A665B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 75 | {79286D2B-E96A-4D24-8148-6B8A696A665B}.Debug|Any CPU.Build.0 = Debug|Any CPU 76 | {79286D2B-E96A-4D24-8148-6B8A696A665B}.Release|Any CPU.ActiveCfg = Release|Any CPU 77 | {79286D2B-E96A-4D24-8148-6B8A696A665B}.Release|Any CPU.Build.0 = Release|Any CPU 78 | {FCF99C51-6A1E-4329-8B90-24833FC5FB4C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 79 | {FCF99C51-6A1E-4329-8B90-24833FC5FB4C}.Debug|Any CPU.Build.0 = Debug|Any CPU 80 | {FCF99C51-6A1E-4329-8B90-24833FC5FB4C}.Release|Any CPU.ActiveCfg = Release|Any CPU 81 | {FCF99C51-6A1E-4329-8B90-24833FC5FB4C}.Release|Any CPU.Build.0 = Release|Any CPU 82 | {43539A4E-BB9F-4677-9572-6BCBBA695F6D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 83 | {43539A4E-BB9F-4677-9572-6BCBBA695F6D}.Debug|Any CPU.Build.0 = Debug|Any CPU 84 | {43539A4E-BB9F-4677-9572-6BCBBA695F6D}.Release|Any CPU.ActiveCfg = Release|Any CPU 85 | {43539A4E-BB9F-4677-9572-6BCBBA695F6D}.Release|Any CPU.Build.0 = Release|Any CPU 86 | {9AC7F8FF-8066-4590-BF48-73464CE9C87E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 87 | {9AC7F8FF-8066-4590-BF48-73464CE9C87E}.Debug|Any CPU.Build.0 = Debug|Any CPU 88 | {9AC7F8FF-8066-4590-BF48-73464CE9C87E}.Release|Any CPU.ActiveCfg = Release|Any CPU 89 | {9AC7F8FF-8066-4590-BF48-73464CE9C87E}.Release|Any CPU.Build.0 = Release|Any CPU 90 | {2444EAA1-E489-4C2D-B2BC-99EF2C6CC545}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 91 | {2444EAA1-E489-4C2D-B2BC-99EF2C6CC545}.Debug|Any CPU.Build.0 = Debug|Any CPU 92 | {2444EAA1-E489-4C2D-B2BC-99EF2C6CC545}.Release|Any CPU.ActiveCfg = Release|Any CPU 93 | {2444EAA1-E489-4C2D-B2BC-99EF2C6CC545}.Release|Any CPU.Build.0 = Release|Any CPU 94 | {19127688-1EF5-4AC8-92EE-BC9919B006B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 95 | {19127688-1EF5-4AC8-92EE-BC9919B006B8}.Debug|Any CPU.Build.0 = Debug|Any CPU 96 | {19127688-1EF5-4AC8-92EE-BC9919B006B8}.Release|Any CPU.ActiveCfg = Release|Any CPU 97 | {19127688-1EF5-4AC8-92EE-BC9919B006B8}.Release|Any CPU.Build.0 = Release|Any CPU 98 | {E8508322-AA63-4BEE-A6B1-F5B27FB226BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 99 | {E8508322-AA63-4BEE-A6B1-F5B27FB226BE}.Debug|Any CPU.Build.0 = Debug|Any CPU 100 | {E8508322-AA63-4BEE-A6B1-F5B27FB226BE}.Release|Any CPU.ActiveCfg = Release|Any CPU 101 | {E8508322-AA63-4BEE-A6B1-F5B27FB226BE}.Release|Any CPU.Build.0 = Release|Any CPU 102 | {569D8850-4F64-4858-AAB9-6ECECF0F2644}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 103 | {569D8850-4F64-4858-AAB9-6ECECF0F2644}.Debug|Any CPU.Build.0 = Debug|Any CPU 104 | {569D8850-4F64-4858-AAB9-6ECECF0F2644}.Release|Any CPU.ActiveCfg = Release|Any CPU 105 | {569D8850-4F64-4858-AAB9-6ECECF0F2644}.Release|Any CPU.Build.0 = Release|Any CPU 106 | EndGlobalSection 107 | GlobalSection(NestedProjects) = preSolution 108 | {C8B1A3CD-9BA7-49DF-91FA-2A150EA92FE8} = {CBAAEC9A-47E4-479C-BB79-F2B8962561FB} 109 | {8713FA51-BF01-4C72-8E82-C102F8E04E16} = {CBAAEC9A-47E4-479C-BB79-F2B8962561FB} 110 | {E20C92AF-3D3F-42BB-BEC3-E8072DE5DA71} = {05ED861E-7905-46D4-843E-8CEB5356A676} 111 | {AAC036DE-835F-40D4-A252-3FE32D224F68} = {05ED861E-7905-46D4-843E-8CEB5356A676} 112 | {D97E604C-DF2C-4AF3-9AF2-2D0766A8E7ED} = {05ED861E-7905-46D4-843E-8CEB5356A676} 113 | {F16F2B33-34E7-4F15-9587-72B91D39024E} = {05ED861E-7905-46D4-843E-8CEB5356A676} 114 | {B73F2526-3D5B-418E-9110-C8068B8E7C97} = {CBAAEC9A-47E4-479C-BB79-F2B8962561FB} 115 | {79286D2B-E96A-4D24-8148-6B8A696A665B} = {CBAAEC9A-47E4-479C-BB79-F2B8962561FB} 116 | {FCF99C51-6A1E-4329-8B90-24833FC5FB4C} = {CBAAEC9A-47E4-479C-BB79-F2B8962561FB} 117 | {43539A4E-BB9F-4677-9572-6BCBBA695F6D} = {CBAAEC9A-47E4-479C-BB79-F2B8962561FB} 118 | {9AC7F8FF-8066-4590-BF48-73464CE9C87E} = {05ED861E-7905-46D4-843E-8CEB5356A676} 119 | {2444EAA1-E489-4C2D-B2BC-99EF2C6CC545} = {05ED861E-7905-46D4-843E-8CEB5356A676} 120 | {19127688-1EF5-4AC8-92EE-BC9919B006B8} = {90213200-D176-4FEF-8F7F-8519FB24E2BE} 121 | {E8508322-AA63-4BEE-A6B1-F5B27FB226BE} = {90213200-D176-4FEF-8F7F-8519FB24E2BE} 122 | {569D8850-4F64-4858-AAB9-6ECECF0F2644} = {90213200-D176-4FEF-8F7F-8519FB24E2BE} 123 | EndGlobalSection 124 | GlobalSection(MonoDevelopProperties) = preSolution 125 | version = 0.4.1 126 | Policies = $0 127 | $0.DotNetNamingPolicy = $1 128 | $1.DirectoryNamespaceAssociation = PrefixedHierarchical 129 | $0.StandardHeader = $2 130 | $0.VersionControlPolicy = $3 131 | EndGlobalSection 132 | EndGlobal 133 | -------------------------------------------------------------------------------- /adamant-notificationService.sublime-project: -------------------------------------------------------------------------------- 1 | { 2 | "folders": 3 | [ 4 | { 5 | "path": "." 6 | } 7 | ] 8 | } 9 | -------------------------------------------------------------------------------- /config.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionStrings": { 3 | "mysql": "Server=localhost" 4 | }, 5 | "Database": { 6 | "Provider": "mysql", 7 | "ConnectionString": "mysql" 8 | }, 9 | "Api": { 10 | "Server": [ 11 | { 12 | "ip": "clown.adamant.im", 13 | "protocol": "https" 14 | }, 15 | { 16 | "ip": "lake.adamant.im", 17 | "protocol": "https" 18 | }, 19 | { 20 | "ip": "endless.adamant.im", 21 | "protocol": "https" 22 | } 23 | ] 24 | }, 25 | "PollingWorker": { 26 | "Warmup": true, 27 | "Delay": 3000 28 | }, 29 | "SignalsRegistration": { 30 | "Warmup": true, 31 | "Delay": 10000, 32 | "Account": "", 33 | "PrivateKey": "" 34 | }, 35 | "ApplePusher": { 36 | "Certificate": { 37 | "path": "~/.ans/cert.p12", 38 | "pass": "" 39 | }, 40 | "Payload": [ 41 | { 42 | "transactionType": 8, 43 | "body": "NotificationsService.NewMessage.BodySingle", 44 | "sound": "notification.mp3" 45 | }, 46 | { 47 | "transactionType": 0, 48 | "body": "NotificationsService.NewTransfer.BodySingle", 49 | "sound": "notification.mp3" 50 | } 51 | ] 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | // "version": "2.0.3" 4 | } 5 | } -------------------------------------------------------------------------------- /nlog.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 8 | 9 | 10 | 11 | 12 | 14 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | --------------------------------------------------------------------------------