using Microsoft.AspNetCore.Mvc; using ServiceOutside.Filter; using ServiceShared; using ServiceShared.Crypto; using ServiceShared.Database; using ServiceShared.Models.Request; using ServiceShared.Models.Response; using ServiceShared.Models.Response.Exception; namespace ServiceOutside.Controllers { [ApiController] [ServiceInsideRequest] [Route("[controller]")] public class ServiceInsideController : BaseController { private readonly ServiceShared.Database.Controllers.Results dbResults; private readonly int MaxOpenedRequest = 10; /// /// Constructor of ServiceInsideController, that getting instance of configuration, dbcontext and KeyPair /// /// Configuration from appsettings.json /// DbContext /// Server Curve25519 KeyPair public ServiceInsideController(IConfiguration configuration, DbContext dbContext, KeyPair keyPair) : base(configuration, dbContext, keyPair) { this.dbResults = new ServiceShared.Database.Controllers.Results(dbContext); string maxOpenedRequests = configuration.GetValue("MaxOpenedRequest"); if (!string.IsNullOrEmpty(maxOpenedRequests)) { int maxOpenedRequestsInt = 0; if (Int32.TryParse(maxOpenedRequests, out maxOpenedRequestsInt)) { MaxOpenedRequest = maxOpenedRequestsInt; } } } /// /// Incoming notification from the ServiceInside /// /// Json Response [Route("notification")] [HttpPost] public JsonResult Notification(EncryptedRequest encrypted) { EncryptedResponse response = null; try { this.Debug(encrypted, "REQUEST"); if (encrypted.ValidSignature(this.GetClientSharedKey(), this.GetClientSignature(), this.GetClientSignatureKey())) { Notification notification = encrypted.Decrypt(this.GetClientSharedKey()); if (notification != null && !string.IsNullOrEmpty(notification.pgs)) { ServiceShared.Models.Database.Results? dbResults = this.dbResults.GetResults(notification.pgs, notification.udid); if (dbResults != null) { if (!string.IsNullOrEmpty(dbResults.DeviceToken) && Service.Notification.Send(dbResults.DeviceToken, dbResults.DeviceType, new Service.Notification.Message(dbResults.Available, dbResults.Status)).Result) { this.dbResults.SetNotified(dbResults.PGS, dbResults.UDID); Log.Trace("notified", dbResults.PGS, dbResults.UDID); } else { this.dbResults.SetNotificationTry(dbResults.PGS, dbResults.UDID); Log.Trace("tried to notificate", dbResults.PGS, dbResults.UDID); } } else { response = new EncryptedResponse("ResponseException", new NotAvailableException(), this.GetClientSharedKey()); } } else { response = new EncryptedResponse("ResponseException", new InvalidClientException(), this.GetClientSharedKey()); } } else { response = new EncryptedResponse("ResponseException", new InvalidClientException(), this.GetClientSharedKey()); } } catch (Exception ex) { Log.Critical(ex, "ServiceOutside.Controllers.ServiceInsideController", "Notify"); } this.Debug(response, "RESPONSE"); return new JsonResult(response); } } }