From 1ef39923f86c9291b99d0bab82032b9a6a08d40f Mon Sep 17 00:00:00 2001 From: alireza995 <88311706+alireza995@users.noreply.github.com> Date: Wed, 30 Nov 2022 08:17:44 +0330 Subject: [PATCH 01/14] refactor(Solution) : Refactor all codes Refactor all codes with: Creating sln file move each class in a new file remove unusable code create some temp changes closes nothing --- Folder.DotSettings | 2 + Kavenegar.Core/Exceptions/ApiException.cs | 27 +- Kavenegar.Core/Exceptions/BaseException.cs | 10 - Kavenegar.Core/Exceptions/HttpException.cs | 17 - .../Exceptions/KavenegarException.cs | 11 + Kavenegar.Core/IKavenegarApi.cs | 277 ++++ Kavenegar.Core/IKavenegarApi2.cs | 88 ++ Kavenegar.Core/Json/JsonArray.cs | 106 +- Kavenegar.Core/Json/JsonBoolean.cs | 31 +- Kavenegar.Core/Json/JsonNullable.cs | 29 +- Kavenegar.Core/Json/JsonNumber.cs | 31 +- Kavenegar.Core/Json/JsonObject.cs | 151 +- Kavenegar.Core/Json/JsonString.cs | 32 +- Kavenegar.Core/Json/Parser.cs | 928 +++++------ Kavenegar.Core/Kavenegar.Core.csproj | 53 +- Kavenegar.Core/KavenegarApi.cs | 1368 +++++++++++------ Kavenegar.Core/KavenegarApi2.cs | 430 ++++++ Kavenegar.Core/Models/AccountConfigResult.cs | 19 +- Kavenegar.Core/Models/AccountInfoResult.cs | 22 +- Kavenegar.Core/Models/CountInboxResult.cs | 13 +- Kavenegar.Core/Models/CountOutboxResult.cs | 11 +- .../Models/CountPostalCodeResult.cs | 11 +- Kavenegar.Core/Models/Enums/MessageStatus.cs | 27 +- Kavenegar.Core/Models/Enums/MessageType.cs | 15 +- Kavenegar.Core/Models/Enums/MetaCode.cs | 42 +- .../Models/Enums/VerifyLookupType.cs | 13 +- Kavenegar.Core/Models/ReceiveResult.cs | 29 +- Kavenegar.Core/Models/SendResult.cs | 35 +- .../Models/StatusLocalMessageIdResult.cs | 16 +- Kavenegar.Core/Models/StatusResult.cs | 14 +- Kavenegar.Core/Result.cs | 7 + Kavenegar.Core/ReturnAccountConfig.cs | 9 + Kavenegar.Core/ReturnAccountInfo.cs | 9 + Kavenegar.Core/ReturnCountInbox.cs | 10 + Kavenegar.Core/ReturnCountOutbox.cs | 10 + Kavenegar.Core/ReturnCountPostalCode.cs | 10 + Kavenegar.Core/ReturnReceive.cs | 10 + Kavenegar.Core/ReturnResult.cs | 7 + Kavenegar.Core/ReturnSend.cs | 10 + Kavenegar.Core/ReturnStatus.cs | 10 + Kavenegar.Core/ReturnStatusLocalMessageId.cs | 10 + Kavenegar.Core/SendMessageRequest.cs | 12 + Kavenegar.Core/Utils/DateHelper.cs | 65 +- Kavenegar.Core/Utils/StringHelper.cs | 18 - Kavenegar.sln | 27 + Kavenegar.sln.DotSettings | 2 + .../Shared.Infrastructure/HttpClientHelper.cs | 24 + Shared/Shared.Infrastructure/JsonUtility.cs | 27 + .../Shared.Infrastructure.csproj | 9 + 49 files changed, 2739 insertions(+), 1405 deletions(-) create mode 100644 Folder.DotSettings delete mode 100644 Kavenegar.Core/Exceptions/BaseException.cs delete mode 100644 Kavenegar.Core/Exceptions/HttpException.cs create mode 100644 Kavenegar.Core/Exceptions/KavenegarException.cs create mode 100644 Kavenegar.Core/IKavenegarApi.cs create mode 100644 Kavenegar.Core/IKavenegarApi2.cs create mode 100644 Kavenegar.Core/KavenegarApi2.cs create mode 100644 Kavenegar.Core/Result.cs create mode 100644 Kavenegar.Core/ReturnAccountConfig.cs create mode 100644 Kavenegar.Core/ReturnAccountInfo.cs create mode 100644 Kavenegar.Core/ReturnCountInbox.cs create mode 100644 Kavenegar.Core/ReturnCountOutbox.cs create mode 100644 Kavenegar.Core/ReturnCountPostalCode.cs create mode 100644 Kavenegar.Core/ReturnReceive.cs create mode 100644 Kavenegar.Core/ReturnResult.cs create mode 100644 Kavenegar.Core/ReturnSend.cs create mode 100644 Kavenegar.Core/ReturnStatus.cs create mode 100644 Kavenegar.Core/ReturnStatusLocalMessageId.cs create mode 100644 Kavenegar.Core/SendMessageRequest.cs delete mode 100644 Kavenegar.Core/Utils/StringHelper.cs create mode 100644 Kavenegar.sln create mode 100644 Kavenegar.sln.DotSettings create mode 100644 Shared/Shared.Infrastructure/HttpClientHelper.cs create mode 100644 Shared/Shared.Infrastructure/JsonUtility.cs create mode 100644 Shared/Shared.Infrastructure/Shared.Infrastructure.csproj diff --git a/Folder.DotSettings b/Folder.DotSettings new file mode 100644 index 0000000..a44ce49 --- /dev/null +++ b/Folder.DotSettings @@ -0,0 +1,2 @@ + + True \ No newline at end of file diff --git a/Kavenegar.Core/Exceptions/ApiException.cs b/Kavenegar.Core/Exceptions/ApiException.cs index 5a0bbc1..4583167 100644 --- a/Kavenegar.Core/Exceptions/ApiException.cs +++ b/Kavenegar.Core/Exceptions/ApiException.cs @@ -1,20 +1,15 @@ using Kavenegar.Core.Models.Enums; -namespace Kavenegar.Core.Exceptions -{ - public class ApiException : KavenegarException - { - readonly MetaCode _result; - public ApiException(string message, int code) - : base(message) - { - _result = (MetaCode)code; - } +namespace Kavenegar.Core.Exceptions; - public MetaCode Code - { - get { return _result; } - } +public class ApiException : KavenegarException +{ + public ApiException( + string message, + int code) : base(message) + { + Code = (MetaCode)code; + } - } -} + public MetaCode Code { get; } +} \ No newline at end of file diff --git a/Kavenegar.Core/Exceptions/BaseException.cs b/Kavenegar.Core/Exceptions/BaseException.cs deleted file mode 100644 index f30b38a..0000000 --- a/Kavenegar.Core/Exceptions/BaseException.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Kavenegar.Core.Exceptions -{ - public class KavenegarException : System.Exception - { - public KavenegarException(string message) - : base(message) - { - } - } -} \ No newline at end of file diff --git a/Kavenegar.Core/Exceptions/HttpException.cs b/Kavenegar.Core/Exceptions/HttpException.cs deleted file mode 100644 index e74fd19..0000000 --- a/Kavenegar.Core/Exceptions/HttpException.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace Kavenegar.Core.Exceptions -{ - public class HttpException : KavenegarException - { - private readonly int _code; - public HttpException(string message, int code) - : base(message) - { - _code = code; - } - - public int Code - { - get { return _code; } - } - } -} \ No newline at end of file diff --git a/Kavenegar.Core/Exceptions/KavenegarException.cs b/Kavenegar.Core/Exceptions/KavenegarException.cs new file mode 100644 index 0000000..49da29e --- /dev/null +++ b/Kavenegar.Core/Exceptions/KavenegarException.cs @@ -0,0 +1,11 @@ +using System; + +namespace Kavenegar.Core.Exceptions; + +public class KavenegarException : Exception +{ + public KavenegarException( + string message) : base(message) + { + } +} \ No newline at end of file diff --git a/Kavenegar.Core/IKavenegarApi.cs b/Kavenegar.Core/IKavenegarApi.cs new file mode 100644 index 0000000..9ce6232 --- /dev/null +++ b/Kavenegar.Core/IKavenegarApi.cs @@ -0,0 +1,277 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Kavenegar.Core.Models; +using Kavenegar.Core.Models.Enums; + +namespace Kavenegar.Core; + +public interface IKavenegarApi +{ + string ApiKey { set; get; } + + Task> Send( + string sender, + List receptor, + string message); + + Task Send( + string sender, + string receptor, + string message); + + Task Send( + string sender, + string receptor, + string message, + MessageType type, + DateTime date); + + Task> Send( + string sender, + List receptor, + string message, + MessageType type, + DateTime date); + + Task Send( + string sender, + string receptor, + string message, + MessageType type, + DateTime date, + string localId); + + Task Send( + string sender, + string receptor, + string message, + string localId); + + Task> Send( + string sender, + List receptors, + string message, + string localId); + + Task> Send( + string sender, + List receptor, + string message, + MessageType type, + DateTime date, + List localIds); + + Task> SendArray( + List senders, + List receptors, + List messages); + + Task> SendArray( + string sender, + List receptors, + List messages, + MessageType type, + DateTime date); + + Task> SendArray( + string sender, + List receptors, + List messages, + MessageType type, + DateTime date, + string localMessageIds); + + Task> SendArray( + string sender, + List receptors, + List messages, + string localMessageId); + + Task> SendArray( + List senders, + List receptors, + List messages, + string localMessageId); + + Task> SendArray( + List senders, + List receptors, + List messages, + List types, + DateTime date, + List localMessageIds); + + Task> Status( + List messageIds); + + Task Status( + string messageId); + + Task> StatusLocalMessageId( + List messageIds); + + Task StatusLocalMessageId( + string messageId); + + Task> Select( + List messageIds); + + Task Select( + string messageId); + + Task> SelectOutbox( + DateTime startDate); + + Task> SelectOutbox( + DateTime startDate, + DateTime endDate); + + Task> SelectOutbox( + DateTime startDate, + DateTime endDate, + string sender); + + Task> LatestOutbox( + long pageSize); + + Task> LatestOutbox( + long pageSize, + string sender); + + Task CountOutbox( + DateTime startDate); + + Task CountOutbox( + DateTime startDate, + DateTime endDate); + + Task CountOutbox( + DateTime startDate, + DateTime endDate, + int status); + + Task> Cancel( + List ids); + + Task Cancel( + string messageId); + + Task> Receive( + string line, + int isRead); + + Task CountInbox( + DateTime startDate, + string lineNumber); + + Task CountInbox( + DateTime startDate, + DateTime endDate, + string lineNumber); + + Task CountInbox( + DateTime startDate, + DateTime endDate, + string lineNumber, + int isRead); + + Task> CountPostalCode( + long postalcode); + + Task> SendByPostalCode( + long postalcode, + string sender, + string message, + long mciStartIndex, + long mciCount, + long mtnStartIndex, + long mtnCount); + + Task> SendByPostalCode( + long postalcode, + string sender, + string message, + long mciStartIndex, + long mciCount, + long mtnStartIndex, + long mtnCount, + DateTime date); + + Task AccountInfo(); + + Task AccountConfig( + string apiLogs, + string dailyReport, + string debugMode, + string defaultSender, + int? minCreditAlarm, + string resendFailed); + + Task VerifyLookup( + string receptor, + string token, + string template); + + Task VerifyLookup( + string receptor, + string token, + string template, + VerifyLookupType type); + + Task VerifyLookup( + string receptor, + string token, + string token2, + string token3, + string template); + + Task VerifyLookup( + string receptor, + string token, + string token2, + string token3, + string token10, + string template); + + Task VerifyLookup( + string receptor, + string token, + string token2, + string token3, + string template, + VerifyLookupType type); + + Task VerifyLookup( + string receptor, + string token, + string token2, + string token3, + string token10, + string template, + VerifyLookupType type); + + Task VerifyLookup( + string receptor, + string token, + string token2, + string token3, + string token10, + string token20, + string template, + VerifyLookupType type); + + Task CallMakeTts( + string message, + string receptor); + + Task> CallMakeTts( + string message, + List receptor); + + Task> CallMakeTts( + string message, + List receptor, + DateTime? date, + List localId); +} \ No newline at end of file diff --git a/Kavenegar.Core/IKavenegarApi2.cs b/Kavenegar.Core/IKavenegarApi2.cs new file mode 100644 index 0000000..ab9d370 --- /dev/null +++ b/Kavenegar.Core/IKavenegarApi2.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Kavenegar.Core.Models; +using Kavenegar.Core.Models.Enums; + +namespace Kavenegar.Core; + +public interface IKavenegarApi2 +{ + string ApiKey { set; get; } + + Task> Send( + SendMessageRequest message, + DateTime? date); + + Task> SendArray( + List messages, + DateTime? date); + + Task Status( + string messageId); + + Task> Status( + List messageIds); + + Task StatusLocalMessageId( + string messageId); + + Task> StatusLocalMessageId( + List messageIds); + + Task Select( + string messageId); + + Task> Select( + List messageIds); + + Task> SelectOutbox( + DateTime startDate, + DateTime? endDate, + string? sender); + + Task> LatestOutbox( + long? pageSize, + string? sender); + + Task CountOutbox( + DateTime startDate, + DateTime? endDate, + int? status); + + Task Cancel( + string messageId); + + Task> Cancel( + List ids); + + Task> Receive( + string line, + int isRead); + + Task CountInbox( + DateTime startDate, + DateTime? endDate, + string? lineNumber, + int? isRead); + + Task AccountInfo(); + + Task AccountConfig( + string apiLogs, + string dailyReport, + string debugMode, + string defaultSender, + int? minCreditAlarm, + string resendFailed); + + Task VerifyLookup( + string receptor, + string template, + string token1, + string? token2, + string? token3, + string? token4, + string? token5, + VerifyLookupType? type); +} \ No newline at end of file diff --git a/Kavenegar.Core/Json/JsonArray.cs b/Kavenegar.Core/Json/JsonArray.cs index ce2d110..f0b88ff 100644 --- a/Kavenegar.Core/Json/JsonArray.cs +++ b/Kavenegar.Core/Json/JsonArray.cs @@ -1,57 +1,53 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; -namespace Kavenegar.Core.Json -{ +namespace Kavenegar.Core.Json; - public class JsonArray : JsonObject - { - public List Array { get; set; } - private List.Enumerator _e; - - public JsonArray() - { - Array = new List(); - } - - public void AddElementToArray(JsonObject arrayElement) - { - Array.Add(arrayElement); - } - - public JsonObject UpCast() - { - JsonObject objectJ = this; - return objectJ; - } - - public void AddList(List lista) - { - Array = lista; - } - - public Boolean NextObject(out JsonObject o) - { - - JsonObject outObject; - _e = Array.GetEnumerator(); - - if (_e.MoveNext()) - { - outObject = _e.Current; - o = outObject; - return true; - } - outObject = new JsonObject(); - o = outObject; - return false; - } - - public int Count - { - get { return Array.Count; } - } - - } - -} +public class JsonArray : JsonObject +{ + private List.Enumerator _e; + + public JsonArray() + { + Array = new List(); + } + + public List Array { get; set; } + + public int Count => Array.Count; + + public void AddElementToArray( + JsonObject arrayElement) + { + Array.Add(arrayElement); + } + + public JsonObject UpCast() + { + JsonObject objectJ = this; + return objectJ; + } + + public void AddList( + List lista) + { + Array = lista; + } + + public bool NextObject( + out JsonObject o) + { + JsonObject outObject; + _e = Array.GetEnumerator(); + + if (_e.MoveNext()) + { + outObject = _e.Current; + o = outObject; + return true; + } + + outObject = new JsonObject(); + o = outObject; + return false; + } +} \ No newline at end of file diff --git a/Kavenegar.Core/Json/JsonBoolean.cs b/Kavenegar.Core/Json/JsonBoolean.cs index 3708b6f..d944ef2 100644 --- a/Kavenegar.Core/Json/JsonBoolean.cs +++ b/Kavenegar.Core/Json/JsonBoolean.cs @@ -1,21 +1,18 @@ -using System; +namespace Kavenegar.Core.Json; -namespace Kavenegar.Core.Json +public class JsonBoolean : JsonObject { + public JsonBoolean( + bool booleanValue) + { + BooleanValue = booleanValue; + } - public class JsonBoolean : JsonObject - { - public Boolean BooleanValue { get; set; } + public bool BooleanValue { get; set; } - public JsonBoolean(Boolean booleanValue) - { - BooleanValue = booleanValue; - } - - public JsonObject UpCast() - { - JsonObject objectJ = this; - return objectJ; - } - } -} + public JsonObject UpCast() + { + JsonObject objectJ = this; + return objectJ; + } +} \ No newline at end of file diff --git a/Kavenegar.Core/Json/JsonNullable.cs b/Kavenegar.Core/Json/JsonNullable.cs index f3a7b2f..6d198d4 100644 --- a/Kavenegar.Core/Json/JsonNullable.cs +++ b/Kavenegar.Core/Json/JsonNullable.cs @@ -1,20 +1,17 @@ -using System; +namespace Kavenegar.Core.Json; -namespace Kavenegar.Core.Json +public class JsonNullable : JsonObject { - public class JsonNullable : JsonObject - { - public String Nullable { get; set; } + public JsonNullable() + { + Nullable = "Null"; + } - public JsonNullable() - { - Nullable = "Null"; - } + public string Nullable { get; set; } - public JsonObject UpCast() - { - JsonObject objectJ = this; - return objectJ; - } - } -} + public JsonObject UpCast() + { + JsonObject objectJ = this; + return objectJ; + } +} \ No newline at end of file diff --git a/Kavenegar.Core/Json/JsonNumber.cs b/Kavenegar.Core/Json/JsonNumber.cs index 69b0de6..f4dee4e 100644 --- a/Kavenegar.Core/Json/JsonNumber.cs +++ b/Kavenegar.Core/Json/JsonNumber.cs @@ -1,21 +1,18 @@ -using Kavenegar.Core.Json; +namespace Kavenegar.Core.Json; -namespace Kavenegar.Core.Json +public class JsonNumber : JsonObject { - public class JsonNumber : JsonObject - { - public float Number { get; set; } + public JsonNumber( + float number) + { + Number = number; + } - public JsonNumber(float number) - { - Number = number; - } + public float Number { get; set; } - public JsonObject UpCast() - { - JsonObject objectJ = this; - return objectJ; - } - } - -} + public JsonObject UpCast() + { + JsonObject objectJ = this; + return objectJ; + } +} \ No newline at end of file diff --git a/Kavenegar.Core/Json/JsonObject.cs b/Kavenegar.Core/Json/JsonObject.cs index 0b79998..224df99 100644 --- a/Kavenegar.Core/Json/JsonObject.cs +++ b/Kavenegar.Core/Json/JsonObject.cs @@ -1,100 +1,83 @@ -using System; using System.Collections.Generic; -namespace Kavenegar.Core.Json +namespace Kavenegar.Core.Json; + +/// +/// JsonObject is the base class. +/// JsonString,JsonNumber,JsonBoolean,JsonNullable and JsonArray inherits from JsonObject. +/// A JsonArray object may contain objects of the base class +/// +public class JsonObject { - /// - /// JsonObject is the base class. - /// JsonString,JsonNumber,JsonBoolean,JsonNullable and JsonArray inherits from JsonObject. - /// A JsonArray object may contain objects of the base class - /// + public Dictionary Values; - public class JsonObject - { - public Dictionary Values; + public JsonObject() + { + Values = new Dictionary(); + } - public JsonObject() - { - Values = new Dictionary(); - } + public void AddJsonValue( + string textTag, + JsonObject newObject) + { + if (!Values.ContainsKey(textTag)) Values.Add(textTag, newObject); + } - public void AddJsonValue(String textTag, JsonObject newObject) - { - if (!Values.ContainsKey(textTag)) - { - Values.Add(textTag, newObject); - } - } + public JsonObject GetObject( + string key) + { + var current = Values[key]; + return current; + } - public JsonObject GetObject(String key) - { - JsonObject current = Values[key]; - return current; - } + public int ElementsOfDictionary() + { + return Values.Count; + } - public int ElementsOfDictionary() - { - return Values.Count; - } + public bool IsJsonString() + { + if (this is JsonString) return true; + return false; + } - public Boolean IsJsonString() - { - if (this is JsonString) - { - return true; - } - return false; - } + public bool IsJsonNumber() + { + if (this is JsonNumber) return true; + return false; + } - public Boolean IsJsonNumber() - { - if (this is JsonNumber) - { - return true; - } - return false; - } + public bool IsJsonBoolean() + { + if (this is JsonBoolean) return true; + return false; + } - public Boolean IsJsonBoolean() - { - if (this is JsonBoolean) - { - return true; - } - return false; - } + public bool IsJsonNullable() + { + if (this is JsonNullable) return true; + return false; + } - public Boolean IsJsonNullable() - { - if (this is JsonNullable) - { - return true; - } - return false; - } + public bool IsJsonArray() + { + if (this is JsonArray) return true; + return false; + } - public Boolean IsJsonArray() - { - if (this is JsonArray) - { - return true; - } - return false; - } + public JsonString GetAsString() + { + return (JsonString)this; + } - public JsonString GetAsString() - { - return (JsonString)this; - } - public JsonNumber GetAsNumber() - { - return (JsonNumber)this; - } - public JsonArray GetAsArray() - { - return (JsonArray)this; - } - } -} + public JsonNumber GetAsNumber() + { + return (JsonNumber)this; + } + public JsonArray GetAsArray() + { + return (JsonArray)this; + } +} \ No newline at end of file diff --git a/Kavenegar.Core/Json/JsonString.cs b/Kavenegar.Core/Json/JsonString.cs index b2031d2..cdbb011 100644 --- a/Kavenegar.Core/Json/JsonString.cs +++ b/Kavenegar.Core/Json/JsonString.cs @@ -1,22 +1,18 @@ -using System; +namespace Kavenegar.Core.Json; -namespace Kavenegar.Core.Json +public class JsonString : JsonObject { - public class JsonString : JsonObject - { - public String Text { get; set; } + public JsonString( + string text) + { + Text = text; + } - public JsonString(String text) - { - Text = text; - } + public string Text { get; set; } - public JsonObject UpCast() - { - JsonObject objectJ = this; - return objectJ; - } - - - } -} + public JsonObject UpCast() + { + JsonObject objectJ = this; + return objectJ; + } +} \ No newline at end of file diff --git a/Kavenegar.Core/Json/Parser.cs b/Kavenegar.Core/Json/Parser.cs index cb61562..604b6f7 100644 --- a/Kavenegar.Core/Json/Parser.cs +++ b/Kavenegar.Core/Json/Parser.cs @@ -1,455 +1,481 @@ -// SharpYourJson -// (c) 2013 Felipe Herranz -// SharpYourJson may be freely distributed under the MIT license. - using System; using System.Collections.Generic; -namespace Kavenegar.Core.Json -{ - /// - /// Contains the façade-style class to perform Json operations - /// - - public class Parser - { - - public JsonObject DocumentJson; // The deserialized Json Object will be stored here - - private const char ObjectBegin = '{'; - private const char ObjectEnd = '}'; - private const char ArrayBegin = '['; - private const char ArrayEnd = ']'; - private const char DoubleQuotes = '"'; - private const char DoublePoint = ':'; - private const char Comma = ','; - private const char BackSlash = '\u005C'; - private const string NullValue = "null"; - private const string TrueValue = "true"; - private const string FalseValue = "false"; - - /// - /// Deserialize a JSON document. This method does not perform a syntax checking so It assumes a valid Json input - /// - /// - /// - /// A string which contains a valid Json array or object - /// - public JsonObject Parse(String json) - { - if (json[0] == ArrayBegin) - { - json = json.Substring(1, json.Length - 2); - JsonArray arrayJson = SerializeArray(json); - JsonObject o = arrayJson; - return o; - - } - else if (json[0] == ObjectBegin) - { - - return SerializeObject(json); - } - return null; - } - /// - /// This method performs deserialization of an object(except array) - /// - /// - /// JsonObject object as a deserialized JSON object - /// - /// - /// A string which contains a valid Json object - /// - private JsonObject SerializeObject(String json) - { - json = json.Replace(@"\", ""); - JsonObject document = new JsonObject(); - int n = 1; - int lengthJson = json.Length; - String keyString = ""; - - while (n <= lengthJson - 1) - { - if (json[n] == DoubleQuotes && json[n - 1] != DoublePoint) // (key-value Pair) key Name - { - int secondDoubleQuotes = FindNextQuote(json, n + 1); - keyString = json.Substring(n + 1, (secondDoubleQuotes - (n + 1))); - n = secondDoubleQuotes + 1; - - } - else if (json[n] == DoubleQuotes && json[n - 1] == DoublePoint) // (key-value Pair) value Name (if string) - { - if (json[n + 1] != DoubleQuotes) - { - int secondDoublesQuotes = FindNextQuote(json, n + 1); - String text = json.Substring(n + 1, (secondDoublesQuotes - (n + 1))); - JsonString stringValue = new JsonString(text); - JsonObject o = stringValue; - document.AddJsonValue(keyString, o); - n = secondDoublesQuotes + 1; - } - else - { - JsonObject o = new JsonString(""); - document.AddJsonValue(keyString, o); - } - - } - else if (json[n] == '-' || json[n] == '0' || json[n] == '1' || json[n] == '2' || json[n] == '3' || - json[n] == '4' || json[n] == '5' || json[n] == '6' || json[n] == '7' || json[n] == '8' || - json[n] == '9') // (key-value Pair) value (if number) - { - char[] arrayEndings = { ObjectEnd, Comma }; - int nextComma = json.IndexOfAny(arrayEndings, n); - String stringNumber = json.Substring(n, nextComma - n); - Double valueNumber = Convert.ToDouble(stringNumber); - float floatNumber = (float)valueNumber; - JsonNumber number = new JsonNumber(floatNumber); - JsonObject o = number; - document.AddJsonValue(keyString, o); - n = nextComma + 1; - - } - else if (json[n] == ArrayBegin) //(key-value Pair) value (if array) - { - if (json[n + 1] != ArrayEnd) - { - String subJson = json.Substring(n, json.Length - n); - int arrayClose = CloseBracketArray(subJson); - String arrayUnknown = json.Substring(n + 1, arrayClose - 2); - JsonArray arrayObjects = SerializeArray(arrayUnknown); - JsonObject o = arrayObjects; - document.AddJsonValue(keyString, o); - n = n + arrayClose; - } - else - { - if (!string.IsNullOrEmpty(keyString)) - { - JsonArray arrayTempEmpty = new JsonArray { Array = null }; - JsonObject emptyArray = arrayTempEmpty; - document.AddJsonValue(keyString, emptyArray); - keyString = ""; - - } - else - { - n++; - } - } - - } - else if (json[n] == ObjectBegin) // (key-value Pair) value (if object) - { - if (json[n + 1] != ObjectEnd) - { - String subJson = json.Substring(n, json.Length - n); - int objectClose = CloseBracketObject(subJson); - String objectUnknown = json.Substring(n, objectClose); - var o = SerializeObject(objectUnknown); - document.AddJsonValue(keyString, o); - n = n + objectClose + 1; - } - else - { - JsonObject o = new JsonObject { Values = null }; - document.AddJsonValue(keyString, o); - } - - } - else if (String.Compare(SafeSubString(json, n, 4), NullValue, StringComparison.Ordinal) == 0) // (key-value Pair) value (if NULL) - { - JsonObject o = new JsonNullable(); - document.AddJsonValue(keyString, o); - n = n + 5; - } - else if (String.Compare(SafeSubString(json, n, 4), TrueValue, StringComparison.Ordinal) == 0) // (key-value Pair) value (if TRUE) - { - JsonObject o = new JsonBoolean(true); - document.AddJsonValue(keyString, o); - n = n + 5; - } - else if (String.Compare(SafeSubString(json, n, 5), FalseValue, StringComparison.Ordinal) == 0) // (key-value Pair) value (if FALSE) - { - JsonObject o = new JsonBoolean(false); - document.AddJsonValue(keyString, o); - n = n + 6; - } - else - { - n++; - } - - } - - return document; - } - - /// - /// Search where is the ending of an object - /// - /// - /// the index of the '}' which closes an object - /// - /// - /// A valid json string ({........) - /// - - private int CloseBracketObject(String json) - { - int countObjectBegin = 0; - int countObjectEnd = 0; - int n = 0; - - do - { - if (json[n] == ObjectBegin) - { - countObjectBegin++; - - } - else if (json[n] == ObjectEnd) - { - countObjectEnd++; - } - - n++; - - } while (countObjectBegin != countObjectEnd); - - return n; - } - - /// - /// Search where is the ending of an array - /// - /// - /// he index of the ']' which closes an object - /// - /// - /// A valid Json string ([.....) - /// - - private int CloseBracketArray(String json) - { - int countArrayBegin = 0; - int countArrayEnd = 0; - int n = 0; - - do - { - if (json[n] == ArrayBegin) - { - countArrayBegin++; - - } - else if (json[n] == ArrayEnd) - { - countArrayEnd++; - } - - n++; - - } while (countArrayBegin != countArrayEnd); - - return n; - } - - /// - /// Deserialize a Json Array into an object JsonArray - /// - /// - /// JsonArray object as a deserialized JSON array - /// - /// - /// valid JSON array except the brackets - /// - - private JsonArray SerializeArray(String array) - { - JsonArray arrayObject = new JsonArray(); - var elements = SplitElements(array); - - foreach (String item in elements) - { - - if (item[0] == DoubleQuotes) - { - String withoutQuotes = item.Trim(DoubleQuotes); - JsonObject o = new JsonString(withoutQuotes); - arrayObject.AddElementToArray(o); - - } - else if (item[0] == ObjectBegin) - { - JsonObject o = SerializeObject(item); - arrayObject.AddElementToArray(o); - - } - else if (item[0] == ArrayBegin) - { - String itemArray = item.Substring(1, item.Length - 2); - JsonArray secondaryArray = SerializeArray(itemArray); - JsonObject o = secondaryArray; - arrayObject.AddElementToArray(o); - - } - else if (item[0] == '-' || item[0] == '0' || item[0] == '1' || item[0] == '2' || item[0] == '3' || - item[0] == '4' || item[0] == '5' || item[0] == '6' || item[0] == '7' || item[0] == '8' || item[0] == '9') - { - Double doubleValue = Convert.ToDouble(item); - float floatValue = (float)doubleValue; - JsonObject o = new JsonNumber(floatValue); - arrayObject.AddElementToArray(o); - } - else if (String.Compare(SafeSubString(item, 0, 4), TrueValue, StringComparison.Ordinal) == 0) - { - JsonObject o = new JsonBoolean(true); - arrayObject.AddElementToArray(o); - } - else if (String.Compare(SafeSubString(item, 0, 5), FalseValue, StringComparison.Ordinal) == 0) - { - JsonObject o = new JsonBoolean(false); - arrayObject.AddElementToArray(o); - } - else if (String.Compare(SafeSubString(item, 0, 4), NullValue, StringComparison.Ordinal) == 0) - { - JsonObject o = new JsonNullable(); - arrayObject.AddElementToArray(o); - } - - } - - return arrayObject; - - } - /// - /// Just a safe subString operation - /// - /// - /// A subString of the string input parameter text - /// - /// - /// A string - /// - /// - /// index of starting - /// - /// - /// Length of the subString - /// - - private String SafeSubString(String text, int start, int length) - { - var safeString = start + length < text.Length ? text.Substring(start, length) : text.Substring(start, text.Length - start); - - return safeString; - } - - /// - /// Finds the next '"' to close a String field - /// - /// - /// The next ' " ' - /// - /// - /// A valid JSON string - /// - /// - /// Index of starting - /// - - private int FindNextQuote(String text, int index) - { - int nextQuote = text.IndexOf(DoubleQuotes, index); - while (text[nextQuote - 1] == BackSlash) - { - nextQuote = text.IndexOf(DoubleQuotes, nextQuote + 1); - } - - return nextQuote; - - } - - /// - /// Splits the elements of an Array - /// - /// - /// The elements in an array of Strings - /// - /// - /// - /// - - private String[] SplitElements(String arrayText) - { - int n = 0; - int doubleQuotesCounter = 0; - int objectBeginCounter = 0; - int objectEndCounter = 0; - int arrayBeginCounter = 0; - int arrayEndCounter = 0; - int previousCommaIndex = 0; - Boolean oneElement = true; - List textSplit = new List(); - - while (n <= arrayText.Length - 1) - { - if (arrayText[n] == DoubleQuotes && arrayText[n - 1] != BackSlash) - { - doubleQuotesCounter++; - n++; - } - else if (arrayText[n] == ObjectBegin) - { - objectBeginCounter++; - n++; - - } - else if (arrayText[n] == ObjectEnd) - { - objectEndCounter++; - n++; - - } - else if (arrayText[n] == ArrayBegin) - { - arrayBeginCounter++; - n++; - - } - else if (arrayText[n] == ArrayEnd) - { - arrayEndCounter++; - n++; - - } - else if (arrayText[n] == Comma && doubleQuotesCounter % 2 == 0 && objectBeginCounter == objectEndCounter - && arrayBeginCounter == arrayEndCounter) - { - textSplit.Add(arrayText.Substring(previousCommaIndex, (n - previousCommaIndex))); - previousCommaIndex = n + 1; - n++; - oneElement = false; - - } - else - { - n++; - } - } - - textSplit.Add(oneElement - ? arrayText - : arrayText.Substring(previousCommaIndex, (arrayText.Length) - previousCommaIndex)); - - String[] textSplitArray = textSplit.ToArray(); - return textSplitArray; - } - - } -} - - +namespace Kavenegar.Core.Json; +/// +/// Contains the façade-style class to perform Json operations +/// +public class Parser +{ + private const char ObjectBegin = '{'; + private const char ObjectEnd = '}'; + private const char ArrayBegin = '['; + private const char ArrayEnd = ']'; + private const char DoubleQuotes = '"'; + private const char DoublePoint = ':'; + private const char Comma = ','; + private const char BackSlash = '\u005C'; + private const string NullValue = "null"; + private const string TrueValue = "true"; + private const string FalseValue = "false"; + + public JsonObject DocumentJson; + + /// + /// Deserialize a JSON document. This method does not perform a syntax checking so It assumes a valid Json input + /// + /// + /// A string which contains a valid Json array or object + /// + public JsonObject Parse( + string json) + { + if (json[0] == ArrayBegin) + { + json = json.Substring(1, json.Length - 2); + var arrayJson = SerializeArray(json); + JsonObject o = arrayJson; + return o; + } + + if (json[0] == ObjectBegin) return SerializeObject(json); + + return null; + } + + /// + /// This method performs deserialization of an object(except array) + /// + /// + /// JsonObject object as a deserialized JSON object + /// + /// + /// A string which contains a valid Json object + /// + private JsonObject SerializeObject( + string json) + { + json = json.Replace(@"\", ""); + var document = new JsonObject(); + var n = 1; + var lengthJson = json.Length; + var keyString = ""; + + while (n <= lengthJson - 1) + if (json[n] == DoubleQuotes && + json[n - 1] != DoublePoint) + { + var secondDoubleQuotes = FindNextQuote(json, n + 1); + keyString = json.Substring(n + 1, secondDoubleQuotes - (n + 1)); + n = secondDoubleQuotes + 1; + } + else if (json[n] == DoubleQuotes && + json[n - 1] == DoublePoint) + { + if (json[n + 1] != DoubleQuotes) + { + var secondDoublesQuotes = FindNextQuote(json, n + 1); + var text = json.Substring(n + 1, secondDoublesQuotes - (n + 1)); + var stringValue = new JsonString(text); + JsonObject o = stringValue; + document.AddJsonValue(keyString, o); + n = secondDoublesQuotes + 1; + } + else + { + JsonObject o = new JsonString(""); + document.AddJsonValue(keyString, o); + } + } + else if (json[n] == '-' || + json[n] == '0' || + json[n] == '1' || + json[n] == '2' || + json[n] == '3' || + json[n] == '4' || + json[n] == '5' || + json[n] == '6' || + json[n] == '7' || + json[n] == '8' || + json[n] == '9') + { + char[] arrayEndings = + { + ObjectEnd, + Comma + }; + var nextComma = json.IndexOfAny(arrayEndings, n); + var stringNumber = json.Substring(n, nextComma - n); + var valueNumber = Convert.ToDouble(stringNumber); + var floatNumber = (float)valueNumber; + var number = new JsonNumber(floatNumber); + JsonObject o = number; + document.AddJsonValue(keyString, o); + n = nextComma + 1; + } + else if (json[n] == ArrayBegin) + { + if (json[n + 1] != ArrayEnd) + { + var subJson = json.Substring(n, json.Length - n); + var arrayClose = CloseBracketArray(subJson); + var arrayUnknown = json.Substring(n + 1, arrayClose - 2); + var arrayObjects = SerializeArray(arrayUnknown); + JsonObject o = arrayObjects; + document.AddJsonValue(keyString, o); + n = n + arrayClose; + } + else + { + if (!string.IsNullOrEmpty(keyString)) + { + var arrayTempEmpty = new JsonArray + { + Array = null + }; + JsonObject emptyArray = arrayTempEmpty; + document.AddJsonValue(keyString, emptyArray); + keyString = ""; + } + else + { + n++; + } + } + } + else if (json[n] == ObjectBegin) + { + if (json[n + 1] != ObjectEnd) + { + var subJson = json.Substring(n, json.Length - n); + var objectClose = CloseBracketObject(subJson); + var objectUnknown = json.Substring(n, objectClose); + var o = SerializeObject(objectUnknown); + document.AddJsonValue(keyString, o); + n = n + objectClose + 1; + } + else + { + var o = new JsonObject + { + Values = null + }; + document.AddJsonValue(keyString, o); + } + } + else if (string.Compare( + SafeSubString( + json, + n, + 4), + NullValue, + StringComparison.Ordinal) == + 0) + { + JsonObject o = new JsonNullable(); + document.AddJsonValue(keyString, o); + n = n + 5; + } + else if (string.Compare( + SafeSubString( + json, + n, + 4), + TrueValue, + StringComparison.Ordinal) == + 0) + { + JsonObject o = new JsonBoolean(true); + document.AddJsonValue(keyString, o); + n = n + 5; + } + else if (string.Compare( + SafeSubString( + json, + n, + 5), + FalseValue, + StringComparison.Ordinal) == + 0) + { + JsonObject o = new JsonBoolean(false); + document.AddJsonValue(keyString, o); + n = n + 6; + } + else + { + n++; + } + + return document; + } + + /// + /// Search where is the ending of an object + /// + /// + /// the index of the '}' which closes an object + /// + /// + /// A valid json string ({........) + /// + private int CloseBracketObject( + string json) + { + var countObjectBegin = 0; + var countObjectEnd = 0; + var n = 0; + + do + { + if (json[n] == ObjectBegin) + countObjectBegin++; + else if (json[n] == ObjectEnd) countObjectEnd++; + + n++; + } + while (countObjectBegin != countObjectEnd); + + return n; + } + + /// + /// Search where is the ending of an array + /// + /// + /// he index of the ']' which closes an object + /// + /// + /// A valid Json string ([.....) + /// + private int CloseBracketArray( + string json) + { + var countArrayBegin = 0; + var countArrayEnd = 0; + var n = 0; + + do + { + if (json[n] == ArrayBegin) + countArrayBegin++; + else if (json[n] == ArrayEnd) countArrayEnd++; + + n++; + } + while (countArrayBegin != countArrayEnd); + + return n; + } + + /// + /// Deserialize a Json Array into an object JsonArray + /// + /// + /// JsonArray object as a deserialized JSON array + /// + /// + /// valid JSON array except the brackets + /// + private JsonArray SerializeArray( + string array) + { + var arrayObject = new JsonArray(); + var elements = SplitElements(array); + + foreach (var item in elements) + if (item[0] == DoubleQuotes) + { + var withoutQuotes = item.Trim(DoubleQuotes); + JsonObject o = new JsonString(withoutQuotes); + arrayObject.AddElementToArray(o); + } + else if (item[0] == ObjectBegin) + { + var o = SerializeObject(item); + arrayObject.AddElementToArray(o); + } + else if (item[0] == ArrayBegin) + { + var itemArray = item.Substring(1, item.Length - 2); + var secondaryArray = SerializeArray(itemArray); + JsonObject o = secondaryArray; + arrayObject.AddElementToArray(o); + } + else if (item[0] == '-' || + item[0] == '0' || + item[0] == '1' || + item[0] == '2' || + item[0] == '3' || + item[0] == '4' || + item[0] == '5' || + item[0] == '6' || + item[0] == '7' || + item[0] == '8' || + item[0] == '9') + { + var doubleValue = Convert.ToDouble(item); + var floatValue = (float)doubleValue; + JsonObject o = new JsonNumber(floatValue); + arrayObject.AddElementToArray(o); + } + else if (string.Compare( + SafeSubString( + item, + 0, + 4), + TrueValue, + StringComparison.Ordinal) == + 0) + { + JsonObject o = new JsonBoolean(true); + arrayObject.AddElementToArray(o); + } + else if (string.Compare( + SafeSubString( + item, + 0, + 5), + FalseValue, + StringComparison.Ordinal) == + 0) + { + JsonObject o = new JsonBoolean(false); + arrayObject.AddElementToArray(o); + } + else if (string.Compare( + SafeSubString( + item, + 0, + 4), + NullValue, + StringComparison.Ordinal) == + 0) + { + JsonObject o = new JsonNullable(); + arrayObject.AddElementToArray(o); + } + + return arrayObject; + } + + /// + /// Just a safe subString operation + /// + /// + /// A subString of the string input parameter text + /// + /// + /// A string + /// + /// + /// index of starting + /// + /// + /// Length of the subString + /// + private string SafeSubString( + string text, + int start, + int length) + { + var safeString = start + length < text.Length ? + text.Substring(start, length) : + text.Substring(start, text.Length - start); + + return safeString; + } + + /// + /// Finds the next '"' to close a String field + /// + /// + /// The next ' " ' + /// + /// + /// A valid JSON string + /// + /// + /// Index of starting + /// + private int FindNextQuote( + string text, + int index) + { + var nextQuote = text.IndexOf(DoubleQuotes, index); + while (text[nextQuote - 1] == BackSlash) nextQuote = text.IndexOf(DoubleQuotes, nextQuote + 1); + + return nextQuote; + } + + /// + /// Splits the elements of an Array + /// + /// + /// The elements in an array of Strings + /// + /// + /// + private string[] SplitElements( + string arrayText) + { + var n = 0; + var doubleQuotesCounter = 0; + var objectBeginCounter = 0; + var objectEndCounter = 0; + var arrayBeginCounter = 0; + var arrayEndCounter = 0; + var previousCommaIndex = 0; + var oneElement = true; + var textSplit = new List(); + + while (n <= arrayText.Length - 1) + if (arrayText[n] == DoubleQuotes && + arrayText[n - 1] != BackSlash) + { + doubleQuotesCounter++; + n++; + } + else if (arrayText[n] == ObjectBegin) + { + objectBeginCounter++; + n++; + } + else if (arrayText[n] == ObjectEnd) + { + objectEndCounter++; + n++; + } + else if (arrayText[n] == ArrayBegin) + { + arrayBeginCounter++; + n++; + } + else if (arrayText[n] == ArrayEnd) + { + arrayEndCounter++; + n++; + } + else if (arrayText[n] == Comma && + doubleQuotesCounter % 2 == 0 && + objectBeginCounter == objectEndCounter && + arrayBeginCounter == arrayEndCounter) + { + textSplit.Add(arrayText.Substring(previousCommaIndex, n - previousCommaIndex)); + previousCommaIndex = n + 1; + n++; + oneElement = false; + } + else + { + n++; + } + + textSplit.Add( + oneElement ? arrayText : arrayText.Substring(previousCommaIndex, arrayText.Length - previousCommaIndex)); + + var textSplitArray = textSplit.ToArray(); + return textSplitArray; + } +} \ No newline at end of file diff --git a/Kavenegar.Core/Kavenegar.Core.csproj b/Kavenegar.Core/Kavenegar.Core.csproj index d29e2a9..752fb60 100644 --- a/Kavenegar.Core/Kavenegar.Core.csproj +++ b/Kavenegar.Core/Kavenegar.Core.csproj @@ -1,33 +1,34 @@ - - 1.0.5 - - netstandard1.2;netstandard1.3;netstandard1.4;netstandard1.5;netstandard1.6;netstandard2.0; - A cross-platform library for the kavenegar sms provider; written in C# - Kavenegar.Core - Kavenegar.Core - Kavenegar.Core - - KavenegarDotNetCore - Kavenegar Core kavenegar.Core kavenegarCore Sms - - https://github.com/kavenegar/Kavenegar.Core + + 1.0.5 - Library - true - true - HadiEskandari Ardavan HosseinRezaei Mberneti MohammadAmirriazi - git - https://github.com/kavenegar/Kavenegar.Core - Kavenegar - - true + net6.0;net6.0-windows;netstandard1.2;netstandard1.3;netstandard1.4;netstandard1.5;netstandard1.6;netstandard2.0 + A cross-platform library for the kavenegar sms provider; written in C# + Kavenegar.Core + Kavenegar.Core - + KavenegarDotNetCore + Kavenegar Core kavenegar.Core kavenegarCore Sms + + https://github.com/kavenegar/Kavenegar.Core - - - + Library + true + true + HadiEskandari Ardavan HosseinRezaei Mberneti MohammadAmirriazi + git + https://github.com/kavenegar/Kavenegar.Core + Kavenegar + + true + 11 + enable + + + + + + diff --git a/Kavenegar.Core/KavenegarApi.cs b/Kavenegar.Core/KavenegarApi.cs index abadf94..0f76bbf 100644 --- a/Kavenegar.Core/KavenegarApi.cs +++ b/Kavenegar.Core/KavenegarApi.cs @@ -1,619 +1,1009 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; using System.Net; -using System.Text; +using System.Net.Http; +using System.Threading.Tasks; using Kavenegar.Core.Exceptions; using Kavenegar.Core.Models; using Kavenegar.Core.Models.Enums; using Kavenegar.Core.Utils; -using System.Net.Http; using Newtonsoft.Json; -using System.Threading.Tasks; -namespace Kavenegar +namespace Kavenegar.Core; + +public class KavenegarApi : IKavenegarApi { - internal class ReturnResult - { - public Result @Return { get; set; } - public object entries { get; set; } - } + private const string ApiPath = "{0}/{1}.{2}"; + private const string BaseUrl = "http://api.kavenegar.com/v1"; + private static HttpClient _client = null!; - internal class Result + public KavenegarApi( + string apikey) { - public int status { get; set; } - public string message { get; set; } + ApiKey = apikey; + + _client = new HttpClient + { + BaseAddress = new Uri($"{BaseUrl}/{ApiKey}/") + }; } - internal class ReturnSend + public string ApiKey { set; get; } + + private string GetApiPath( + string @base, + string method, + string output) { - public Result @Return { get; set; } - public List entries { get; set; } + return string.Format( + ApiPath, + @base, + method, + output); } - internal class ReturnStatus + private async Task Execute( + string path, + Dictionary @params) { - public Result result { get; set; } - public List entries { get; set; } + var nvc = @params?.Select(x => new KeyValuePair(x.Key, x.Value?.ToString())); + + var postdata = new FormUrlEncodedContent(nvc); + + var response = await _client.PostAsync(path, postdata); + var responseBody = await response.Content.ReadAsStringAsync(); + + var result = JsonConvert.DeserializeObject(responseBody); + + if (response.StatusCode != HttpStatusCode.OK) + throw new ApiException(result.Return.message, result.Return.status); + + return responseBody; } - internal class ReturnStatusLocalMessageId + public async Task> Send( + string sender, + List receptor, + string message) { - public Result result { get; set; } - public List entries { get; set; } + return await Send( + sender, + receptor, + message, + MessageType.MobileMemory, + DateTime.MinValue); } - internal class ReturnReceive + public async Task Send( + string sender, + string receptor, + string message) { - public Result result { get; set; } - public List entries { get; set; } + return await Send( + sender, + receptor, + message, + MessageType.MobileMemory, + DateTime.MinValue); } - internal class ReturnCountOutbox + public async Task Send( + string sender, + string receptor, + string message, + MessageType type, + DateTime date) { - public Result result { get; set; } - public List entries { get; set; } + var receptors = new List + { + receptor + }; + return (await Send( + sender, + receptors, + message, + type, + date))[0]; } - internal class ReturnCountInbox + public async Task> Send( + string sender, + List receptor, + string message, + MessageType type, + DateTime date) { - public Result result { get; set; } - public List entries { get; set; } - + return await Send( + sender, + receptor, + message, + type, + date, + null); } - internal class ReturnCountPostalCode + public async Task Send( + string sender, + string receptor, + string message, + MessageType type, + DateTime date, + string localId) { - public Result result { get; set; } - public List entries { get; set; } + var receptors = new List + { + receptor + }; + var localIds = new List + { + localId + }; + return (await Send( + sender, + receptors, + message, + type, + date, + localIds))[0]; } - internal class ReturnAccountInfo + public async Task Send( + string sender, + string receptor, + string message, + string localId) { - public Result result { get; set; } - public AccountInfoResult entries { get; set; } + return await Send( + sender, + receptor, + message, + MessageType.MobileMemory, + DateTime.MinValue, + localId); } - internal class ReturnAccountConfig + public async Task> Send( + string sender, + List receptors, + string message, + string localId) { - public Result result { get; set; } - public AccountConfigResult entries { get; set; } + var localIds = new List(); + for (var i = 0; i <= receptors.Count - 1; i++) localIds.Add(localId); + return await Send( + sender, + receptors, + message, + MessageType.MobileMemory, + DateTime.MinValue, + localIds); } - public class KavenegarApi + public async Task> Send( + string sender, + List receptor, + string message, + MessageType type, + DateTime date, + List localIds) { - private string _apikey; - private static HttpClient _client; - private int _returnCode = 200; - private string _returnMessage = ""; - private const string Apipath = "{0}/{1}.{2}"; - private const string BaseUrl = "http://api.kavenegar.com/v1"; - public KavenegarApi(string apikey) + var path = GetApiPath( + "sms", + "send", + "json"); + var param = new Dictionary { - _apikey = apikey; - - _client = new HttpClient { - BaseAddress = new Uri($"{BaseUrl}/{_apikey}/") - }; - - } - - public string ApiKey - { - set => _apikey = value; - get => _apikey; - } + "sender", WebUtility.HtmlEncode(sender) + }, + { + "receptor", WebUtility.HtmlEncode(string.Join(",", receptor)) + }, + { + "message", message + }, + { + "type", (int)type + }, + { + "date", date == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(date) + } + }; + if (localIds != null && + localIds.Count > 0) + param.Add("localId", string.Join(",", localIds)); + var responseBody = await Execute(path, param); + var l = JsonConvert.DeserializeObject(responseBody); + return l.entries; + } - public int ReturnCode - { - get { return _returnCode; } + public async Task> SendArray( + List senders, + List receptors, + List messages) + { + var types = new List(); + for (var i = 0; i <= senders.Count - 1; i++) types.Add(MessageType.MobileMemory); + return await SendArray( + senders, + receptors, + messages, + types, + DateTime.MinValue, + null); + } - } + public async Task> SendArray( + string sender, + List receptors, + List messages, + MessageType type, + DateTime date) + { + var senders = new List(); + for (var i = 0; i < receptors.Count; i++) senders.Add(sender); + var types = new List(); + for (var i = 0; i <= senders.Count - 1; i++) types.Add(MessageType.MobileMemory); + return await SendArray( + senders, + receptors, + messages, + types, + date, + null); + } - public string ReturnMessage - { - get { return _returnMessage; } + public async Task> SendArray( + string sender, + List receptors, + List messages, + MessageType type, + DateTime date, + string localMessageIds) + { + var senders = new List(); + for (var i = 0; i < receptors.Count; i++) senders.Add(sender); + var types = new List(); + for (var i = 0; i <= senders.Count - 1; i++) types.Add(MessageType.MobileMemory); + return await SendArray( + senders, + receptors, + messages, + types, + date, + new List + { + localMessageIds + }); + } - } + public async Task> SendArray( + string sender, + List receptors, + List messages, + string localMessageId) + { + var senders = new List(); + for (var i = 0; i < receptors.Count; i++) senders.Add(sender); + + return await SendArray( + senders, + receptors, + messages, + localMessageId); + } - private string GetApiPath(string _base, string method, string output) - { - return string.Format(Apipath, _base, method, output); - } + public async Task> SendArray( + List senders, + List receptors, + List messages, + string localMessageId) + { + var types = new List(); + for (var i = 0; i <= receptors.Count - 1; i++) types.Add(MessageType.MobileMemory); + var localMessageIds = new List(); + for (var i = 0; i <= receptors.Count - 1; i++) localMessageIds.Add(localMessageId); + return await SendArray( + senders, + receptors, + messages, + types, + DateTime.MinValue, + localMessageIds); + } - private async Task Execute(string path, Dictionary _params) + public async Task> SendArray( + List senders, + List receptors, + List messages, + List types, + DateTime date, + List localMessageIds) + { + var path = GetApiPath( + "sms", + "sendarray", + "json"); + var jsonSenders = JsonConvert.SerializeObject(senders); + var jsonReceptors = JsonConvert.SerializeObject(receptors); + var jsonMessages = JsonConvert.SerializeObject(messages); + var jsonTypes = JsonConvert.SerializeObject(types); + var param = new Dictionary { - var nvc = _params?.Select(x => new KeyValuePair(x.Key, x.Value?.ToString())); - - var postdata = new FormUrlEncodedContent(nvc); - - var response = await _client.PostAsync(path, postdata); - var responseBody = await response.Content.ReadAsStringAsync(); - - // System.Diagnostics.Debug.WriteLine(responseBody); - - try { - var result = JsonConvert.DeserializeObject(responseBody); - - if (response.StatusCode != HttpStatusCode.OK) - throw new ApiException(result.Return.message, result.Return.status); - - return responseBody; - } - catch (HttpException) + "message", jsonMessages + }, + { + "sender", jsonSenders + }, + { + "receptor", jsonReceptors + }, + { + "type", jsonTypes + }, { - throw; + "date", date == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(date) } - } - public async Task> Send(string sender, List receptor, string message) - { - return await Send(sender, receptor, message, MessageType.MobileMemory, DateTime.MinValue); - } + }; + if (localMessageIds != null && + localMessageIds.Count > 0) + param.Add("localMessageIds", string.Join(",", localMessageIds)); + + var responsebody = await Execute(path, param); + var l = JsonConvert.DeserializeObject(responsebody); + if (l.entries == null) return new List(); + return l.entries; + } - public async Task Send(string sender, String receptor, string message) - { - return await Send(sender, receptor, message, MessageType.MobileMemory, DateTime.MinValue); - } - public async Task Send(string sender, string receptor, string message, MessageType type, DateTime date) - { - List receptors = new List { receptor }; - return (await Send(sender, receptors, message, type, date))[0]; - } - public async Task> Send(string sender, List receptor, string message, MessageType type, DateTime date) - { - return await Send(sender, receptor, message, type, date, null); - } - public async Task Send(string sender, string receptor, string message, MessageType type, DateTime date, string localid) - { - var receptors = new List { receptor }; - var localids = new List { localid }; - return (await Send(sender, receptors, message, type, date, localids))[0]; - } - public async Task Send(string sender, string receptor, string message, string localid) - { - return await Send(sender, receptor, message, MessageType.MobileMemory, DateTime.MinValue, localid); - } - public async Task> Send(string sender, List receptors, string message, string localid) + public async Task> Status( + List messageIds) + { + var path = GetApiPath( + "sms", + "status", + "json"); + var param = new Dictionary { - List localids = new List(); - for (var i = 0; i <= receptors.Count - 1; i++) { - localids.Add(localid); + "messageId", string.Join(",", messageIds) } - return await Send(sender, receptors, message, MessageType.MobileMemory, DateTime.MinValue, localids); - } - public async Task> Send(string sender, List receptor, string message, MessageType type, DateTime date, List localids) - { - var path = GetApiPath("sms", "send", "json"); - var param = new Dictionary - { - {"sender", System.Net.WebUtility.HtmlEncode(sender)}, - {"receptor", System.Net.WebUtility.HtmlEncode(StringHelper.Join(",", receptor.ToArray()))}, - {"message", message}, - {"type", (int) type}, - {"date", date == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(date)} }; - if (localids != null && localids.Count > 0) - { - param.Add("localid", StringHelper.Join(",", localids.ToArray())); - } - var responseBody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responseBody); - return l.entries; - } + var responsebody = await Execute(path, param); + var l = JsonConvert.DeserializeObject(responsebody); + if (l.entries == null) return new List(); + return l.entries; + } - public async Task> SendArray(List senders, List receptors, List messages) + public async Task Status( + string messageId) + { + var ids = new List { - var types = new List(); - for (var i = 0; i <= senders.Count - 1; i++) - { - types.Add(MessageType.MobileMemory); - } - return await SendArray(senders, receptors, messages, types, DateTime.MinValue, null); - } + messageId + }; + var result = await Status(ids); + return result.Count == 1 ? result[0] : null; + } - public async Task> SendArray(string sender, List receptors, List messages, MessageType type, DateTime date) + public async Task> StatusLocalMessageId( + List messageIds) + { + var path = GetApiPath( + "sms", + "statuslocalmessageid", + "json"); + var param = new Dictionary { - var senders = new List(); - for (var i = 0; i < receptors.Count; i++) { - senders.Add(sender); + "localId", string.Join(",", messageIds) } - var types = new List(); - for (var i = 0; i <= senders.Count - 1; i++) + }; + var responsebody = await Execute(path, param); + var l = JsonConvert.DeserializeObject(responsebody); + return l.entries; + } + + public async Task StatusLocalMessageId( + string messageId) + { + var result = await StatusLocalMessageId( + new List { - types.Add(MessageType.MobileMemory); - } - return await SendArray(senders, receptors, messages, types, date, null); - } + messageId + }); + return result.Count == 1 ? result[0] : null; + } - public async Task> SendArray(string sender, List receptors, List messages, MessageType type, DateTime date, string localmessageids) + public async Task> Select( + List messageIds) + { + var path = GetApiPath( + "sms", + "select", + "json"); + var param = new Dictionary { - var senders = new List(); - for (var i = 0; i < receptors.Count; i++) { - senders.Add(sender); + "messageId", string.Join(",", messageIds) } - List types = new List(); - for (var i = 0; i <= senders.Count - 1; i++) - { - types.Add(MessageType.MobileMemory); - } - return await SendArray(senders, receptors, messages, types, date, new List() { localmessageids }); - } + }; + var responsebody = await Execute(path, param); + var l = JsonConvert.DeserializeObject(responsebody); + if (l.entries == null) return new List(); + return l.entries; + } - public async Task> SendArray(string sender, List receptors, List messages, string localmessageid) + public async Task Select( + string messageId) + { + var ids = new List { - List senders = new List(); - for (var i = 0; i < receptors.Count; i++) - { - senders.Add(sender); - } + messageId + }; + var result = await Select(ids); + return result.Count == 1 ? result[0] : null; + } + + public async Task> SelectOutbox( + DateTime startDate) + { + return await SelectOutbox(startDate, DateTime.MaxValue); + } - return await SendArray(senders, receptors, messages, localmessageid); - } + public async Task> SelectOutbox( + DateTime startDate, + DateTime endDate) + { + return await SelectOutbox( + startDate, + endDate, + null); + } - public async Task> SendArray(List senders, List receptors, List messages, string localmessageid) + public async Task> SelectOutbox( + DateTime startDate, + DateTime endDate, + string sender) + { + var path = GetApiPath( + "sms", + "selectoutbox", + "json"); + var param = new Dictionary { - var types = new List(); - for (var i = 0; i <= receptors.Count - 1; i++) { - types.Add(MessageType.MobileMemory); - } - var localmessageids = new List(); - for (var i = 0; i <= receptors.Count - 1; i++) + "startDate", startDate == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(startDate) + }, { - localmessageids.Add(localmessageid); - } - return await SendArray(senders, receptors, messages, types, DateTime.MinValue, localmessageids); - } - - public async Task> SendArray(List senders, List receptors, List messages, List types, DateTime date, List localmessageids) - { - String path = GetApiPath("sms", "sendarray", "json"); - var jsonSenders = JsonConvert.SerializeObject(senders); - var jsonReceptors = JsonConvert.SerializeObject(receptors); - var jsonMessages = JsonConvert.SerializeObject(messages); - var jsonTypes = JsonConvert.SerializeObject(types); - var param = new Dictionary - { - {"message", jsonMessages}, - {"sender", jsonSenders}, - {"receptor", jsonReceptors}, - {"type", jsonTypes}, - {"date", date == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(date)} - }; - if (localmessageids != null && localmessageids.Count > 0) + "endDate", endDate == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(endDate) + }, { - param.Add("localmessageids", StringHelper.Join(",", localmessageids.ToArray())); + "sender", sender } + }; + var responsebody = await Execute(path, param); + var l = JsonConvert.DeserializeObject(responsebody); + return l.entries; + } - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - if (l.entries == null) - { - return new List(); - } - return l.entries; - } + public async Task> LatestOutbox( + long pageSize) + { + return await LatestOutbox(pageSize, ""); + } - public async Task> Status(List messageids) - { - string path = GetApiPath("sms", "status", "json"); - var param = new Dictionary + public async Task> LatestOutbox( + long pageSize, + string sender) + { + var path = GetApiPath( + "sms", + "latestoutbox", + "json"); + var param = new Dictionary { - {"messageid", StringHelper.Join(",", messageids.ToArray())} - }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - if (l.entries == null) { - return new List(); + "pageSize", pageSize + }, + { + "sender", sender } - return l.entries; - } + }; + var responsebody = await Execute(path, param); + var l = JsonConvert.DeserializeObject(responsebody); + return l.entries; + } - public async Task Status(string messageid) - { - var ids = new List { messageid }; - var result = await Status(ids); - return result.Count == 1 ? result[0] : null; - } + public async Task CountOutbox( + DateTime startDate) + { + return await CountOutbox( + startDate, + DateTime.MaxValue, + 10); + } - public async Task> StatusLocalMessageId(List messageids) - { - string path = GetApiPath("sms", "statuslocalmessageid", "json"); - var param = new Dictionary { { "localid", StringHelper.Join(",", messageids.ToArray()) } }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries; - } - - public async Task StatusLocalMessageId(string messageid) - { - List result = await StatusLocalMessageId(new List() { messageid }); - return result.Count == 1 ? result[0] : null; - } + public async Task CountOutbox( + DateTime startDate, + DateTime endDate) + { + return await CountOutbox( + startDate, + endDate, + 0); + } - public async Task> Select(List messageids) + public async Task CountOutbox( + DateTime startDate, + DateTime endDate, + int status) + { + var path = GetApiPath( + "sms", + "countoutbox", + "json"); + var param = new Dictionary { - var path = GetApiPath("sms", "select", "json"); - var param = new Dictionary { { "messageid", StringHelper.Join(",", messageids.ToArray()) } }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - if (l.entries == null) { - return new List(); + "startDate", startDate == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(startDate) + }, + { + "endDate", endDate == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(endDate) + }, + { + "status", status } - return l.entries; - } + }; + var responsebody = await Execute(path, param); + var l = JsonConvert.DeserializeObject(responsebody); + if (l.entries == null || + l.entries[0] == null) + return new CountOutboxResult(); + return l.entries[0]; + } - public async Task Select(string messageid) + public async Task> Cancel( + List ids) + { + var path = GetApiPath( + "sms", + "cancel", + "json"); + var param = new Dictionary { - var ids = new List { messageid }; - var result = await Select(ids); - return result.Count == 1 ? result[0] : null; - } + { + "messageId", string.Join(",", ids) + } + }; + var responsebody = await Execute(path, param); + var l = JsonConvert.DeserializeObject(responsebody); + return l.entries; + } - public async Task> SelectOutbox(DateTime startdate) + public async Task Cancel( + string messageId) + { + var ids = new List { - return await SelectOutbox(startdate, DateTime.MaxValue); - } + messageId + }; + var result = await Cancel(ids); + return result.Count == 1 ? result[0] : null; + } - public async Task> SelectOutbox(DateTime startdate, DateTime enddate) + public async Task> Receive( + string line, + int isRead) + { + var path = GetApiPath( + "sms", + "receive", + "json"); + var param = new Dictionary { - return await SelectOutbox(startdate, enddate, null); - } + { + "lineNumber", line + }, + { + "isRead", isRead + } + }; + var responsebody = await Execute(path, param); + var l = JsonConvert.DeserializeObject(responsebody); + if (l.entries == null) return new List(); + return l.entries; + } - public async Task> SelectOutbox(DateTime startdate, DateTime enddate, String sender) - { - String path = GetApiPath("sms", "selectoutbox", "json"); - var param = new Dictionary - { - {"startdate", startdate == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(startdate)}, - {"enddate", enddate == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(enddate)}, - {"sender", sender} - }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries; - } - - public async Task> LatestOutbox(long pagesize) - { - return await LatestOutbox(pagesize, ""); - } + public async Task CountInbox( + DateTime startDate, + string lineNumber) + { + return await CountInbox( + startDate, + DateTime.MaxValue, + lineNumber, + 0); + } - public async Task> LatestOutbox(long pagesize, String sender) - { - var path = GetApiPath("sms", "latestoutbox", "json"); - var param = new Dictionary { { "pagesize", pagesize }, { "sender", sender } }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries; - } - - public async Task CountOutbox(DateTime startdate) - { - return await CountOutbox(startdate, DateTime.MaxValue, 10); - } + public async Task CountInbox( + DateTime startDate, + DateTime endDate, + string lineNumber) + { + return await CountInbox( + startDate, + endDate, + lineNumber, + 0); + } - public async Task CountOutbox(DateTime startdate, DateTime enddate) + public async Task CountInbox( + DateTime startDate, + DateTime endDate, + string lineNumber, + int isRead) + { + var path = GetApiPath( + "sms", + "countoutbox", + "json"); + var param = new Dictionary { - return await CountOutbox(startdate, enddate, 0); - } + { + "startDate", startDate == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(startDate) + }, + { + "endDate", endDate == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(endDate) + }, + { + "lineNumber", lineNumber + }, + { + "isRead", isRead + } + }; + var responsebody = await Execute(path, param); + var l = JsonConvert.DeserializeObject(responsebody); + return l.entries[0]; + } - public async Task CountOutbox(DateTime startdate, DateTime enddate, int status) + public async Task> CountPostalCode( + long postalcode) + { + var path = GetApiPath( + "sms", + "countpostalcode", + "json"); + var param = new Dictionary { - string path = GetApiPath("sms", "countoutbox", "json"); - var param = new Dictionary - { - {"startdate", startdate == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(startdate)}, - {"enddate", enddate == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(enddate)}, - {"status", status} - }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - if (l.entries == null || l.entries[0] == null) - { - return new CountOutboxResult(); + { + "postalcode", postalcode } - return l.entries[0]; - } + }; + var responsebody = await Execute(path, param); + var l = JsonConvert.DeserializeObject(responsebody); + return l.entries; + } - public async Task> Cancel(List ids) - { - string path = GetApiPath("sms", "cancel", "json"); - var param = new Dictionary + public async Task> SendByPostalCode( + long postalcode, + string sender, + string message, + long mciStartIndex, + long mciCount, + long mtnStartIndex, + long mtnCount) + { + return await SendByPostalCode( + postalcode, + sender, + message, + mciStartIndex, + mciCount, + mtnStartIndex, + mtnCount, + DateTime.MinValue); + } + + public async Task> SendByPostalCode( + long postalcode, + string sender, + string message, + long mciStartIndex, + long mciCount, + long mtnStartIndex, + long mtnCount, + DateTime date) + { + var path = GetApiPath( + "sms", + "sendbypostalcode", + "json"); + var param = new Dictionary { - {"messageid", StringHelper.Join(",", ids.ToArray())} + { + "postalcode", postalcode + }, + { + "sender", sender + }, + { + "message", WebUtility.HtmlEncode(message) + }, + { + "mciStartIndex", mciStartIndex + }, + { + "mciCount", mciCount + }, + { + "mtnStartIndex", mtnStartIndex + }, + { + "mtnCount", mtnCount + }, + { + "date", date == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(date) + } }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries; - } + var responsebody = await Execute(path, param); + var l = JsonConvert.DeserializeObject(responsebody); + return l.entries; + } - public async Task Cancel(String messageid) - { - var ids = new List { messageid }; - var result = await Cancel(ids); - return result.Count == 1 ? result[0] : null; - } + public async Task AccountInfo() + { + var path = GetApiPath( + "account", + "info", + "json"); + var responsebody = await Execute(path, null); + var l = JsonConvert.DeserializeObject(responsebody); + return l.entries; + } - public async Task> Receive(string line, int isread) + public async Task AccountConfig( + string apiLogs, + string dailyReport, + string debugMode, + string defaultSender, + int? minCreditAlarm, + string resendFailed) + { + var path = GetApiPath( + "account", + "config", + "json"); + var param = new Dictionary { - String path = GetApiPath("sms", "receive", "json"); - var param = new Dictionary { { "linenumber", line }, { "isread", isread } }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - if (l.entries == null) { - return new List(); + "apiLogs", apiLogs + }, + { + "dailyReport", dailyReport + }, + { + "debugMode", debugMode + }, + { + "defaultSender", defaultSender + }, + { + "minCreditAlarm", minCreditAlarm + }, + { + "resendFailed", resendFailed } - return l.entries; - } + }; + var responsebody = await Execute(path, param); + var l = JsonConvert.DeserializeObject(responsebody); + return l.entries; + } - public async Task CountInbox(DateTime startdate, string linenumber) - { - return await CountInbox(startdate, DateTime.MaxValue, linenumber, 0); - } + public async Task VerifyLookup( + string receptor, + string token, + string template) + { + return await VerifyLookup( + receptor, + token, + null, + null, + template, + VerifyLookupType.Sms); + } - public async Task CountInbox(DateTime startdate, DateTime enddate, String linenumber) - { - return await CountInbox(startdate, enddate, linenumber, 0); - } + public async Task VerifyLookup( + string receptor, + string token, + string template, + VerifyLookupType type) + { + return await VerifyLookup( + receptor, + token, + null, + null, + template, + type); + } - public async Task CountInbox(DateTime startdate, DateTime enddate, String linenumber, int isread) - { - var path = GetApiPath("sms", "countoutbox", "json"); - var param = new Dictionary - { - {"startdate", startdate == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(startdate)}, - {"enddate", enddate == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(enddate)}, - {"linenumber", linenumber}, - {"isread", isread} - }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries[0]; - } + public async Task VerifyLookup( + string receptor, + string token, + string token2, + string token3, + string template) + { + return await VerifyLookup( + receptor, + token, + token2, + token3, + template, + VerifyLookupType.Sms); + } - public async Task> CountPostalCode(long postalcode) - { - String path = GetApiPath("sms", "countpostalcode", "json"); - var param = new Dictionary { { "postalcode", postalcode } }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries; - } - - public async Task> SendByPostalCode(long postalcode, String sender, String message, long mcistartIndex, long mcicount, long mtnstartindex, long mtncount) - { - return await SendByPostalCode(postalcode, sender, message, mcistartIndex, mcicount, mtnstartindex, mtncount, DateTime.MinValue); - } + public async Task VerifyLookup( + string receptor, + string token, + string token2, + string token3, + string token10, + string template) + { + return await VerifyLookup( + receptor, + token, + token2, + token3, + token10, + template, + VerifyLookupType.Sms); + } - public async Task> SendByPostalCode(long postalcode, String sender, String message, long mcistartIndex, long mcicount, long mtnstartindex, long mtncount, DateTime date) - { - var path = GetApiPath("sms", "sendbypostalcode", "json"); - var param = new Dictionary - { - {"postalcode", postalcode}, - {"sender", sender}, - {"message", System.Net.WebUtility.HtmlEncode(message)}, - {"mcistartIndex", mcistartIndex}, - {"mcicount", mcicount}, - {"mtnstartindex", mtnstartindex}, - {"mtncount", mtncount}, - {"date", date == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(date)} - }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries; - } + public async Task VerifyLookup( + string receptor, + string token, + string token2, + string token3, + string template, + VerifyLookupType type) + { + return await VerifyLookup( + receptor, + token, + token2, + token3, + null, + template, + type); + } - public async Task AccountInfo() - { - var path = GetApiPath("account", "info", "json"); - var responsebody = await Execute(path, null); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries; - } + public async Task VerifyLookup( + string receptor, + string token, + string token2, + string token3, + string token10, + string template, + VerifyLookupType type) + { + return await VerifyLookup( + receptor, + token, + token2, + token3, + token10, + null, + template, + type); + } - public async Task AccountConfig(string apilogs, string dailyreport, string debugmode, string defaultsender, int? mincreditalarm, string resendfailed) - { - var path = GetApiPath("account", "config", "json"); - var param = new Dictionary + public async Task VerifyLookup( + string receptor, + string token, + string token2, + string token3, + string token10, + string token20, + string template, + VerifyLookupType type) + { + var path = GetApiPath( + "verify", + "lookup", + "json"); + var param = new Dictionary { - {"apilogs", apilogs}, - {"dailyreport", dailyreport}, - {"debugmode", debugmode}, - {"defaultsender", defaultsender}, - {"mincreditalarm", mincreditalarm}, - {"resendfailed", resendfailed} + { + "receptor", receptor + }, + { + "template", template + }, + { + "token", token + }, + { + "token2", token2 + }, + { + "token3", token3 + }, + { + "token10", token10 + }, + { + "token20", token20 + }, + { + "type", type + } }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries; - } + var responsebody = await Execute(path, param); + var l = JsonConvert.DeserializeObject(responsebody); + return l.entries[0]; + } - public async Task VerifyLookup(string receptor, string token, string template) - { - return await VerifyLookup(receptor, token, null, null, template, VerifyLookupType.Sms); - } - public async Task VerifyLookup(string receptor, string token, string template, VerifyLookupType type) - { - return await VerifyLookup(receptor, token, null, null, template, type); - } - public async Task VerifyLookup(string receptor, string token, string token2, string token3, string template) - { - return await VerifyLookup(receptor, token, token2, token3, template, VerifyLookupType.Sms); - } - public async Task VerifyLookup(string receptor, string token, string token2, string token3, string token10, string template) - { - return await VerifyLookup(receptor, token, token2, token3, token10, template, VerifyLookupType.Sms); - } - public async Task VerifyLookup(string receptor, string token, string token2, string token3, string template, VerifyLookupType type) - { - return await VerifyLookup(receptor, token, token2, token3, null, template, type); - } - public async Task VerifyLookup(string receptor, string token, string token2, string token3, string token10, string template, VerifyLookupType type) - { - return await VerifyLookup(receptor, token, token2, token3, token10, null, template, type); - } + #region << CallMakeTts >> - public async Task VerifyLookup(string receptor, string token, string token2, string token3, string token10, string token20, string template, VerifyLookupType type) - { - var path = GetApiPath("verify", "lookup", "json"); - var param = new Dictionary - { - {"receptor", receptor}, - {"template", template}, - {"token", token}, - {"token2", token2}, - {"token3", token3}, - {"token10", token10}, - {"token20", token20}, - {"type", type}, - }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries[0]; - } - - - #region << CallMakeTTS >> - - public async Task CallMakeTTS(string message, string receptor) - { - return (await CallMakeTTS(message, new List { receptor }, null, null))[0]; - } - public async Task> CallMakeTTS(string message, List receptor) - { - return await CallMakeTTS(message, receptor, null, null); - } - - public async Task> CallMakeTTS(string message, List receptor, DateTime? date, List localid) - { - var path = GetApiPath("call", "maketts", "json"); - var param = new Dictionary + public async Task CallMakeTts( + string message, + string receptor) + { + return (await CallMakeTts( + message, + new List { - {"receptor", StringHelper.Join(",", receptor.ToArray())}, - {"message", System.Net.WebUtility.HtmlEncode(message)}, - }; - if (date != null) - param.Add("date", DateHelper.DateTimeToUnixTimestamp(date.Value)); - if (localid != null && localid.Count > 0) - param.Add("localid", StringHelper.Join(",", localid.ToArray())); - var responseBody = await Execute(path, param); + receptor + }, + null, + null))[0]; + } - return JsonConvert.DeserializeObject(responseBody).entries; - } + public async Task> CallMakeTts( + string message, + List receptor) + { + return await CallMakeTts( + message, + receptor, + null, + null); + } - #endregion << CallMakeTTS >> + public async Task> CallMakeTts( + string message, + List receptor, + DateTime? date, + List localId) + { + var path = GetApiPath( + "call", + "maketts", + "json"); + var param = new Dictionary + { + { + "receptor", string.Join(",", receptor) + }, + { + "message", WebUtility.HtmlEncode(message) + } + }; + if (date != null) param.Add("date", DateHelper.DateTimeToUnixTimestamp(date.Value)); + if (localId != null && + localId.Count > 0) + param.Add("localId", string.Join(",", localId)); + var responseBody = await Execute(path, param); + return JsonConvert.DeserializeObject(responseBody).entries; } + + #endregion << CallMakeTts >> } \ No newline at end of file diff --git a/Kavenegar.Core/KavenegarApi2.cs b/Kavenegar.Core/KavenegarApi2.cs new file mode 100644 index 0000000..fc54c23 --- /dev/null +++ b/Kavenegar.Core/KavenegarApi2.cs @@ -0,0 +1,430 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Kavenegar.Core.Models; +using Kavenegar.Core.Models.Enums; + +namespace Kavenegar.Core; + +class KavenegarApi2 : IKavenegarApi +{ + public KavenegarApi2( + string apiKey) + { + ApiKey = apiKey; + } + + public string ApiKey { get; set; } + + public Task> Send( + string sender, + List receptor, + string message) + { + throw new NotImplementedException(); + } + + public Task Send( + string sender, + string receptor, + string message) + { + throw new NotImplementedException(); + } + + public Task Send( + string sender, + string receptor, + string message, + MessageType type, + DateTime date) + { + throw new NotImplementedException(); + } + + public Task> Send( + string sender, + List receptor, + string message, + MessageType type, + DateTime date) + { + throw new NotImplementedException(); + } + + public Task Send( + string sender, + string receptor, + string message, + MessageType type, + DateTime date, + string localId) + { + throw new NotImplementedException(); + } + + public Task Send( + string sender, + string receptor, + string message, + string localId) + { + throw new NotImplementedException(); + } + + public Task> Send( + string sender, + List receptors, + string message, + string localId) + { + throw new NotImplementedException(); + } + + public Task> Send( + string sender, + List receptor, + string message, + MessageType type, + DateTime date, + List localIds) + { + throw new NotImplementedException(); + } + + public Task> SendArray( + List senders, + List receptors, + List messages) + { + throw new NotImplementedException(); + } + + public Task> SendArray( + string sender, + List receptors, + List messages, + MessageType type, + DateTime date) + { + throw new NotImplementedException(); + } + + public Task> SendArray( + string sender, + List receptors, + List messages, + MessageType type, + DateTime date, + string localMessageIds) + { + throw new NotImplementedException(); + } + + public Task> SendArray( + string sender, + List receptors, + List messages, + string localMessageId) + { + throw new NotImplementedException(); + } + + public Task> SendArray( + List senders, + List receptors, + List messages, + string localMessageId) + { + throw new NotImplementedException(); + } + + public Task> SendArray( + List senders, + List receptors, + List messages, + List types, + DateTime date, + List localMessageIds) + { + throw new NotImplementedException(); + } + + public Task> Status( + List messageIds) + { + throw new NotImplementedException(); + } + + public Task Status( + string messageId) + { + throw new NotImplementedException(); + } + + public Task> StatusLocalMessageId( + List messageIds) + { + throw new NotImplementedException(); + } + + public Task StatusLocalMessageId( + string messageId) + { + throw new NotImplementedException(); + } + + public Task> Select( + List messageIds) + { + throw new NotImplementedException(); + } + + public Task Select( + string messageId) + { + throw new NotImplementedException(); + } + + public Task> SelectOutbox( + DateTime startDate) + { + throw new NotImplementedException(); + } + + public Task> SelectOutbox( + DateTime startDate, + DateTime endDate) + { + throw new NotImplementedException(); + } + + public Task> SelectOutbox( + DateTime startDate, + DateTime endDate, + string sender) + { + throw new NotImplementedException(); + } + + public Task> LatestOutbox( + long pageSize) + { + throw new NotImplementedException(); + } + + public Task> LatestOutbox( + long pageSize, + string sender) + { + throw new NotImplementedException(); + } + + public Task CountOutbox( + DateTime startDate) + { + throw new NotImplementedException(); + } + + public Task CountOutbox( + DateTime startDate, + DateTime endDate) + { + throw new NotImplementedException(); + } + + public Task CountOutbox( + DateTime startDate, + DateTime endDate, + int status) + { + throw new NotImplementedException(); + } + + public Task> Cancel( + List ids) + { + throw new NotImplementedException(); + } + + public Task Cancel( + string messageId) + { + throw new NotImplementedException(); + } + + public Task> Receive( + string line, + int isRead) + { + throw new NotImplementedException(); + } + + public Task CountInbox( + DateTime startDate, + string lineNumber) + { + throw new NotImplementedException(); + } + + public Task CountInbox( + DateTime startDate, + DateTime endDate, + string lineNumber) + { + throw new NotImplementedException(); + } + + public Task CountInbox( + DateTime startDate, + DateTime endDate, + string lineNumber, + int isRead) + { + throw new NotImplementedException(); + } + + public Task> CountPostalCode( + long postalcode) + { + throw new NotImplementedException(); + } + + public Task> SendByPostalCode( + long postalcode, + string sender, + string message, + long mciStartIndex, + long mciCount, + long mtnStartIndex, + long mtnCount) + { + throw new NotImplementedException(); + } + + public Task> SendByPostalCode( + long postalcode, + string sender, + string message, + long mciStartIndex, + long mciCount, + long mtnStartIndex, + long mtnCount, + DateTime date) + { + throw new NotImplementedException(); + } + + public Task AccountInfo() + { + throw new NotImplementedException(); + } + + public Task AccountConfig( + string apiLogs, + string dailyReport, + string debugMode, + string defaultSender, + int? minCreditAlarm, + string resendFailed) + { + throw new NotImplementedException(); + } + + public Task VerifyLookup( + string receptor, + string token, + string template) + { + throw new NotImplementedException(); + } + + public Task VerifyLookup( + string receptor, + string token, + string template, + VerifyLookupType type) + { + throw new NotImplementedException(); + } + + public Task VerifyLookup( + string receptor, + string token, + string token2, + string token3, + string template) + { + throw new NotImplementedException(); + } + + public Task VerifyLookup( + string receptor, + string token, + string token2, + string token3, + string token10, + string template) + { + throw new NotImplementedException(); + } + + public Task VerifyLookup( + string receptor, + string token, + string token2, + string token3, + string template, + VerifyLookupType type) + { + throw new NotImplementedException(); + } + + public Task VerifyLookup( + string receptor, + string token, + string token2, + string token3, + string token10, + string template, + VerifyLookupType type) + { + throw new NotImplementedException(); + } + + public Task VerifyLookup( + string receptor, + string token, + string token2, + string token3, + string token10, + string token20, + string template, + VerifyLookupType type) + { + throw new NotImplementedException(); + } + + public Task CallMakeTts( + string message, + string receptor) + { + throw new NotImplementedException(); + } + + public Task> CallMakeTts( + string message, + List receptor) + { + throw new NotImplementedException(); + } + + public Task> CallMakeTts( + string message, + List receptor, + DateTime? date, + List localId) + { + throw new NotImplementedException(); + } +} \ No newline at end of file diff --git a/Kavenegar.Core/Models/AccountConfigResult.cs b/Kavenegar.Core/Models/AccountConfigResult.cs index 3f9428a..0d844c2 100644 --- a/Kavenegar.Core/Models/AccountConfigResult.cs +++ b/Kavenegar.Core/Models/AccountConfigResult.cs @@ -1,12 +1,11 @@ -namespace Kavenegar.Core.Models +namespace Kavenegar.Core.Models; + +public class AccountConfigResult { - public class AccountConfigResult - { - public string ApiLogs { get; set; } - public string DailyReport { get; set; } - public string DebugMode { get; set; } - public string DefaultSender { get; set; } - public string MinCreditAlarm { get; set; } - public string ResendFailed { get; set; } - } + public string ApiLogs { get; set; } + public string DailyReport { get; set; } + public string DebugMode { get; set; } + public string DefaultSender { get; set; } + public string MinCreditAlarm { get; set; } + public string ResendFailed { get; set; } } \ No newline at end of file diff --git a/Kavenegar.Core/Models/AccountInfoResult.cs b/Kavenegar.Core/Models/AccountInfoResult.cs index 4fac746..ca13c6d 100644 --- a/Kavenegar.Core/Models/AccountInfoResult.cs +++ b/Kavenegar.Core/Models/AccountInfoResult.cs @@ -1,14 +1,14 @@ using System; -namespace Kavenegar.Core.Models +using Kavenegar.Core.Utils; + +namespace Kavenegar.Core.Models; + +public class AccountInfoResult { - public class AccountInfoResult - { - public long RemainCredit { get; set; } - public long Expiredate { get; set; } - public DateTime GregorianExpiredate - { - get { return Utils.DateHelper.UnixTimestampToDateTime(Expiredate); } - } - public string Type { get; set; } - } + public long RemainCredit { get; set; } + public long Expiredate { get; set; } + + public DateTime GregorianExpiredate => DateHelper.UnixTimestampToDateTime(Expiredate); + + public string Type { get; set; } } \ No newline at end of file diff --git a/Kavenegar.Core/Models/CountInboxResult.cs b/Kavenegar.Core/Models/CountInboxResult.cs index 08e02f0..b13e9b1 100644 --- a/Kavenegar.Core/Models/CountInboxResult.cs +++ b/Kavenegar.Core/Models/CountInboxResult.cs @@ -1,9 +1,8 @@ -namespace Kavenegar.Core.Models +namespace Kavenegar.Core.Models; + +public class CountInboxResult { - public class CountInboxResult - { - public long StartDate { get; set; } - public long EndDate { get; set; } - public long SumCount { get; set; } - } + public long StartDate { get; set; } + public long EndDate { get; set; } + public long SumCount { get; set; } } \ No newline at end of file diff --git a/Kavenegar.Core/Models/CountOutboxResult.cs b/Kavenegar.Core/Models/CountOutboxResult.cs index 5fe6ab8..9efa686 100644 --- a/Kavenegar.Core/Models/CountOutboxResult.cs +++ b/Kavenegar.Core/Models/CountOutboxResult.cs @@ -1,8 +1,7 @@ -namespace Kavenegar.Core.Models +namespace Kavenegar.Core.Models; + +public class CountOutboxResult : CountInboxResult { - public class CountOutboxResult : CountInboxResult - { - public long SumPart { get; set; } - public long Cost { get; set; } - } + public long SumPart { get; set; } + public long Cost { get; set; } } \ No newline at end of file diff --git a/Kavenegar.Core/Models/CountPostalCodeResult.cs b/Kavenegar.Core/Models/CountPostalCodeResult.cs index e0d745c..2a312df 100644 --- a/Kavenegar.Core/Models/CountPostalCodeResult.cs +++ b/Kavenegar.Core/Models/CountPostalCodeResult.cs @@ -1,8 +1,7 @@ -namespace Kavenegar.Core.Models +namespace Kavenegar.Core.Models; + +public class CountPostalCodeResult { - public class CountPostalCodeResult - { - public string Section { get; set; } - public int Value { get; set; } - } + public string Section { get; set; } + public int Value { get; set; } } \ No newline at end of file diff --git a/Kavenegar.Core/Models/Enums/MessageStatus.cs b/Kavenegar.Core/Models/Enums/MessageStatus.cs index 3d95e8d..e0b1026 100644 --- a/Kavenegar.Core/Models/Enums/MessageStatus.cs +++ b/Kavenegar.Core/Models/Enums/MessageStatus.cs @@ -1,15 +1,14 @@ -namespace Kavenegar.Core.Models.Enums +namespace Kavenegar.Core.Models.Enums; + +public enum MessageStatus { - public enum MessageStatus - { - Queued = 1, - Schulded = 2, - SentToCenter = 4, - Delivered = 10, - Undelivered = 11, - Canceled = 13, - Filtered = 14, - Received = 50, - Incorrect = 100 - } -} + Queued = 1, + Schulded = 2, + SentToCenter = 4, + Delivered = 10, + Undelivered = 11, + Canceled = 13, + Filtered = 14, + Received = 50, + Incorrect = 100 +} \ No newline at end of file diff --git a/Kavenegar.Core/Models/Enums/MessageType.cs b/Kavenegar.Core/Models/Enums/MessageType.cs index 1161def..e6d26b3 100644 --- a/Kavenegar.Core/Models/Enums/MessageType.cs +++ b/Kavenegar.Core/Models/Enums/MessageType.cs @@ -1,10 +1,9 @@ -namespace Kavenegar.Core.Models.Enums +namespace Kavenegar.Core.Models.Enums; + +public enum MessageType { - public enum MessageType - { - Flash = 0, - MobileMemory = 1, - SimMemory = 2, - AppMemory = 3 - } + Flash = 0, + MobileMemory = 1, + SimMemory = 2, + AppMemory = 3 } \ No newline at end of file diff --git a/Kavenegar.Core/Models/Enums/MetaCode.cs b/Kavenegar.Core/Models/Enums/MetaCode.cs index a4da33e..3d4ddaf 100644 --- a/Kavenegar.Core/Models/Enums/MetaCode.cs +++ b/Kavenegar.Core/Models/Enums/MetaCode.cs @@ -1,24 +1,22 @@ -namespace Kavenegar.Core.Models.Enums -{ - public enum MetaCode - { +namespace Kavenegar.Core.Models.Enums; - NotChecked = 99, - Approved = 100, - InvalidApiKey = 101, - ExpiredApiKey = 102, - AccountDisabled = 103, - NotEnoughCredit = 104, - ServerisBusy = 105, - UndefinedCommand = 106, - RequestFailed = 107, - ParametersBroken = 108, - InvalidRecp = 110, - InvalidSenderNumber = 111, - EmptyMessage = 112, - RecpIsTooLarge = 113, - InvalidDate = 114, - MsgIsTooLarge = 115, - RecpNotEqualWithMessage = 116 - } +public enum MetaCode +{ + NotChecked = 99, + Approved = 100, + InvalidApiKey = 101, + ExpiredApiKey = 102, + AccountDisabled = 103, + NotEnoughCredit = 104, + ServerisBusy = 105, + UndefinedCommand = 106, + RequestFailed = 107, + ParametersBroken = 108, + InvalidRecp = 110, + InvalidSenderNumber = 111, + EmptyMessage = 112, + RecpIsTooLarge = 113, + InvalidDate = 114, + MsgIsTooLarge = 115, + RecpNotEqualWithMessage = 116 } \ No newline at end of file diff --git a/Kavenegar.Core/Models/Enums/VerifyLookupType.cs b/Kavenegar.Core/Models/Enums/VerifyLookupType.cs index 78e8965..553a24d 100644 --- a/Kavenegar.Core/Models/Enums/VerifyLookupType.cs +++ b/Kavenegar.Core/Models/Enums/VerifyLookupType.cs @@ -1,8 +1,7 @@ -namespace Kavenegar.Core.Models.Enums +namespace Kavenegar.Core.Models.Enums; + +public enum VerifyLookupType { - public enum VerifyLookupType - { - Sms = 0, - Call = 1, - } -} + Sms = 0, + Call = 1 +} \ No newline at end of file diff --git a/Kavenegar.Core/Models/ReceiveResult.cs b/Kavenegar.Core/Models/ReceiveResult.cs index ec97085..0ac6a1e 100644 --- a/Kavenegar.Core/Models/ReceiveResult.cs +++ b/Kavenegar.Core/Models/ReceiveResult.cs @@ -1,24 +1,19 @@ using System; -namespace Kavenegar.Core.Models +using Kavenegar.Core.Utils; + +namespace Kavenegar.Core.Models; + +public class ReceiveResult { - public class ReceiveResult - { - public long Date { get; set; } + public long Date { get; set; } + + public DateTime GregorianDate => DateHelper.UnixTimestampToDateTime(Date); - public DateTime GregorianDate - { - get - { - return Utils.DateHelper.UnixTimestampToDateTime(Date); - } - } - - public long MessageId { get; set; } + public long MessageId { get; set; } - public string Sender { get; set; } + public string Sender { get; set; } - public string Message { get; set; } + public string Message { get; set; } - public string Receptor { get; set; } - } + public string Receptor { get; set; } } \ No newline at end of file diff --git a/Kavenegar.Core/Models/SendResult.cs b/Kavenegar.Core/Models/SendResult.cs index db042be..64a43d4 100644 --- a/Kavenegar.Core/Models/SendResult.cs +++ b/Kavenegar.Core/Models/SendResult.cs @@ -1,29 +1,28 @@ using System; using Kavenegar.Core.Utils; -namespace Kavenegar.Core.Models +namespace Kavenegar.Core.Models; + +public class SendResult { - public class SendResult - { - public long Messageid { get; set; } + public long Messageid { get; set; } + + public int Cost { get; set; } - public int Cost { get; set; } + public DateTime GregorianDate + { + get => DateHelper.UnixTimestampToDateTime(Date); + set => Date = DateHelper.DateTimeToUnixTimestamp(value); + } - public DateTime GregorianDate - { - get { return DateHelper.UnixTimestampToDateTime(Date); } - set { Date = DateHelper.DateTimeToUnixTimestamp(value); } - } - - public long Date { get; set; } + public double Date { get; set; } - public string Message { get; set; } + public string Message { get; set; } - public string Receptor { get; set; } + public string Receptor { get; set; } - public string Sender { get; set; } - public int Status { get; set; } + public string Sender { get; set; } + public int Status { get; set; } - public string StatusText { get; set; } - } + public string StatusText { get; set; } } \ No newline at end of file diff --git a/Kavenegar.Core/Models/StatusLocalMessageIdResult.cs b/Kavenegar.Core/Models/StatusLocalMessageIdResult.cs index 22ed9f4..088063e 100644 --- a/Kavenegar.Core/Models/StatusLocalMessageIdResult.cs +++ b/Kavenegar.Core/Models/StatusLocalMessageIdResult.cs @@ -1,11 +1,11 @@ using Kavenegar.Core.Models.Enums; -namespace Kavenegar.Core.Models + +namespace Kavenegar.Core.Models; + +public class StatusLocalMessageIdResult { - public class StatusLocalMessageIdResult - { - public long Messageid { get; set; } - public long Localid { get; set; } - public MessageStatus Status { get; set; } - public string Statustext { get; set; } - } + public long Messageid { get; set; } + public long Localid { get; set; } + public MessageStatus Status { get; set; } + public string Statustext { get; set; } } \ No newline at end of file diff --git a/Kavenegar.Core/Models/StatusResult.cs b/Kavenegar.Core/Models/StatusResult.cs index 25708d8..298216f 100644 --- a/Kavenegar.Core/Models/StatusResult.cs +++ b/Kavenegar.Core/Models/StatusResult.cs @@ -1,10 +1,10 @@ using Kavenegar.Core.Models.Enums; -namespace Kavenegar.Core.Models + +namespace Kavenegar.Core.Models; + +public class StatusResult { - public class StatusResult - { - public long Messageid { get; set; } - public MessageStatus Status { get; set; } - public string Statustext { get; set; } - } + public long Messageid { get; set; } + public MessageStatus Status { get; set; } + public string Statustext { get; set; } } \ No newline at end of file diff --git a/Kavenegar.Core/Result.cs b/Kavenegar.Core/Result.cs new file mode 100644 index 0000000..774f98a --- /dev/null +++ b/Kavenegar.Core/Result.cs @@ -0,0 +1,7 @@ +namespace Kavenegar.Core; + +internal class Result +{ + public int status { get; set; } + public string message { get; set; } +} \ No newline at end of file diff --git a/Kavenegar.Core/ReturnAccountConfig.cs b/Kavenegar.Core/ReturnAccountConfig.cs new file mode 100644 index 0000000..b71fb3c --- /dev/null +++ b/Kavenegar.Core/ReturnAccountConfig.cs @@ -0,0 +1,9 @@ +using Kavenegar.Core.Models; + +namespace Kavenegar.Core; + +internal class ReturnAccountConfig +{ + public Result result { get; set; } + public AccountConfigResult entries { get; set; } +} \ No newline at end of file diff --git a/Kavenegar.Core/ReturnAccountInfo.cs b/Kavenegar.Core/ReturnAccountInfo.cs new file mode 100644 index 0000000..a31b52b --- /dev/null +++ b/Kavenegar.Core/ReturnAccountInfo.cs @@ -0,0 +1,9 @@ +using Kavenegar.Core.Models; + +namespace Kavenegar.Core; + +internal class ReturnAccountInfo +{ + public Result result { get; set; } + public AccountInfoResult entries { get; set; } +} \ No newline at end of file diff --git a/Kavenegar.Core/ReturnCountInbox.cs b/Kavenegar.Core/ReturnCountInbox.cs new file mode 100644 index 0000000..e77f9b3 --- /dev/null +++ b/Kavenegar.Core/ReturnCountInbox.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using Kavenegar.Core.Models; + +namespace Kavenegar.Core; + +internal class ReturnCountInbox +{ + public Result result { get; set; } + public List entries { get; set; } +} \ No newline at end of file diff --git a/Kavenegar.Core/ReturnCountOutbox.cs b/Kavenegar.Core/ReturnCountOutbox.cs new file mode 100644 index 0000000..10ea22a --- /dev/null +++ b/Kavenegar.Core/ReturnCountOutbox.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using Kavenegar.Core.Models; + +namespace Kavenegar.Core; + +internal class ReturnCountOutbox +{ + public Result result { get; set; } + public List entries { get; set; } +} \ No newline at end of file diff --git a/Kavenegar.Core/ReturnCountPostalCode.cs b/Kavenegar.Core/ReturnCountPostalCode.cs new file mode 100644 index 0000000..002f51c --- /dev/null +++ b/Kavenegar.Core/ReturnCountPostalCode.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using Kavenegar.Core.Models; + +namespace Kavenegar.Core; + +internal class ReturnCountPostalCode +{ + public Result result { get; set; } + public List entries { get; set; } +} \ No newline at end of file diff --git a/Kavenegar.Core/ReturnReceive.cs b/Kavenegar.Core/ReturnReceive.cs new file mode 100644 index 0000000..aded919 --- /dev/null +++ b/Kavenegar.Core/ReturnReceive.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using Kavenegar.Core.Models; + +namespace Kavenegar.Core; + +internal class ReturnReceive +{ + public Result result { get; set; } + public List entries { get; set; } +} \ No newline at end of file diff --git a/Kavenegar.Core/ReturnResult.cs b/Kavenegar.Core/ReturnResult.cs new file mode 100644 index 0000000..a96ad42 --- /dev/null +++ b/Kavenegar.Core/ReturnResult.cs @@ -0,0 +1,7 @@ +namespace Kavenegar.Core; + +internal class ReturnResult +{ + public Result Return { get; set; } + public object entries { get; set; } +} \ No newline at end of file diff --git a/Kavenegar.Core/ReturnSend.cs b/Kavenegar.Core/ReturnSend.cs new file mode 100644 index 0000000..0581a88 --- /dev/null +++ b/Kavenegar.Core/ReturnSend.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using Kavenegar.Core.Models; + +namespace Kavenegar.Core; + +internal class ReturnSend +{ + public Result Return { get; set; } + public List entries { get; set; } +} \ No newline at end of file diff --git a/Kavenegar.Core/ReturnStatus.cs b/Kavenegar.Core/ReturnStatus.cs new file mode 100644 index 0000000..37589f7 --- /dev/null +++ b/Kavenegar.Core/ReturnStatus.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using Kavenegar.Core.Models; + +namespace Kavenegar.Core; + +internal class ReturnStatus +{ + public Result result { get; set; } + public List entries { get; set; } +} \ No newline at end of file diff --git a/Kavenegar.Core/ReturnStatusLocalMessageId.cs b/Kavenegar.Core/ReturnStatusLocalMessageId.cs new file mode 100644 index 0000000..d124aad --- /dev/null +++ b/Kavenegar.Core/ReturnStatusLocalMessageId.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using Kavenegar.Core.Models; + +namespace Kavenegar.Core; + +internal class ReturnStatusLocalMessageId +{ + public Result result { get; set; } + public List entries { get; set; } +} \ No newline at end of file diff --git a/Kavenegar.Core/SendMessageRequest.cs b/Kavenegar.Core/SendMessageRequest.cs new file mode 100644 index 0000000..4c7b0e2 --- /dev/null +++ b/Kavenegar.Core/SendMessageRequest.cs @@ -0,0 +1,12 @@ +using Kavenegar.Core.Models.Enums; + +namespace Kavenegar.Core; + +public class SendMessageRequest +{ + public string Sender { get; set; } = null!; + public string Receptor { get; set; } = null!; + public string Message { get; set; } = null!; + public MessageType? Type { get; set; } + public string? LocalMessageId { get; set; } +} \ No newline at end of file diff --git a/Kavenegar.Core/Utils/DateHelper.cs b/Kavenegar.Core/Utils/DateHelper.cs index 0efa7e9..18bf5b2 100644 --- a/Kavenegar.Core/Utils/DateHelper.cs +++ b/Kavenegar.Core/Utils/DateHelper.cs @@ -1,32 +1,37 @@ using System; -using System.Globalization; -namespace Kavenegar.Core.Utils + +namespace Kavenegar.Core.Utils; + +public static class DateHelper { - public class DateHelper - { - public static DateTime UnixTimestampToDateTime(long unixTimeStamp) - { - try - { - return (new DateTime(1970, 1, 1, 0, 0, 0)).AddSeconds(unixTimeStamp); - } - catch - { - return DateTime.MaxValue; - } - } - public static long DateTimeToUnixTimestamp(DateTime idateTime) - { - try - { - idateTime = new DateTime(idateTime.Year, idateTime.Month, idateTime.Day, idateTime.Hour, idateTime.Minute, idateTime.Second); - TimeSpan unixTimeSpan = (idateTime - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local).ToLocalTime()); - return long.Parse(unixTimeSpan.TotalSeconds.ToString(CultureInfo.InvariantCulture)); - } - catch - { - return 0; - } - } - } -} + private static DateTime _minUnixDateTime = new( + 1970, + 1, + 1, + 0, + 0, + 0, + 0, + DateTimeKind.Local); + + public static DateTime UnixTimestampToDateTime( + long unixTimeStamp) + { + return _minUnixDateTime.AddSeconds(unixTimeStamp); + } + + public static DateTime UnixTimestampToDateTime( + double unixTimeStamp) + { + return _minUnixDateTime.AddSeconds(unixTimeStamp); + } + + public static double DateTimeToUnixTimestamp( + DateTime dt) + { + if (dt < _minUnixDateTime) throw new ArgumentException("dt cannot be before min unix date time"); + + var unixTimeSpan = dt - _minUnixDateTime.ToLocalTime(); + return unixTimeSpan.TotalSeconds; + } +} \ No newline at end of file diff --git a/Kavenegar.Core/Utils/StringHelper.cs b/Kavenegar.Core/Utils/StringHelper.cs deleted file mode 100644 index 5f18b71..0000000 --- a/Kavenegar.Core/Utils/StringHelper.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Linq; -namespace Kavenegar.Core.Utils -{ - public class StringHelper - { - public static String Join(String delimeter, string[] items) - { - var result = items.Aggregate("", (current, obj) => current + (obj + ",")); - return result.Substring(0, result.Length - 1); - } - public static String Join(String delimeter, long[] items) - { - string result = items.Aggregate("", (current, obj) => current + (obj.ToString() + ",")); - return result.Substring(0, result.Length - 1); - } - } -} \ No newline at end of file diff --git a/Kavenegar.sln b/Kavenegar.sln new file mode 100644 index 0000000..65964ff --- /dev/null +++ b/Kavenegar.sln @@ -0,0 +1,27 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kavenegar.Core", "Kavenegar.Core\Kavenegar.Core.csproj", "{4B4EA3FD-4296-4A75-9A59-04BC580BC846}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Shared", "Shared", "{0E27FAE0-128A-4B33-86AC-EC949911C220}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Shared.Infrastructure", "Shared\Shared.Infrastructure\Shared.Infrastructure.csproj", "{5A102430-241D-46A1-A615-0149411194D5}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {4B4EA3FD-4296-4A75-9A59-04BC580BC846}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4B4EA3FD-4296-4A75-9A59-04BC580BC846}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4B4EA3FD-4296-4A75-9A59-04BC580BC846}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4B4EA3FD-4296-4A75-9A59-04BC580BC846}.Release|Any CPU.Build.0 = Release|Any CPU + {5A102430-241D-46A1-A615-0149411194D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5A102430-241D-46A1-A615-0149411194D5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5A102430-241D-46A1-A615-0149411194D5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5A102430-241D-46A1-A615-0149411194D5}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {5A102430-241D-46A1-A615-0149411194D5} = {0E27FAE0-128A-4B33-86AC-EC949911C220} + EndGlobalSection +EndGlobal diff --git a/Kavenegar.sln.DotSettings b/Kavenegar.sln.DotSettings new file mode 100644 index 0000000..a44ce49 --- /dev/null +++ b/Kavenegar.sln.DotSettings @@ -0,0 +1,2 @@ + + True \ No newline at end of file diff --git a/Shared/Shared.Infrastructure/HttpClientHelper.cs b/Shared/Shared.Infrastructure/HttpClientHelper.cs new file mode 100644 index 0000000..99fc939 --- /dev/null +++ b/Shared/Shared.Infrastructure/HttpClientHelper.cs @@ -0,0 +1,24 @@ +namespace Shared.Infrastructure; + +public class HttpClientHelper +{ + private readonly HttpClient _httpClient = new(); + + public async Task PostAsync( + string requestUri, + object body, + CancellationToken cancellationToken = default) + { + return await _httpClient.PostAsync( + requestUri, + await SerializeBody(body, cancellationToken), + cancellationToken); + } + + private async Task SerializeBody( + object obj, + CancellationToken cancellationToken) + { + return new StringContent(await JsonUtility.Serialize(obj, cancellationToken)); + } +} \ No newline at end of file diff --git a/Shared/Shared.Infrastructure/JsonUtility.cs b/Shared/Shared.Infrastructure/JsonUtility.cs new file mode 100644 index 0000000..c6cfd8a --- /dev/null +++ b/Shared/Shared.Infrastructure/JsonUtility.cs @@ -0,0 +1,27 @@ +using System.Text; +using System.Text.Json; + +namespace Shared.Infrastructure; + +public static class JsonUtility +{ + public static async Task Serialize( + T obj, + CancellationToken cancellationToken = default) + { + var stream = new MemoryStream(); + await JsonSerializer.SerializeAsync( + stream, + obj, + cancellationToken: cancellationToken); + var sr = new StreamReader(stream, Encoding.UTF8); + return await sr.ReadToEndAsync(); + } + + public static async Task Deserialize( + Stream json, + CancellationToken cancellationToken = default) + { + return await JsonSerializer.DeserializeAsync(json, cancellationToken: cancellationToken); + } +} \ No newline at end of file diff --git a/Shared/Shared.Infrastructure/Shared.Infrastructure.csproj b/Shared/Shared.Infrastructure/Shared.Infrastructure.csproj new file mode 100644 index 0000000..eb2460e --- /dev/null +++ b/Shared/Shared.Infrastructure/Shared.Infrastructure.csproj @@ -0,0 +1,9 @@ + + + + net6.0 + enable + enable + + + From 9db333f6a1979158621ac5df0322a1cc993f0b2b Mon Sep 17 00:00:00 2001 From: alireza995 <88311706+alireza995@users.noreply.github.com> Date: Thu, 1 Dec 2022 10:19:35 +0330 Subject: [PATCH 02/14] refactor(Solution) : relocate files relocate files and remove unnecessary files closes nothing --- Kavenegar.Core/KavenegarApi2.cs | 367 ++---------------- Kavenegar.Core/{ => Models}/Result.cs | 0 .../{ => Models}/ReturnAccountConfig.cs | 0 .../{ => Models}/ReturnAccountInfo.cs | 0 .../{ => Models}/ReturnCountInbox.cs | 0 .../{ => Models}/ReturnCountOutbox.cs | 0 .../{ => Models}/ReturnCountPostalCode.cs | 0 Kavenegar.Core/{ => Models}/ReturnReceive.cs | 0 Kavenegar.Core/{ => Models}/ReturnResult.cs | 0 Kavenegar.Core/{ => Models}/ReturnSend.cs | 0 Kavenegar.Core/{ => Models}/ReturnStatus.cs | 0 .../ReturnStatusLocalMessageId.cs | 0 .../{ => Models}/SendMessageRequest.cs | 0 Test/Program.cs | 41 -- Test/test.csproj | 10 - 15 files changed, 40 insertions(+), 378 deletions(-) rename Kavenegar.Core/{ => Models}/Result.cs (100%) rename Kavenegar.Core/{ => Models}/ReturnAccountConfig.cs (100%) rename Kavenegar.Core/{ => Models}/ReturnAccountInfo.cs (100%) rename Kavenegar.Core/{ => Models}/ReturnCountInbox.cs (100%) rename Kavenegar.Core/{ => Models}/ReturnCountOutbox.cs (100%) rename Kavenegar.Core/{ => Models}/ReturnCountPostalCode.cs (100%) rename Kavenegar.Core/{ => Models}/ReturnReceive.cs (100%) rename Kavenegar.Core/{ => Models}/ReturnResult.cs (100%) rename Kavenegar.Core/{ => Models}/ReturnSend.cs (100%) rename Kavenegar.Core/{ => Models}/ReturnStatus.cs (100%) rename Kavenegar.Core/{ => Models}/ReturnStatusLocalMessageId.cs (100%) rename Kavenegar.Core/{ => Models}/SendMessageRequest.cs (100%) delete mode 100644 Test/Program.cs delete mode 100644 Test/test.csproj diff --git a/Kavenegar.Core/KavenegarApi2.cs b/Kavenegar.Core/KavenegarApi2.cs index fc54c23..e7a429e 100644 --- a/Kavenegar.Core/KavenegarApi2.cs +++ b/Kavenegar.Core/KavenegarApi2.cs @@ -6,311 +6,106 @@ namespace Kavenegar.Core; -class KavenegarApi2 : IKavenegarApi +class KavenegarApi2 : IKavenegarApi2 { - public KavenegarApi2( - string apiKey) - { - ApiKey = apiKey; - } - - public string ApiKey { get; set; } - - public Task> Send( - string sender, - List receptor, - string message) - { - throw new NotImplementedException(); - } - - public Task Send( - string sender, - string receptor, - string message) - { - throw new NotImplementedException(); - } - - public Task Send( - string sender, - string receptor, - string message, - MessageType type, - DateTime date) - { - throw new NotImplementedException(); - } - - public Task> Send( - string sender, - List receptor, - string message, - MessageType type, - DateTime date) - { - throw new NotImplementedException(); - } - - public Task Send( - string sender, - string receptor, - string message, - MessageType type, - DateTime date, - string localId) - { - throw new NotImplementedException(); - } - - public Task Send( - string sender, - string receptor, - string message, - string localId) - { - throw new NotImplementedException(); - } - - public Task> Send( - string sender, - List receptors, - string message, - string localId) - { - throw new NotImplementedException(); - } + public string ApiKey { get; set; } = null!; public Task> Send( - string sender, - List receptor, - string message, - MessageType type, - DateTime date, - List localIds) + SendMessageRequest message, + DateTime? date + ) { throw new NotImplementedException(); } public Task> SendArray( - List senders, - List receptors, - List messages) + List messages, + DateTime? date + ) { throw new NotImplementedException(); } - public Task> SendArray( - string sender, - List receptors, - List messages, - MessageType type, - DateTime date) + public Task Status(string messageId) { throw new NotImplementedException(); } - public Task> SendArray( - string sender, - List receptors, - List messages, - MessageType type, - DateTime date, - string localMessageIds) + public Task> Status(List messageIds) { throw new NotImplementedException(); } - public Task> SendArray( - string sender, - List receptors, - List messages, - string localMessageId) + public Task StatusLocalMessageId(string messageId) { throw new NotImplementedException(); } - public Task> SendArray( - List senders, - List receptors, - List messages, - string localMessageId) + public Task> StatusLocalMessageId(List messageIds) { throw new NotImplementedException(); } - public Task> SendArray( - List senders, - List receptors, - List messages, - List types, - DateTime date, - List localMessageIds) - { - throw new NotImplementedException(); - } - - public Task> Status( - List messageIds) - { - throw new NotImplementedException(); - } - - public Task Status( - string messageId) - { - throw new NotImplementedException(); - } - - public Task> StatusLocalMessageId( - List messageIds) - { - throw new NotImplementedException(); - } - - public Task StatusLocalMessageId( - string messageId) - { - throw new NotImplementedException(); - } - - public Task> Select( - List messageIds) + public Task Select(string messageId) { throw new NotImplementedException(); } - public Task Select( - string messageId) - { - throw new NotImplementedException(); - } - - public Task> SelectOutbox( - DateTime startDate) - { - throw new NotImplementedException(); - } - - public Task> SelectOutbox( - DateTime startDate, - DateTime endDate) + public Task> Select(List messageIds) { throw new NotImplementedException(); } public Task> SelectOutbox( DateTime startDate, - DateTime endDate, - string sender) - { - throw new NotImplementedException(); - } - - public Task> LatestOutbox( - long pageSize) + DateTime? endDate, + string? sender + ) { throw new NotImplementedException(); } public Task> LatestOutbox( - long pageSize, - string sender) - { - throw new NotImplementedException(); - } - - public Task CountOutbox( - DateTime startDate) + long? pageSize, + string? sender + ) { throw new NotImplementedException(); } public Task CountOutbox( DateTime startDate, - DateTime endDate) + DateTime? endDate, + int? status + ) { throw new NotImplementedException(); } - public Task CountOutbox( - DateTime startDate, - DateTime endDate, - int status) + public Task Cancel(string messageId) { throw new NotImplementedException(); } - public Task> Cancel( - List ids) - { - throw new NotImplementedException(); - } - - public Task Cancel( - string messageId) + public Task> Cancel(List ids) { throw new NotImplementedException(); } public Task> Receive( string line, - int isRead) + int isRead + ) { throw new NotImplementedException(); } public Task CountInbox( DateTime startDate, - string lineNumber) - { - throw new NotImplementedException(); - } - - public Task CountInbox( - DateTime startDate, - DateTime endDate, - string lineNumber) - { - throw new NotImplementedException(); - } - - public Task CountInbox( - DateTime startDate, - DateTime endDate, - string lineNumber, - int isRead) - { - throw new NotImplementedException(); - } - - public Task> CountPostalCode( - long postalcode) - { - throw new NotImplementedException(); - } - - public Task> SendByPostalCode( - long postalcode, - string sender, - string message, - long mciStartIndex, - long mciCount, - long mtnStartIndex, - long mtnCount) - { - throw new NotImplementedException(); - } - - public Task> SendByPostalCode( - long postalcode, - string sender, - string message, - long mciStartIndex, - long mciCount, - long mtnStartIndex, - long mtnCount, - DateTime date) + DateTime? endDate, + string? lineNumber, + int? isRead + ) { throw new NotImplementedException(); } @@ -326,104 +121,22 @@ public Task AccountConfig( string debugMode, string defaultSender, int? minCreditAlarm, - string resendFailed) - { - throw new NotImplementedException(); - } - - public Task VerifyLookup( - string receptor, - string token, - string template) - { - throw new NotImplementedException(); - } - - public Task VerifyLookup( - string receptor, - string token, - string template, - VerifyLookupType type) + string resendFailed + ) { throw new NotImplementedException(); } public Task VerifyLookup( string receptor, - string token, - string token2, - string token3, - string template) - { - throw new NotImplementedException(); - } - - public Task VerifyLookup( - string receptor, - string token, - string token2, - string token3, - string token10, - string template) - { - throw new NotImplementedException(); - } - - public Task VerifyLookup( - string receptor, - string token, - string token2, - string token3, string template, - VerifyLookupType type) - { - throw new NotImplementedException(); - } - - public Task VerifyLookup( - string receptor, - string token, - string token2, - string token3, - string token10, - string template, - VerifyLookupType type) - { - throw new NotImplementedException(); - } - - public Task VerifyLookup( - string receptor, - string token, - string token2, - string token3, - string token10, - string token20, - string template, - VerifyLookupType type) - { - throw new NotImplementedException(); - } - - public Task CallMakeTts( - string message, - string receptor) - { - throw new NotImplementedException(); - } - - public Task> CallMakeTts( - string message, - List receptor) - { - throw new NotImplementedException(); - } - - public Task> CallMakeTts( - string message, - List receptor, - DateTime? date, - List localId) + string token1, + string? token2, + string? token3, + string? token4, + string? token5, + VerifyLookupType? type + ) { throw new NotImplementedException(); } diff --git a/Kavenegar.Core/Result.cs b/Kavenegar.Core/Models/Result.cs similarity index 100% rename from Kavenegar.Core/Result.cs rename to Kavenegar.Core/Models/Result.cs diff --git a/Kavenegar.Core/ReturnAccountConfig.cs b/Kavenegar.Core/Models/ReturnAccountConfig.cs similarity index 100% rename from Kavenegar.Core/ReturnAccountConfig.cs rename to Kavenegar.Core/Models/ReturnAccountConfig.cs diff --git a/Kavenegar.Core/ReturnAccountInfo.cs b/Kavenegar.Core/Models/ReturnAccountInfo.cs similarity index 100% rename from Kavenegar.Core/ReturnAccountInfo.cs rename to Kavenegar.Core/Models/ReturnAccountInfo.cs diff --git a/Kavenegar.Core/ReturnCountInbox.cs b/Kavenegar.Core/Models/ReturnCountInbox.cs similarity index 100% rename from Kavenegar.Core/ReturnCountInbox.cs rename to Kavenegar.Core/Models/ReturnCountInbox.cs diff --git a/Kavenegar.Core/ReturnCountOutbox.cs b/Kavenegar.Core/Models/ReturnCountOutbox.cs similarity index 100% rename from Kavenegar.Core/ReturnCountOutbox.cs rename to Kavenegar.Core/Models/ReturnCountOutbox.cs diff --git a/Kavenegar.Core/ReturnCountPostalCode.cs b/Kavenegar.Core/Models/ReturnCountPostalCode.cs similarity index 100% rename from Kavenegar.Core/ReturnCountPostalCode.cs rename to Kavenegar.Core/Models/ReturnCountPostalCode.cs diff --git a/Kavenegar.Core/ReturnReceive.cs b/Kavenegar.Core/Models/ReturnReceive.cs similarity index 100% rename from Kavenegar.Core/ReturnReceive.cs rename to Kavenegar.Core/Models/ReturnReceive.cs diff --git a/Kavenegar.Core/ReturnResult.cs b/Kavenegar.Core/Models/ReturnResult.cs similarity index 100% rename from Kavenegar.Core/ReturnResult.cs rename to Kavenegar.Core/Models/ReturnResult.cs diff --git a/Kavenegar.Core/ReturnSend.cs b/Kavenegar.Core/Models/ReturnSend.cs similarity index 100% rename from Kavenegar.Core/ReturnSend.cs rename to Kavenegar.Core/Models/ReturnSend.cs diff --git a/Kavenegar.Core/ReturnStatus.cs b/Kavenegar.Core/Models/ReturnStatus.cs similarity index 100% rename from Kavenegar.Core/ReturnStatus.cs rename to Kavenegar.Core/Models/ReturnStatus.cs diff --git a/Kavenegar.Core/ReturnStatusLocalMessageId.cs b/Kavenegar.Core/Models/ReturnStatusLocalMessageId.cs similarity index 100% rename from Kavenegar.Core/ReturnStatusLocalMessageId.cs rename to Kavenegar.Core/Models/ReturnStatusLocalMessageId.cs diff --git a/Kavenegar.Core/SendMessageRequest.cs b/Kavenegar.Core/Models/SendMessageRequest.cs similarity index 100% rename from Kavenegar.Core/SendMessageRequest.cs rename to Kavenegar.Core/Models/SendMessageRequest.cs diff --git a/Test/Program.cs b/Test/Program.cs deleted file mode 100644 index 2ef3714..0000000 --- a/Test/Program.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using Kavenegar; -using Kavenegar.Core.Exceptions; - -namespace test -{ - class Program - { - static async Task Main() - { - Console.OutputEncoding = Encoding.UTF8; - try - { - var receptors = new List { "" }; - - var api = new KavenegarApi(""); - - var result = await api.Send("", receptors, ""); - - foreach (var r in result) - { - Console.Write($"{r.Messageid.ToString()}"); - } - - } - catch (ApiException ex) - { - // در صورتی که خروجی وب سرویس 200 نباشد این خطارخ می دهد. - Console.Write("Message : " + ex.Message); - } - catch (HttpException ex) - { - // در زمانی که مشکلی در برقرای ارتباط با وب سرویس وجود داشته باشد این خطا رخ می دهد - Console.Write("Message : " + ex.Message); - } - } - } -} diff --git a/Test/test.csproj b/Test/test.csproj deleted file mode 100644 index fa6cd6c..0000000 --- a/Test/test.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - Exe - latest - netcoreapp2.0 - - - - - \ No newline at end of file From 1397eae59e8ded5a30acbad6cbcf2297411b6c35 Mon Sep 17 00:00:00 2001 From: alireza995 <88311706+alireza995@users.noreply.github.com> Date: Sat, 3 Dec 2022 01:34:11 +0330 Subject: [PATCH 03/14] refactor(Solution) : create new api recreate kavenegarapi closes nothing --- Kavenegar.Core/Core/MappingProfiles.cs | 87 ++++ Kavenegar.Core/DependencyManager.cs | 13 + Kavenegar.Core/Dto/ResultDto.cs | 13 + Kavenegar.Core/IKavenegarApi2.cs | 69 +-- Kavenegar.Core/Kavenegar.Core.csproj | 13 +- Kavenegar.Core/KavenegarApi.cs | 82 ++-- Kavenegar.Core/KavenegarApi2.cs | 440 +++++++++++++++--- Kavenegar.Core/Models/AccountInfoResult.cs | 2 +- Kavenegar.Core/Models/Enums/MessageStatus.cs | 3 +- Kavenegar.Core/Models/MessageInfo.cs | 11 + Kavenegar.Core/Models/ReceiveResult.cs | 2 +- Kavenegar.Core/Models/Result.cs | 6 +- Kavenegar.Core/Models/ReturnResult.cs | 4 +- Kavenegar.Core/Models/SendMessageRequest.cs | 12 - .../Models/SendMultiMessageRequest.cs | 11 + .../Models/SendMultiMessageRequestDto.cs | 27 ++ Kavenegar.Core/Models/SendResult.cs | 29 +- .../Models/SendSingleMessageRequest.cs | 12 + .../Models/SendSingleMessageRequestDto.cs | 27 ++ Kavenegar.Core/Utils/DateHelper.cs | 22 +- .../Shared.Infrastructure/HttpClientHelper.cs | 15 +- Shared/Shared.Infrastructure/JsonUtility.cs | 18 +- .../Shared.Infrastructure/QueryParamHelper.cs | 35 ++ 23 files changed, 754 insertions(+), 199 deletions(-) create mode 100644 Kavenegar.Core/Core/MappingProfiles.cs create mode 100644 Kavenegar.Core/DependencyManager.cs create mode 100644 Kavenegar.Core/Dto/ResultDto.cs create mode 100644 Kavenegar.Core/Models/MessageInfo.cs delete mode 100644 Kavenegar.Core/Models/SendMessageRequest.cs create mode 100644 Kavenegar.Core/Models/SendMultiMessageRequest.cs create mode 100644 Kavenegar.Core/Models/SendMultiMessageRequestDto.cs create mode 100644 Kavenegar.Core/Models/SendSingleMessageRequest.cs create mode 100644 Kavenegar.Core/Models/SendSingleMessageRequestDto.cs create mode 100644 Shared/Shared.Infrastructure/QueryParamHelper.cs diff --git a/Kavenegar.Core/Core/MappingProfiles.cs b/Kavenegar.Core/Core/MappingProfiles.cs new file mode 100644 index 0000000..dba50af --- /dev/null +++ b/Kavenegar.Core/Core/MappingProfiles.cs @@ -0,0 +1,87 @@ +using System.Linq; +using System.Net; +using AutoMapper; +using Kavenegar.Core.Models; +using Kavenegar.Core.Utils; +using Shared.Infrastructure; + +namespace Kavenegar.Core.Core; + +public class MappingProfiles : Profile +{ + public MappingProfiles() + { + CreateMap() + .ForMember( + sendSingleMessageRequestDto => sendSingleMessageRequestDto.Receptors, + memberConfigurationExpression => memberConfigurationExpression.MapFrom( + sendSingleMessageRequest => string.Join(',', sendSingleMessageRequest.Receptors))) + .ForMember( + sendSingleMessageRequestDto => sendSingleMessageRequestDto.Sender, + memberConfigurationExpression => memberConfigurationExpression.MapFrom( + sendSingleMessageRequest => sendSingleMessageRequest.MessageInfo.Sender)) + .ForMember( + sendSingleMessageRequestDto => sendSingleMessageRequestDto.Message, + memberConfigurationExpression => memberConfigurationExpression.MapFrom( + sendSingleMessageRequest => WebUtility.HtmlEncode(sendSingleMessageRequest.MessageInfo.Message))) + .ForMember( + sendSingleMessageRequestDto => sendSingleMessageRequestDto.Date, + memberConfigurationExpression => memberConfigurationExpression.MapFrom( + sendSingleMessageRequest => sendSingleMessageRequest.Date.ToUnixTimestamp())) + .ForMember( + sendSingleMessageRequestDto => sendSingleMessageRequestDto.Type, + memberConfigurationExpression => memberConfigurationExpression.MapFrom( + sendSingleMessageRequest => (int)sendSingleMessageRequest.MessageInfo.Type)) + .ForMember( + sendSingleMessageRequestDto => sendSingleMessageRequestDto.LocalMessageId, + memberConfigurationExpression => memberConfigurationExpression.MapFrom( + sendSingleMessageRequest => sendSingleMessageRequest.MessageInfo.LocalMessageId)) + .ForMember( + sendSingleMessageRequestDto => sendSingleMessageRequestDto.Hide, + memberConfigurationExpression => memberConfigurationExpression.MapFrom( + sendSingleMessageRequest => sendSingleMessageRequest.Hide ? 1 : 0)); + + CreateMap() + .ForMember( + sendMultiMessageRequestDto => sendMultiMessageRequestDto.Receptors, + memberConfigurationExpression => memberConfigurationExpression.MapFrom( + sendSingleMessageRequest => sendSingleMessageRequest.Messages.Keys.ToList().Serialize(default))) + .ForMember( + sendMultiMessageRequestDto => sendMultiMessageRequestDto.Sender, + memberConfigurationExpression => memberConfigurationExpression.MapFrom( + sendMultiMessageRequest => sendMultiMessageRequest.Messages.Values + .Select(messageInfo => messageInfo.Sender) + .ToList() + .Serialize(default) + .Result)) + .ForMember( + sendMultiMessageRequestDto => sendMultiMessageRequestDto.Message, + memberConfigurationExpression => memberConfigurationExpression.MapFrom( + sendMultiMessageRequest => sendMultiMessageRequest.Messages.Values + .Select(messageInfo => WebUtility.HtmlEncode(messageInfo.Message)) + .ToList() + .Serialize(default))) + .ForMember( + sendMultiMessageRequestDto => sendMultiMessageRequestDto.Date, + memberConfigurationExpression => memberConfigurationExpression.MapFrom( + sendMultiMessageRequest => sendMultiMessageRequest.Date.ToUnixTimestamp())) + .ForMember( + sendMultiMessageRequestDto => sendMultiMessageRequestDto.Type, + memberConfigurationExpression => memberConfigurationExpression.MapFrom( + sendMultiMessageRequest => sendMultiMessageRequest.Messages.Values + .Select(messageInfo => (int)messageInfo.Type) + .ToList() + .Serialize(default))) + .ForMember( + sendMultiMessageRequestDto => sendMultiMessageRequestDto.LocalMessageId, + memberConfigurationExpression => memberConfigurationExpression.MapFrom( + sendMultiMessageRequest => sendMultiMessageRequest.Messages.Values + .Select(messageInfo => messageInfo.LocalMessageId) + .ToList() + .Serialize(default))) + .ForMember( + sendMultiMessageRequestDto => sendMultiMessageRequestDto.Hide, + memberConfigurationExpression => memberConfigurationExpression.MapFrom( + sendMultiMessageRequest => sendMultiMessageRequest.Hide ? 1 : 0)); + } +} \ No newline at end of file diff --git a/Kavenegar.Core/DependencyManager.cs b/Kavenegar.Core/DependencyManager.cs new file mode 100644 index 0000000..c771f2d --- /dev/null +++ b/Kavenegar.Core/DependencyManager.cs @@ -0,0 +1,13 @@ +using Kavenegar.Core.Core; +using Microsoft.Extensions.DependencyInjection; + +namespace Kavenegar.Core; + +public static class DependencyManager +{ + public static IServiceCollection AddKavenegar( + this IServiceCollection serviceCollection) + { + return serviceCollection.AddAutoMapper(typeof(MappingProfiles).Assembly); + } +} \ No newline at end of file diff --git a/Kavenegar.Core/Dto/ResultDto.cs b/Kavenegar.Core/Dto/ResultDto.cs new file mode 100644 index 0000000..08b2cca --- /dev/null +++ b/Kavenegar.Core/Dto/ResultDto.cs @@ -0,0 +1,13 @@ +using Kavenegar.Core.Models; +using Newtonsoft.Json; + +namespace Kavenegar.Core.Dto; + +internal class ResultDto +{ + [JsonProperty("return")] + public Result Result { get; set; } = null!; + + [JsonProperty("entries")] + public T Value { get; set; } = default!; +} \ No newline at end of file diff --git a/Kavenegar.Core/IKavenegarApi2.cs b/Kavenegar.Core/IKavenegarApi2.cs index ab9d370..a270655 100644 --- a/Kavenegar.Core/IKavenegarApi2.cs +++ b/Kavenegar.Core/IKavenegarApi2.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; using Kavenegar.Core.Models; using Kavenegar.Core.Models.Enums; @@ -8,65 +9,77 @@ namespace Kavenegar.Core; public interface IKavenegarApi2 { - string ApiKey { set; get; } + Task Send( + SendSingleMessageRequest message, + CancellationToken cancellationToken = default); Task> Send( - SendMessageRequest message, - DateTime? date); - - Task> SendArray( - List messages, - DateTime? date); + SendMultiMessageRequest messages, + CancellationToken cancellationToken = default); Task Status( - string messageId); + string messageId, + CancellationToken cancellationToken = default); Task> Status( - List messageIds); + List messageIds, + CancellationToken cancellationToken = default); Task StatusLocalMessageId( - string messageId); + string messageId, + CancellationToken cancellationToken = default); Task> StatusLocalMessageId( - List messageIds); + List messageIds, + CancellationToken cancellationToken = default); Task Select( - string messageId); + string messageId, + CancellationToken cancellationToken = default); Task> Select( - List messageIds); + List messageIds, + CancellationToken cancellationToken = default); Task> SelectOutbox( DateTime startDate, DateTime? endDate, - string? sender); + string? sender, + CancellationToken cancellationToken = default); Task> LatestOutbox( long? pageSize, - string? sender); + string? sender, + CancellationToken cancellationToken = default); Task CountOutbox( DateTime startDate, DateTime? endDate, - int? status); + int? status, + CancellationToken cancellationToken = default); Task Cancel( - string messageId); + string messageId, + CancellationToken cancellationToken = default); Task> Cancel( - List ids); + List ids, + CancellationToken cancellationToken = default); Task> Receive( string line, - int isRead); + bool isRead, + CancellationToken cancellationToken = default); Task CountInbox( DateTime startDate, DateTime? endDate, string? lineNumber, - int? isRead); + bool? isRead, + CancellationToken cancellationToken = default); - Task AccountInfo(); + Task AccountInfo( + CancellationToken cancellationToken = default); Task AccountConfig( string apiLogs, @@ -74,15 +87,17 @@ Task AccountConfig( string debugMode, string defaultSender, int? minCreditAlarm, - string resendFailed); + string resendFailed, + CancellationToken cancellationToken = default); Task VerifyLookup( string receptor, string template, string token1, - string? token2, - string? token3, - string? token4, - string? token5, - VerifyLookupType? type); + string? token2 = null, + string? token3 = null, + string? token4 = null, + string? token5 = null, + VerifyLookupType? type = null, + CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Kavenegar.Core/Kavenegar.Core.csproj b/Kavenegar.Core/Kavenegar.Core.csproj index 752fb60..cea0371 100644 --- a/Kavenegar.Core/Kavenegar.Core.csproj +++ b/Kavenegar.Core/Kavenegar.Core.csproj @@ -2,15 +2,12 @@ 1.0.5 - - net6.0;net6.0-windows;netstandard1.2;netstandard1.3;netstandard1.4;netstandard1.5;netstandard1.6;netstandard2.0 A cross-platform library for the kavenegar sms provider; written in C# Kavenegar.Core Kavenegar.Core KavenegarDotNetCore Kavenegar Core kavenegar.Core kavenegarCore Sms - https://github.com/kavenegar/Kavenegar.Core Library @@ -20,15 +17,21 @@ git https://github.com/kavenegar/Kavenegar.Core Kavenegar - true 11 enable + net6.0 - + + + + + + + diff --git a/Kavenegar.Core/KavenegarApi.cs b/Kavenegar.Core/KavenegarApi.cs index 0f76bbf..4d9baf8 100644 --- a/Kavenegar.Core/KavenegarApi.cs +++ b/Kavenegar.Core/KavenegarApi.cs @@ -31,37 +31,6 @@ public KavenegarApi( public string ApiKey { set; get; } - private string GetApiPath( - string @base, - string method, - string output) - { - return string.Format( - ApiPath, - @base, - method, - output); - } - - private async Task Execute( - string path, - Dictionary @params) - { - var nvc = @params?.Select(x => new KeyValuePair(x.Key, x.Value?.ToString())); - - var postdata = new FormUrlEncodedContent(nvc); - - var response = await _client.PostAsync(path, postdata); - var responseBody = await response.Content.ReadAsStringAsync(); - - var result = JsonConvert.DeserializeObject(responseBody); - - if (response.StatusCode != HttpStatusCode.OK) - throw new ApiException(result.Return.message, result.Return.status); - - return responseBody; - } - public async Task> Send( string sender, List receptor, @@ -207,7 +176,7 @@ public async Task> Send( "type", (int)type }, { - "date", date == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(date) + "date", date == DateTime.MinValue ? 0 : date.ToUnixTimestamp() } }; if (localIds != null && @@ -344,7 +313,7 @@ public async Task> SendArray( "type", jsonTypes }, { - "date", date == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(date) + "date", date == DateTime.MinValue ? 0 : date.ToUnixTimestamp() } }; if (localMessageIds != null && @@ -474,10 +443,10 @@ public async Task> SelectOutbox( var param = new Dictionary { { - "startDate", startDate == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(startDate) + "startDate", startDate == DateTime.MinValue ? 0 : startDate.ToUnixTimestamp() }, { - "endDate", endDate == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(endDate) + "endDate", endDate == DateTime.MinValue ? 0 : endDate.ToUnixTimestamp() }, { "sender", sender @@ -547,10 +516,10 @@ public async Task CountOutbox( var param = new Dictionary { { - "startDate", startDate == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(startDate) + "startDate", startDate == DateTime.MinValue ? 0 : startDate.ToUnixTimestamp() }, { - "endDate", endDate == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(endDate) + "endDate", endDate == DateTime.MinValue ? 0 : endDate.ToUnixTimestamp() }, { "status", status @@ -652,10 +621,10 @@ public async Task CountInbox( var param = new Dictionary { { - "startDate", startDate == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(startDate) + "startDate", startDate == DateTime.MinValue ? 0 : startDate.ToUnixTimestamp() }, { - "endDate", endDate == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(endDate) + "endDate", endDate == DateTime.MinValue ? 0 : endDate.ToUnixTimestamp() }, { "lineNumber", lineNumber @@ -745,7 +714,7 @@ public async Task> SendByPostalCode( "mtnCount", mtnCount }, { - "date", date == DateTime.MinValue ? 0 : DateHelper.DateTimeToUnixTimestamp(date) + "date", date == DateTime.MinValue ? 0 : date.ToUnixTimestamp() } }; var responsebody = await Execute(path, param); @@ -949,6 +918,37 @@ public async Task VerifyLookup( return l.entries[0]; } + private string GetApiPath( + string @base, + string method, + string output) + { + return string.Format( + ApiPath, + @base, + method, + output); + } + + private async Task Execute( + string path, + Dictionary @params) + { + var nvc = @params?.Select(x => new KeyValuePair(x.Key, x.Value?.ToString())); + + var postdata = new FormUrlEncodedContent(nvc); + + var response = await _client.PostAsync(path, postdata); + var responseBody = await response.Content.ReadAsStringAsync(); + + var result = JsonConvert.DeserializeObject(responseBody); + + if (response.StatusCode != HttpStatusCode.OK) + throw new ApiException(result.Return.Message, result.Return.Status); + + return responseBody; + } + #region << CallMakeTts >> @@ -996,7 +996,7 @@ public async Task> CallMakeTts( "message", WebUtility.HtmlEncode(message) } }; - if (date != null) param.Add("date", DateHelper.DateTimeToUnixTimestamp(date.Value)); + if (date != null) param.Add("date", date.Value.ToUnixTimestamp()); if (localId != null && localId.Count > 0) param.Add("localId", string.Join(",", localId)); diff --git a/Kavenegar.Core/KavenegarApi2.cs b/Kavenegar.Core/KavenegarApi2.cs index e7a429e..5f4860f 100644 --- a/Kavenegar.Core/KavenegarApi2.cs +++ b/Kavenegar.Core/KavenegarApi2.cs @@ -1,143 +1,449 @@ using System; using System.Collections.Generic; +using System.Linq; +using System.Threading; using System.Threading.Tasks; +using AutoMapper; +using Kavenegar.Core.Dto; using Kavenegar.Core.Models; using Kavenegar.Core.Models.Enums; +using Kavenegar.Core.Utils; +using Shared.Infrastructure; namespace Kavenegar.Core; -class KavenegarApi2 : IKavenegarApi2 +internal class KavenegarApi2 : IKavenegarApi2 { - public string ApiKey { get; set; } = null!; + private readonly HttpClientHelper _httpClientHelper; + private readonly IMapper _mapper; - public Task> Send( - SendMessageRequest message, - DateTime? date - ) + public KavenegarApi2( + string apiKey, + IMapper mapper) { - throw new NotImplementedException(); + _mapper = mapper; + _httpClientHelper = new HttpClientHelper + { + BaseAddress = $"https://api.kavenegar.com/v1/{apiKey}" + }; } - public Task> SendArray( - List messages, - DateTime? date - ) + public async Task Send( + SendSingleMessageRequest message, + CancellationToken cancellationToken = default) { - throw new NotImplementedException(); + var requestParams = _mapper.Map(message).ParametrizeObject(); + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/send.json", + null, + requestParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))!.Value + .FirstOrDefault(); } - public Task Status(string messageId) + public async Task> Send( + SendMultiMessageRequest messages, + CancellationToken cancellationToken = default) { - throw new NotImplementedException(); + var requestParams = _mapper.Map(messages).ParametrizeObject(); + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/send.json", + null, + requestParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))!.Value; } - public Task> Status(List messageIds) + public async Task Status( + string messageId, + CancellationToken cancellationToken = default) { - throw new NotImplementedException(); + return (await Status( + new List + { + messageId + }, + cancellationToken)).FirstOrDefault()!; } - public Task StatusLocalMessageId(string messageId) + public async Task> Status( + List messageIds, + CancellationToken cancellationToken = default) { - throw new NotImplementedException(); + var queryParams = new Dictionary + { + { + "messageid", string.Join(',', messageIds) + } + }; + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/status.json", + null, + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? + new List(); } - public Task> StatusLocalMessageId(List messageIds) + public async Task StatusLocalMessageId( + string messageId, + CancellationToken cancellationToken = default) { - throw new NotImplementedException(); + return (await StatusLocalMessageId( + new List + { + messageId + }, + cancellationToken)).FirstOrDefault()!; } - public Task Select(string messageId) + public async Task> StatusLocalMessageId( + List messageIds, + CancellationToken cancellationToken = default) { - throw new NotImplementedException(); + var queryParams = new Dictionary + { + { + "messageid", string.Join(',', messageIds) + } + }; + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/statuslocalmessageid.json", + null, + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken)) + ?.Value ?? + new List(); } - public Task> Select(List messageIds) + public async Task Select( + string messageId, + CancellationToken cancellationToken = default) { - throw new NotImplementedException(); + return (await Select( + new List + { + messageId + }, + cancellationToken)).FirstOrDefault()!; } - public Task> SelectOutbox( + public async Task> Select( + List messageIds, + CancellationToken cancellationToken = default) + { + var queryParams = new Dictionary + { + { + "messageid", string.Join(',', messageIds) + } + }; + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/select.json", + null, + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? + new List(); + } + + public async Task> SelectOutbox( DateTime startDate, DateTime? endDate, - string? sender - ) + string? sender, + CancellationToken cancellationToken = default) { - throw new NotImplementedException(); + if (endDate <= startDate) throw new ArgumentException("تاریخ پایان نباید از تاریخ شروع کوچکتر باشد."); + + if ((endDate - startDate)!.Value.TotalDays > 1) + throw new ArgumentException( + "حداکثر فاصله زمانی بین متغیر startdate تا متغیر enddate برابر با 1 روز می باشد."); + + if (startDate < DateTime.Now.AddDays(-60)) + throw new ArgumentException("تاریخ شروع startdate حداکثر باید تا 60 روز قبل باشد."); + + var queryParams = new Dictionary + { + { + "startdate", startDate.ToUnixTimestamp() + } + }; + + if (endDate.HasValue) queryParams.Add("endate", endDate.Value.ToUnixTimestamp()); + + if (string.IsNullOrWhiteSpace(sender)) queryParams.Add("sender", sender); + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/selectoutbox.json", + null, + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? + new List(); } - public Task> LatestOutbox( + public async Task> LatestOutbox( long? pageSize, - string? sender - ) + string? sender, + CancellationToken cancellationToken = default) { - throw new NotImplementedException(); + if (pageSize is > 500) throw new ArgumentException("تعداد رکورد های خروجی این متد حداکثر 500 رکورد می‌باشد."); + + pageSize ??= 500; + + var queryParams = new Dictionary + { + { + "pagesize", pageSize + } + }; + + if (string.IsNullOrWhiteSpace(sender)) queryParams.Add("sender", sender); + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/latestoutbox.json", + null, + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? + new List(); } - public Task CountOutbox( + public async Task CountOutbox( DateTime startDate, DateTime? endDate, - int? status - ) + int? status, + CancellationToken cancellationToken = default) { - throw new NotImplementedException(); + if (endDate <= startDate) throw new ArgumentException("تاریخ پایان نباید از تاریخ شروع کوچکتر باشد."); + + if ((endDate - startDate)!.Value.TotalDays > 1) + throw new ArgumentException( + "حداکثر فاصله زمانی بین متغیر startdate تا متغیر enddate برابر با 1 روز می باشد."); + + if (startDate < DateTime.Now.AddDays(-60)) + throw new ArgumentException("تاریخ شروع startdate حداکثر باید تا 60 روز قبل باشد."); + + var queryParams = new Dictionary + { + { + "startdate", startDate.ToUnixTimestamp() + } + }; + + if (endDate.HasValue) queryParams.Add("endate", endDate.Value.ToUnixTimestamp()); + + if (status.HasValue) queryParams.Add("status", status); + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/countoutbox.json", + null, + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value + .FirstOrDefault() ?? + new CountOutboxResult(); } - public Task Cancel(string messageId) + public async Task Cancel( + string messageId, + CancellationToken cancellationToken = default) { - throw new NotImplementedException(); + return (await Cancel( + new List + { + messageId + }, + cancellationToken)).FirstOrDefault()!; } - public Task> Cancel(List ids) + public async Task> Cancel( + List ids, + CancellationToken cancellationToken = default) { - throw new NotImplementedException(); + var queryParams = new Dictionary + { + { + "messageid", string.Join(',', ids) + } + }; + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/cancel.json", + null, + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? + new List(); } - public Task> Receive( + public async Task> Receive( string line, - int isRead - ) + bool isRead, + CancellationToken cancellationToken = default) { - throw new NotImplementedException(); + var queryParams = new Dictionary + { + { + "linenumber", line + }, + { + "isread", isRead ? 1 : 0 + } + }; + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/receive.json", + null, + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? + new List(); } - public Task CountInbox( + public async Task CountInbox( DateTime startDate, DateTime? endDate, string? lineNumber, - int? isRead - ) + bool? isRead, + CancellationToken cancellationToken = default) { - throw new NotImplementedException(); + if (endDate <= startDate) throw new ArgumentException("تاریخ پایان نباید از تاریخ شروع کوچکتر باشد."); + + if ((endDate - startDate)!.Value.TotalDays > 1) + throw new ArgumentException( + "حداکثر فاصله زمانی بین متغیر startdate تا متغیر enddate برابر با 1 روز می باشد."); + + if (startDate < DateTime.Now.AddDays(-60)) + throw new ArgumentException("تاریخ شروع startdate حداکثر باید تا 60 روز قبل باشد."); + + var queryParams = new Dictionary + { + { + "startdate", startDate.ToUnixTimestamp() + } + }; + + if (endDate.HasValue) queryParams.Add("endate", endDate.Value.ToUnixTimestamp()); + if (string.IsNullOrWhiteSpace(lineNumber)) queryParams.Add("linenumber", lineNumber); + if (isRead.HasValue) queryParams.Add("isread", isRead.Value ? 1 : 0); + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/countinbox.json", + null, + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value + .FirstOrDefault() ?? + new CountOutboxResult(); } - public Task AccountInfo() + public async Task AccountInfo( + CancellationToken cancellationToken = default) { - throw new NotImplementedException(); + var httpResponseMessage = await _httpClientHelper.PostAsync( + "account/info.json", + null, + null, + cancellationToken); + + return (await httpResponseMessage.Deserialize>(cancellationToken))?.Value ?? + new AccountInfoResult(); } - public Task AccountConfig( - string apiLogs, - string dailyReport, - string debugMode, - string defaultSender, + public async Task AccountConfig( + string? apiLogs, + string? dailyReport, + string? debugMode, + string? defaultSender, int? minCreditAlarm, - string resendFailed - ) + string? resendFailed, + CancellationToken cancellationToken = default) { - throw new NotImplementedException(); + var queryParams = new Dictionary(); + + if (string.IsNullOrWhiteSpace(apiLogs)) queryParams.Add("apilogs", apiLogs); + + if (string.IsNullOrWhiteSpace(dailyReport)) queryParams.Add("dailyreport", dailyReport); + + if (string.IsNullOrWhiteSpace(debugMode)) queryParams.Add("debugmode", debugMode); + + if (string.IsNullOrWhiteSpace(defaultSender)) queryParams.Add("defaultsender", defaultSender); + + queryParams.Add("mincreditalarm", minCreditAlarm); + + if (string.IsNullOrWhiteSpace(resendFailed)) queryParams.Add("resendfailed", resendFailed); + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "account/config.json", + null, + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>(cancellationToken))?.Value ?? + new AccountConfigResult(); } - public Task VerifyLookup( + public async Task VerifyLookup( string receptor, string template, string token1, - string? token2, - string? token3, - string? token4, - string? token5, - VerifyLookupType? type - ) - { - throw new NotImplementedException(); + string? token2 = null, + string? token3 = null, + string? token4 = null, + string? token5 = null, + VerifyLookupType? type = null, + CancellationToken cancellationToken = default) + { + var queryParams = new Dictionary + { + { + "receptor", receptor + }, + { + "template", template + }, + { + "token", token1 + } + }; + + if (string.IsNullOrWhiteSpace(token2)) queryParams.Add("token2", token2); + + if (string.IsNullOrWhiteSpace(token3)) queryParams.Add("token3", token3); + + if (string.IsNullOrWhiteSpace(token4)) queryParams.Add("token10", token4); + + if (string.IsNullOrWhiteSpace(token5)) queryParams.Add("token20", token5); + + if (type.HasValue) queryParams.Add("type", type.Value.ToString()); + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "verify/lookup.json", + null, + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value + .FirstOrDefault() ?? + new SendResult(); } } \ No newline at end of file diff --git a/Kavenegar.Core/Models/AccountInfoResult.cs b/Kavenegar.Core/Models/AccountInfoResult.cs index ca13c6d..01aa475 100644 --- a/Kavenegar.Core/Models/AccountInfoResult.cs +++ b/Kavenegar.Core/Models/AccountInfoResult.cs @@ -8,7 +8,7 @@ public class AccountInfoResult public long RemainCredit { get; set; } public long Expiredate { get; set; } - public DateTime GregorianExpiredate => DateHelper.UnixTimestampToDateTime(Expiredate); + public DateTime GregorianExpiredate => Expiredate.ToDateTime(); public string Type { get; set; } } \ No newline at end of file diff --git a/Kavenegar.Core/Models/Enums/MessageStatus.cs b/Kavenegar.Core/Models/Enums/MessageStatus.cs index e0b1026..4868220 100644 --- a/Kavenegar.Core/Models/Enums/MessageStatus.cs +++ b/Kavenegar.Core/Models/Enums/MessageStatus.cs @@ -3,8 +3,9 @@ namespace Kavenegar.Core.Models.Enums; public enum MessageStatus { Queued = 1, - Schulded = 2, + Scheduled = 2, SentToCenter = 4, + AlsoSentToCenter = 5, Delivered = 10, Undelivered = 11, Canceled = 13, diff --git a/Kavenegar.Core/Models/MessageInfo.cs b/Kavenegar.Core/Models/MessageInfo.cs new file mode 100644 index 0000000..7f00171 --- /dev/null +++ b/Kavenegar.Core/Models/MessageInfo.cs @@ -0,0 +1,11 @@ +using Kavenegar.Core.Models.Enums; + +namespace Kavenegar.Core.Models; + +public class MessageInfo +{ + public string Sender { get; set; } = null!; + public string Message { get; set; } = null!; + public MessageType Type { get; set; } + public string LocalMessageId { get; set; } = null!; +} \ No newline at end of file diff --git a/Kavenegar.Core/Models/ReceiveResult.cs b/Kavenegar.Core/Models/ReceiveResult.cs index 0ac6a1e..de2f86f 100644 --- a/Kavenegar.Core/Models/ReceiveResult.cs +++ b/Kavenegar.Core/Models/ReceiveResult.cs @@ -7,7 +7,7 @@ public class ReceiveResult { public long Date { get; set; } - public DateTime GregorianDate => DateHelper.UnixTimestampToDateTime(Date); + public DateTime GregorianDate => Date.ToDateTime(); public long MessageId { get; set; } diff --git a/Kavenegar.Core/Models/Result.cs b/Kavenegar.Core/Models/Result.cs index 774f98a..34a97b7 100644 --- a/Kavenegar.Core/Models/Result.cs +++ b/Kavenegar.Core/Models/Result.cs @@ -1,7 +1,7 @@ -namespace Kavenegar.Core; +namespace Kavenegar.Core.Models; internal class Result { - public int status { get; set; } - public string message { get; set; } + public int Status { get; set; } + public string Message { get; set; } = null!; } \ No newline at end of file diff --git a/Kavenegar.Core/Models/ReturnResult.cs b/Kavenegar.Core/Models/ReturnResult.cs index a96ad42..3633bec 100644 --- a/Kavenegar.Core/Models/ReturnResult.cs +++ b/Kavenegar.Core/Models/ReturnResult.cs @@ -1,4 +1,6 @@ -namespace Kavenegar.Core; +using Kavenegar.Core.Models; + +namespace Kavenegar.Core; internal class ReturnResult { diff --git a/Kavenegar.Core/Models/SendMessageRequest.cs b/Kavenegar.Core/Models/SendMessageRequest.cs deleted file mode 100644 index 4c7b0e2..0000000 --- a/Kavenegar.Core/Models/SendMessageRequest.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Kavenegar.Core.Models.Enums; - -namespace Kavenegar.Core; - -public class SendMessageRequest -{ - public string Sender { get; set; } = null!; - public string Receptor { get; set; } = null!; - public string Message { get; set; } = null!; - public MessageType? Type { get; set; } - public string? LocalMessageId { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/SendMultiMessageRequest.cs b/Kavenegar.Core/Models/SendMultiMessageRequest.cs new file mode 100644 index 0000000..fc3df2f --- /dev/null +++ b/Kavenegar.Core/Models/SendMultiMessageRequest.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; + +namespace Kavenegar.Core.Models; + +public class SendMultiMessageRequest +{ + public Dictionary Messages { get; set; } = null!; + public DateTime Date { get; set; } + public bool Hide { get; set; } +} \ No newline at end of file diff --git a/Kavenegar.Core/Models/SendMultiMessageRequestDto.cs b/Kavenegar.Core/Models/SendMultiMessageRequestDto.cs new file mode 100644 index 0000000..4630d2d --- /dev/null +++ b/Kavenegar.Core/Models/SendMultiMessageRequestDto.cs @@ -0,0 +1,27 @@ +using System.ComponentModel.DataAnnotations.Schema; + +namespace Kavenegar.Core.Models; + +internal class SendMultiMessageRequestDto +{ + [Column("receptor", Order = 1)] + public string Receptors { get; set; } = null!; + + [Column("sender", Order = 2)] + public string? Sender { get; set; } + + [Column("message", Order = 3)] + public string Message { get; set; } = null!; + + [Column("date", Order = 4)] + public long Date { get; set; } + + [Column("type", Order = 5)] + public int Type { get; set; } + + [Column("localmessageids", Order = 6)] + public string LocalMessageId { get; set; } = null!; + + [Column("hide", Order = 7)] + public int Hide { get; set; } +} \ No newline at end of file diff --git a/Kavenegar.Core/Models/SendResult.cs b/Kavenegar.Core/Models/SendResult.cs index 64a43d4..482ca5b 100644 --- a/Kavenegar.Core/Models/SendResult.cs +++ b/Kavenegar.Core/Models/SendResult.cs @@ -1,28 +1,13 @@ -using System; -using Kavenegar.Core.Utils; - namespace Kavenegar.Core.Models; public class SendResult { - public long Messageid { get; set; } - - public int Cost { get; set; } - - public DateTime GregorianDate - { - get => DateHelper.UnixTimestampToDateTime(Date); - set => Date = DateHelper.DateTimeToUnixTimestamp(value); - } - - public double Date { get; set; } - - public string Message { get; set; } - - public string Receptor { get; set; } - - public string Sender { get; set; } + public long MessageId { get; set; } + public string Message { get; set; } = null!; public int Status { get; set; } - - public string StatusText { get; set; } + public string StatusText { get; set; } = null!; + public string Sender { get; set; } = null!; + public string Receptor { get; set; } = null!; + public long Date { get; set; } + public int Cost { get; set; } } \ No newline at end of file diff --git a/Kavenegar.Core/Models/SendSingleMessageRequest.cs b/Kavenegar.Core/Models/SendSingleMessageRequest.cs new file mode 100644 index 0000000..d856bf4 --- /dev/null +++ b/Kavenegar.Core/Models/SendSingleMessageRequest.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; + +namespace Kavenegar.Core.Models; + +public class SendSingleMessageRequest +{ + public MessageInfo MessageInfo { get; set; } = null!; + public IEnumerable Receptors { get; set; } = null!; + public DateTime Date { get; set; } + public bool Hide { get; set; } +} \ No newline at end of file diff --git a/Kavenegar.Core/Models/SendSingleMessageRequestDto.cs b/Kavenegar.Core/Models/SendSingleMessageRequestDto.cs new file mode 100644 index 0000000..a50f74e --- /dev/null +++ b/Kavenegar.Core/Models/SendSingleMessageRequestDto.cs @@ -0,0 +1,27 @@ +using System.ComponentModel.DataAnnotations.Schema; + +namespace Kavenegar.Core.Models; + +internal class SendSingleMessageRequestDto +{ + [Column("receptor", Order = 1)] + public string Receptors { get; set; } = null!; + + [Column("sender", Order = 2)] + public string? Sender { get; set; } + + [Column("message", Order = 3)] + public string Message { get; set; } = null!; + + [Column("date", Order = 4)] + public long Date { get; set; } + + [Column("type", Order = 5)] + public int Type { get; set; } + + [Column("localid", Order = 6)] + public string LocalMessageId { get; set; } = null!; + + [Column("hide", Order = 7)] + public int Hide { get; set; } +} \ No newline at end of file diff --git a/Kavenegar.Core/Utils/DateHelper.cs b/Kavenegar.Core/Utils/DateHelper.cs index 18bf5b2..c50c2a4 100644 --- a/Kavenegar.Core/Utils/DateHelper.cs +++ b/Kavenegar.Core/Utils/DateHelper.cs @@ -4,7 +4,7 @@ namespace Kavenegar.Core.Utils; public static class DateHelper { - private static DateTime _minUnixDateTime = new( + private static readonly DateTime MinUnixDateTime = new( 1970, 1, 1, @@ -14,24 +14,24 @@ public static class DateHelper 0, DateTimeKind.Local); - public static DateTime UnixTimestampToDateTime( - long unixTimeStamp) + public static DateTime ToDateTime( + this long unixTimeStamp) { - return _minUnixDateTime.AddSeconds(unixTimeStamp); + return MinUnixDateTime.AddSeconds(unixTimeStamp); } - public static DateTime UnixTimestampToDateTime( - double unixTimeStamp) + public static DateTime ToDateTime( + this double unixTimeStamp) { - return _minUnixDateTime.AddSeconds(unixTimeStamp); + return MinUnixDateTime.AddSeconds(unixTimeStamp); } - public static double DateTimeToUnixTimestamp( - DateTime dt) + public static double ToUnixTimestamp( + this DateTime dt) { - if (dt < _minUnixDateTime) throw new ArgumentException("dt cannot be before min unix date time"); + if (dt < MinUnixDateTime) throw new ArgumentException("dt cannot be before min unix date time"); - var unixTimeSpan = dt - _minUnixDateTime.ToLocalTime(); + var unixTimeSpan = dt - MinUnixDateTime.ToLocalTime(); return unixTimeSpan.TotalSeconds; } } \ No newline at end of file diff --git a/Shared/Shared.Infrastructure/HttpClientHelper.cs b/Shared/Shared.Infrastructure/HttpClientHelper.cs index 99fc939..a871bf4 100644 --- a/Shared/Shared.Infrastructure/HttpClientHelper.cs +++ b/Shared/Shared.Infrastructure/HttpClientHelper.cs @@ -4,14 +4,21 @@ public class HttpClientHelper { private readonly HttpClient _httpClient = new(); + public string BaseAddress { get; set; } = null!; + public async Task PostAsync( string requestUri, - object body, + object? body = null, + Dictionary? queryParams = null, CancellationToken cancellationToken = default) { + var address = queryParams == null ? + Path.Combine(BaseAddress, requestUri) : + QueryParamHelper.AddQueryParamToUri(Path.Combine(BaseAddress, requestUri), queryParams); + return await _httpClient.PostAsync( - requestUri, - await SerializeBody(body, cancellationToken), + address, + body == null ? null : await SerializeBody(body, cancellationToken), cancellationToken); } @@ -19,6 +26,6 @@ private async Task SerializeBody( object obj, CancellationToken cancellationToken) { - return new StringContent(await JsonUtility.Serialize(obj, cancellationToken)); + return new StringContent(await obj.Serialize(cancellationToken)); } } \ No newline at end of file diff --git a/Shared/Shared.Infrastructure/JsonUtility.cs b/Shared/Shared.Infrastructure/JsonUtility.cs index c6cfd8a..566f80c 100644 --- a/Shared/Shared.Infrastructure/JsonUtility.cs +++ b/Shared/Shared.Infrastructure/JsonUtility.cs @@ -6,7 +6,7 @@ namespace Shared.Infrastructure; public static class JsonUtility { public static async Task Serialize( - T obj, + this T obj, CancellationToken cancellationToken = default) { var stream = new MemoryStream(); @@ -14,8 +14,9 @@ await JsonSerializer.SerializeAsync( stream, obj, cancellationToken: cancellationToken); - var sr = new StreamReader(stream, Encoding.UTF8); - return await sr.ReadToEndAsync(); + + var streamReader = new StreamReader(stream, Encoding.UTF8); + return await streamReader.ReadToEndAsync(); } public static async Task Deserialize( @@ -24,4 +25,15 @@ await JsonSerializer.SerializeAsync( { return await JsonSerializer.DeserializeAsync(json, cancellationToken: cancellationToken); } + + public static async Task Deserialize( + this HttpResponseMessage httpResponseMessage, + CancellationToken cancellationToken = default) + { + var content = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken); + var stream = new MemoryStream(); + var streamWriter = new StreamWriter(stream, Encoding.UTF8); + await streamWriter.WriteAsync(content); + return await Deserialize(stream, cancellationToken); + } } \ No newline at end of file diff --git a/Shared/Shared.Infrastructure/QueryParamHelper.cs b/Shared/Shared.Infrastructure/QueryParamHelper.cs new file mode 100644 index 0000000..eed186a --- /dev/null +++ b/Shared/Shared.Infrastructure/QueryParamHelper.cs @@ -0,0 +1,35 @@ +using System.ComponentModel.DataAnnotations.Schema; +using System.Web; + +namespace Shared.Infrastructure; + +public static class QueryParamHelper +{ + public static string AddQueryParamToUri( + string requestUri, + Dictionary queryParams = null!) + { + var uriBuilder = new UriBuilder(requestUri); + var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); + foreach (var parameter in queryParams) queryString[parameter.Key] = parameter.Value?.ToString(); + + uriBuilder.Query = queryString.ToString(); + return uriBuilder.ToString(); + } + + public static Dictionary ParametrizeObject( + this T obj) + { + var properties = obj!.GetType() + .GetProperties() + .OrderBy( + propertyInfo => ((ColumnAttribute)propertyInfo.GetCustomAttributes(typeof(ColumnAttribute), false)[0]) + .Order); + + return properties.ToDictionary( + propertyInfo => + ((ColumnAttribute)propertyInfo.GetCustomAttributes(typeof(ColumnAttribute), false)[0]).Name ?? + propertyInfo.Name, + propertyInfo => propertyInfo.GetValue(obj)); + } +} \ No newline at end of file From 62109821fd4ca7d8f01475aad0731a4436ac9e4e Mon Sep 17 00:00:00 2001 From: alireza995 <88311706+alireza995@users.noreply.github.com> Date: Sat, 3 Dec 2022 03:15:35 +0330 Subject: [PATCH 04/14] refactor(Solution) : Remove unnecessary objects Remove unnecessary classes and file. Recreate csproj. Fix spelling naming problems. Add DI infrastructure. and mane more... closes nothing --- Kavenegar.Core/Core/MappingProfiles.cs | 87 -- Kavenegar.Core/DependencyManager.cs | 8 +- Kavenegar.Core/Dto/Message/MessageInfo.cs | 12 + Kavenegar.Core/Dto/Message/SendMessageInfo.cs | 8 + .../Dto/Message/SendMultiMessageRequest.cs | 8 + .../Dto/Message/SendSingleMessageRequest.cs | 14 + Kavenegar.Core/Dto/Result/AccountConfigDto.cs | 11 + Kavenegar.Core/Dto/Result/AccountInfoDto.cs | 11 + .../Result/CountInboxDto.cs} | 4 +- Kavenegar.Core/Dto/Result/CountOutboxDto.cs | 7 + Kavenegar.Core/Dto/Result/LocalStatusDto.cs | 12 + .../Dto/Result/ReceivedMessageDto.cs | 13 + Kavenegar.Core/Dto/Result/ResultDto.cs | 12 + .../Result.cs => Dto/Result/ResultStatus.cs} | 4 +- .../{Models => Dto/Result}/SendResult.cs | 2 +- Kavenegar.Core/Dto/Result/StatusMessageDto.cs | 11 + Kavenegar.Core/Dto/ResultDto.cs | 13 - .../{Models => }/Enums/MessageStatus.cs | 2 +- .../{Models => }/Enums/MessageType.cs | 2 +- Kavenegar.Core/{Models => }/Enums/MetaCode.cs | 0 .../{Models => }/Enums/VerifyLookupType.cs | 2 +- Kavenegar.Core/Exceptions/ApiException.cs | 15 - .../Exceptions/KavenegarException.cs | 11 - Kavenegar.Core/IKavenegarApi.cs | 297 +---- Kavenegar.Core/IKavenegarApi2.cs | 103 -- Kavenegar.Core/Json/JsonArray.cs | 53 - Kavenegar.Core/Json/JsonBoolean.cs | 18 - Kavenegar.Core/Json/JsonNullable.cs | 17 - Kavenegar.Core/Json/JsonNumber.cs | 18 - Kavenegar.Core/Json/JsonObject.cs | 83 -- Kavenegar.Core/Json/JsonString.cs | 18 - Kavenegar.Core/Json/Parser.cs | 481 ------- Kavenegar.Core/Kavenegar.Core.csproj | 28 +- Kavenegar.Core/KavenegarApi.cs | 1150 +++++------------ Kavenegar.Core/KavenegarApi2.cs | 449 ------- Kavenegar.Core/Models/AccountConfigResult.cs | 11 - Kavenegar.Core/Models/AccountInfoResult.cs | 14 - Kavenegar.Core/Models/CountOutboxResult.cs | 7 - .../Models/CountPostalCodeResult.cs | 7 - Kavenegar.Core/Models/MessageInfo.cs | 11 - Kavenegar.Core/Models/ReceiveResult.cs | 19 - Kavenegar.Core/Models/ReturnAccountConfig.cs | 9 - Kavenegar.Core/Models/ReturnAccountInfo.cs | 9 - Kavenegar.Core/Models/ReturnCountInbox.cs | 10 - Kavenegar.Core/Models/ReturnCountOutbox.cs | 10 - .../Models/ReturnCountPostalCode.cs | 10 - Kavenegar.Core/Models/ReturnReceive.cs | 10 - Kavenegar.Core/Models/ReturnResult.cs | 9 - Kavenegar.Core/Models/ReturnSend.cs | 10 - Kavenegar.Core/Models/ReturnStatus.cs | 10 - .../Models/ReturnStatusLocalMessageId.cs | 10 - .../Models/SendMultiMessageRequest.cs | 11 - .../Models/SendMultiMessageRequestDto.cs | 27 - .../Models/SendSingleMessageRequest.cs | 12 - .../Models/SendSingleMessageRequestDto.cs | 27 - .../Models/StatusLocalMessageIdResult.cs | 11 - Kavenegar.Core/Models/StatusResult.cs | 10 - Kavenegar.sln | 12 +- Kavenegar.sln.DotSettings | 36 +- .../Shared.Infrastructure}/DateHelper.cs | 4 +- 60 files changed, 557 insertions(+), 2743 deletions(-) delete mode 100644 Kavenegar.Core/Core/MappingProfiles.cs create mode 100644 Kavenegar.Core/Dto/Message/MessageInfo.cs create mode 100644 Kavenegar.Core/Dto/Message/SendMessageInfo.cs create mode 100644 Kavenegar.Core/Dto/Message/SendMultiMessageRequest.cs create mode 100644 Kavenegar.Core/Dto/Message/SendSingleMessageRequest.cs create mode 100644 Kavenegar.Core/Dto/Result/AccountConfigDto.cs create mode 100644 Kavenegar.Core/Dto/Result/AccountInfoDto.cs rename Kavenegar.Core/{Models/CountInboxResult.cs => Dto/Result/CountInboxDto.cs} (65%) create mode 100644 Kavenegar.Core/Dto/Result/CountOutboxDto.cs create mode 100644 Kavenegar.Core/Dto/Result/LocalStatusDto.cs create mode 100644 Kavenegar.Core/Dto/Result/ReceivedMessageDto.cs create mode 100644 Kavenegar.Core/Dto/Result/ResultDto.cs rename Kavenegar.Core/{Models/Result.cs => Dto/Result/ResultStatus.cs} (56%) rename Kavenegar.Core/{Models => Dto/Result}/SendResult.cs (90%) create mode 100644 Kavenegar.Core/Dto/Result/StatusMessageDto.cs delete mode 100644 Kavenegar.Core/Dto/ResultDto.cs rename Kavenegar.Core/{Models => }/Enums/MessageStatus.cs (85%) rename Kavenegar.Core/{Models => }/Enums/MessageType.cs (72%) rename Kavenegar.Core/{Models => }/Enums/MetaCode.cs (100%) rename Kavenegar.Core/{Models => }/Enums/VerifyLookupType.cs (60%) delete mode 100644 Kavenegar.Core/Exceptions/ApiException.cs delete mode 100644 Kavenegar.Core/Exceptions/KavenegarException.cs delete mode 100644 Kavenegar.Core/IKavenegarApi2.cs delete mode 100644 Kavenegar.Core/Json/JsonArray.cs delete mode 100644 Kavenegar.Core/Json/JsonBoolean.cs delete mode 100644 Kavenegar.Core/Json/JsonNullable.cs delete mode 100644 Kavenegar.Core/Json/JsonNumber.cs delete mode 100644 Kavenegar.Core/Json/JsonObject.cs delete mode 100644 Kavenegar.Core/Json/JsonString.cs delete mode 100644 Kavenegar.Core/Json/Parser.cs delete mode 100644 Kavenegar.Core/KavenegarApi2.cs delete mode 100644 Kavenegar.Core/Models/AccountConfigResult.cs delete mode 100644 Kavenegar.Core/Models/AccountInfoResult.cs delete mode 100644 Kavenegar.Core/Models/CountOutboxResult.cs delete mode 100644 Kavenegar.Core/Models/CountPostalCodeResult.cs delete mode 100644 Kavenegar.Core/Models/MessageInfo.cs delete mode 100644 Kavenegar.Core/Models/ReceiveResult.cs delete mode 100644 Kavenegar.Core/Models/ReturnAccountConfig.cs delete mode 100644 Kavenegar.Core/Models/ReturnAccountInfo.cs delete mode 100644 Kavenegar.Core/Models/ReturnCountInbox.cs delete mode 100644 Kavenegar.Core/Models/ReturnCountOutbox.cs delete mode 100644 Kavenegar.Core/Models/ReturnCountPostalCode.cs delete mode 100644 Kavenegar.Core/Models/ReturnReceive.cs delete mode 100644 Kavenegar.Core/Models/ReturnResult.cs delete mode 100644 Kavenegar.Core/Models/ReturnSend.cs delete mode 100644 Kavenegar.Core/Models/ReturnStatus.cs delete mode 100644 Kavenegar.Core/Models/ReturnStatusLocalMessageId.cs delete mode 100644 Kavenegar.Core/Models/SendMultiMessageRequest.cs delete mode 100644 Kavenegar.Core/Models/SendMultiMessageRequestDto.cs delete mode 100644 Kavenegar.Core/Models/SendSingleMessageRequest.cs delete mode 100644 Kavenegar.Core/Models/SendSingleMessageRequestDto.cs delete mode 100644 Kavenegar.Core/Models/StatusLocalMessageIdResult.cs delete mode 100644 Kavenegar.Core/Models/StatusResult.cs rename {Kavenegar.Core/Utils => Shared/Shared.Infrastructure}/DateHelper.cs (94%) diff --git a/Kavenegar.Core/Core/MappingProfiles.cs b/Kavenegar.Core/Core/MappingProfiles.cs deleted file mode 100644 index dba50af..0000000 --- a/Kavenegar.Core/Core/MappingProfiles.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System.Linq; -using System.Net; -using AutoMapper; -using Kavenegar.Core.Models; -using Kavenegar.Core.Utils; -using Shared.Infrastructure; - -namespace Kavenegar.Core.Core; - -public class MappingProfiles : Profile -{ - public MappingProfiles() - { - CreateMap() - .ForMember( - sendSingleMessageRequestDto => sendSingleMessageRequestDto.Receptors, - memberConfigurationExpression => memberConfigurationExpression.MapFrom( - sendSingleMessageRequest => string.Join(',', sendSingleMessageRequest.Receptors))) - .ForMember( - sendSingleMessageRequestDto => sendSingleMessageRequestDto.Sender, - memberConfigurationExpression => memberConfigurationExpression.MapFrom( - sendSingleMessageRequest => sendSingleMessageRequest.MessageInfo.Sender)) - .ForMember( - sendSingleMessageRequestDto => sendSingleMessageRequestDto.Message, - memberConfigurationExpression => memberConfigurationExpression.MapFrom( - sendSingleMessageRequest => WebUtility.HtmlEncode(sendSingleMessageRequest.MessageInfo.Message))) - .ForMember( - sendSingleMessageRequestDto => sendSingleMessageRequestDto.Date, - memberConfigurationExpression => memberConfigurationExpression.MapFrom( - sendSingleMessageRequest => sendSingleMessageRequest.Date.ToUnixTimestamp())) - .ForMember( - sendSingleMessageRequestDto => sendSingleMessageRequestDto.Type, - memberConfigurationExpression => memberConfigurationExpression.MapFrom( - sendSingleMessageRequest => (int)sendSingleMessageRequest.MessageInfo.Type)) - .ForMember( - sendSingleMessageRequestDto => sendSingleMessageRequestDto.LocalMessageId, - memberConfigurationExpression => memberConfigurationExpression.MapFrom( - sendSingleMessageRequest => sendSingleMessageRequest.MessageInfo.LocalMessageId)) - .ForMember( - sendSingleMessageRequestDto => sendSingleMessageRequestDto.Hide, - memberConfigurationExpression => memberConfigurationExpression.MapFrom( - sendSingleMessageRequest => sendSingleMessageRequest.Hide ? 1 : 0)); - - CreateMap() - .ForMember( - sendMultiMessageRequestDto => sendMultiMessageRequestDto.Receptors, - memberConfigurationExpression => memberConfigurationExpression.MapFrom( - sendSingleMessageRequest => sendSingleMessageRequest.Messages.Keys.ToList().Serialize(default))) - .ForMember( - sendMultiMessageRequestDto => sendMultiMessageRequestDto.Sender, - memberConfigurationExpression => memberConfigurationExpression.MapFrom( - sendMultiMessageRequest => sendMultiMessageRequest.Messages.Values - .Select(messageInfo => messageInfo.Sender) - .ToList() - .Serialize(default) - .Result)) - .ForMember( - sendMultiMessageRequestDto => sendMultiMessageRequestDto.Message, - memberConfigurationExpression => memberConfigurationExpression.MapFrom( - sendMultiMessageRequest => sendMultiMessageRequest.Messages.Values - .Select(messageInfo => WebUtility.HtmlEncode(messageInfo.Message)) - .ToList() - .Serialize(default))) - .ForMember( - sendMultiMessageRequestDto => sendMultiMessageRequestDto.Date, - memberConfigurationExpression => memberConfigurationExpression.MapFrom( - sendMultiMessageRequest => sendMultiMessageRequest.Date.ToUnixTimestamp())) - .ForMember( - sendMultiMessageRequestDto => sendMultiMessageRequestDto.Type, - memberConfigurationExpression => memberConfigurationExpression.MapFrom( - sendMultiMessageRequest => sendMultiMessageRequest.Messages.Values - .Select(messageInfo => (int)messageInfo.Type) - .ToList() - .Serialize(default))) - .ForMember( - sendMultiMessageRequestDto => sendMultiMessageRequestDto.LocalMessageId, - memberConfigurationExpression => memberConfigurationExpression.MapFrom( - sendMultiMessageRequest => sendMultiMessageRequest.Messages.Values - .Select(messageInfo => messageInfo.LocalMessageId) - .ToList() - .Serialize(default))) - .ForMember( - sendMultiMessageRequestDto => sendMultiMessageRequestDto.Hide, - memberConfigurationExpression => memberConfigurationExpression.MapFrom( - sendMultiMessageRequest => sendMultiMessageRequest.Hide ? 1 : 0)); - } -} \ No newline at end of file diff --git a/Kavenegar.Core/DependencyManager.cs b/Kavenegar.Core/DependencyManager.cs index c771f2d..9d37983 100644 --- a/Kavenegar.Core/DependencyManager.cs +++ b/Kavenegar.Core/DependencyManager.cs @@ -1,13 +1,13 @@ -using Kavenegar.Core.Core; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; namespace Kavenegar.Core; public static class DependencyManager { public static IServiceCollection AddKavenegar( - this IServiceCollection serviceCollection) + this IServiceCollection serviceCollection, + string apiKey) { - return serviceCollection.AddAutoMapper(typeof(MappingProfiles).Assembly); + return serviceCollection.AddTransient(_ => new KavenegarApi(apiKey)); } } \ No newline at end of file diff --git a/Kavenegar.Core/Dto/Message/MessageInfo.cs b/Kavenegar.Core/Dto/Message/MessageInfo.cs new file mode 100644 index 0000000..1392503 --- /dev/null +++ b/Kavenegar.Core/Dto/Message/MessageInfo.cs @@ -0,0 +1,12 @@ +using Kavenegar.Core.Enums; +using Kavenegar.Core.Models.Enums; + +namespace Kavenegar.Core.Dto.Message +{ + public class MessageInfo + { + public string Sender { get; set; } = null!; + public string Message { get; set; } = null!; + public MessageType Type { get; set; } + } +} \ No newline at end of file diff --git a/Kavenegar.Core/Dto/Message/SendMessageInfo.cs b/Kavenegar.Core/Dto/Message/SendMessageInfo.cs new file mode 100644 index 0000000..6a09e09 --- /dev/null +++ b/Kavenegar.Core/Dto/Message/SendMessageInfo.cs @@ -0,0 +1,8 @@ +namespace Kavenegar.Core.Dto.Message; + +public class SendMessageInfo +{ + public MessageInfo MessageInfo { get; set; } = null!; + public string Receptor { get; set; } = null!; + public string LocalMessageId { get; set; } = null!; +} \ No newline at end of file diff --git a/Kavenegar.Core/Dto/Message/SendMultiMessageRequest.cs b/Kavenegar.Core/Dto/Message/SendMultiMessageRequest.cs new file mode 100644 index 0000000..4be63d1 --- /dev/null +++ b/Kavenegar.Core/Dto/Message/SendMultiMessageRequest.cs @@ -0,0 +1,8 @@ +namespace Kavenegar.Core.Dto.Message; + +public class SendMultiMessageRequest +{ + public IEnumerable SendMessageInfos { get; set; } = null!; + public DateTime Date { get; set; } + public bool Hide { get; set; } +} \ No newline at end of file diff --git a/Kavenegar.Core/Dto/Message/SendSingleMessageRequest.cs b/Kavenegar.Core/Dto/Message/SendSingleMessageRequest.cs new file mode 100644 index 0000000..e5edf01 --- /dev/null +++ b/Kavenegar.Core/Dto/Message/SendSingleMessageRequest.cs @@ -0,0 +1,14 @@ +namespace Kavenegar.Core.Dto.Message; + +public class SendSingleMessageRequest +{ + public MessageInfo MessageInfo { get; set; } = null!; + + /// + /// Key is receptor + /// Value is local message id + /// + public Dictionary ReceptorLocalMessageIds { get; set; } = null!; + public DateTime? Date { get; set; } + public bool Hide { get; set; } +} \ No newline at end of file diff --git a/Kavenegar.Core/Dto/Result/AccountConfigDto.cs b/Kavenegar.Core/Dto/Result/AccountConfigDto.cs new file mode 100644 index 0000000..403d579 --- /dev/null +++ b/Kavenegar.Core/Dto/Result/AccountConfigDto.cs @@ -0,0 +1,11 @@ +namespace Kavenegar.Core.Dto.Result; + +public class AccountConfigDto +{ + public string ApiLogs { get; set; } = null!; + public string DailyReport { get; set; }= null!; + public string DebugMode { get; set; }= null!; + public string DefaultSender { get; set; }= null!; + public string MinCreditAlarm { get; set; }= null!; + public string ResendFailed { get; set; }= null!; +} \ No newline at end of file diff --git a/Kavenegar.Core/Dto/Result/AccountInfoDto.cs b/Kavenegar.Core/Dto/Result/AccountInfoDto.cs new file mode 100644 index 0000000..c4a2cdb --- /dev/null +++ b/Kavenegar.Core/Dto/Result/AccountInfoDto.cs @@ -0,0 +1,11 @@ +using Shared.Infrastructure; + +namespace Kavenegar.Core.Dto.Result; + +public class AccountInfoDto +{ + public long RemainCredit { get; set; } + public long ExpireDate { get; set; } + public DateTime GregorianExpireDate => ExpireDate.ToDateTime(); + public string Type { get; set; } = null!; +} \ No newline at end of file diff --git a/Kavenegar.Core/Models/CountInboxResult.cs b/Kavenegar.Core/Dto/Result/CountInboxDto.cs similarity index 65% rename from Kavenegar.Core/Models/CountInboxResult.cs rename to Kavenegar.Core/Dto/Result/CountInboxDto.cs index b13e9b1..766a3c3 100644 --- a/Kavenegar.Core/Models/CountInboxResult.cs +++ b/Kavenegar.Core/Dto/Result/CountInboxDto.cs @@ -1,6 +1,6 @@ -namespace Kavenegar.Core.Models; +namespace Kavenegar.Core.Dto.Result; -public class CountInboxResult +public class CountInboxDto { public long StartDate { get; set; } public long EndDate { get; set; } diff --git a/Kavenegar.Core/Dto/Result/CountOutboxDto.cs b/Kavenegar.Core/Dto/Result/CountOutboxDto.cs new file mode 100644 index 0000000..e232f95 --- /dev/null +++ b/Kavenegar.Core/Dto/Result/CountOutboxDto.cs @@ -0,0 +1,7 @@ +namespace Kavenegar.Core.Dto.Result; + +public class CountOutboxDto : CountInboxDto +{ + public long SumPart { get; set; } + public long Cost { get; set; } +} \ No newline at end of file diff --git a/Kavenegar.Core/Dto/Result/LocalStatusDto.cs b/Kavenegar.Core/Dto/Result/LocalStatusDto.cs new file mode 100644 index 0000000..3d2f1d8 --- /dev/null +++ b/Kavenegar.Core/Dto/Result/LocalStatusDto.cs @@ -0,0 +1,12 @@ +using Kavenegar.Core.Enums; +using Kavenegar.Core.Models.Enums; + +namespace Kavenegar.Core.Dto.Result; + +public class LocalStatusDto +{ + public long MessageId { get; set; } + public long LocalId { get; set; } + public MessageStatus Status { get; set; } + public string StatusText { get; set; } = null!; +} \ No newline at end of file diff --git a/Kavenegar.Core/Dto/Result/ReceivedMessageDto.cs b/Kavenegar.Core/Dto/Result/ReceivedMessageDto.cs new file mode 100644 index 0000000..b3806b8 --- /dev/null +++ b/Kavenegar.Core/Dto/Result/ReceivedMessageDto.cs @@ -0,0 +1,13 @@ +using Shared.Infrastructure; + +namespace Kavenegar.Core.Dto.Result; + +public class ReceivedMessageDto +{ + public long Date { get; set; } + public DateTime GregorianDate => Date.ToDateTime(); + public long MessageId { get; set; } + public string Sender { get; set; }= null!; + public string Message { get; set; }= null!; + public string Receptor { get; set; }= null!; +} \ No newline at end of file diff --git a/Kavenegar.Core/Dto/Result/ResultDto.cs b/Kavenegar.Core/Dto/Result/ResultDto.cs new file mode 100644 index 0000000..a3510fa --- /dev/null +++ b/Kavenegar.Core/Dto/Result/ResultDto.cs @@ -0,0 +1,12 @@ +using System.Text.Json.Serialization; + +namespace Kavenegar.Core.Dto.Result; + +internal class ResultDto +{ + [JsonPropertyName("return")] + public ResultStatus Result { get; set; } = null!; + + [JsonPropertyName("entries")] + public T Value { get; set; } = default!; +} \ No newline at end of file diff --git a/Kavenegar.Core/Models/Result.cs b/Kavenegar.Core/Dto/Result/ResultStatus.cs similarity index 56% rename from Kavenegar.Core/Models/Result.cs rename to Kavenegar.Core/Dto/Result/ResultStatus.cs index 34a97b7..32762a2 100644 --- a/Kavenegar.Core/Models/Result.cs +++ b/Kavenegar.Core/Dto/Result/ResultStatus.cs @@ -1,6 +1,6 @@ -namespace Kavenegar.Core.Models; +namespace Kavenegar.Core.Dto.Result; -internal class Result +internal class ResultStatus { public int Status { get; set; } public string Message { get; set; } = null!; diff --git a/Kavenegar.Core/Models/SendResult.cs b/Kavenegar.Core/Dto/Result/SendResult.cs similarity index 90% rename from Kavenegar.Core/Models/SendResult.cs rename to Kavenegar.Core/Dto/Result/SendResult.cs index 482ca5b..21852ea 100644 --- a/Kavenegar.Core/Models/SendResult.cs +++ b/Kavenegar.Core/Dto/Result/SendResult.cs @@ -1,4 +1,4 @@ -namespace Kavenegar.Core.Models; +namespace Kavenegar.Core.Dto.Result; public class SendResult { diff --git a/Kavenegar.Core/Dto/Result/StatusMessageDto.cs b/Kavenegar.Core/Dto/Result/StatusMessageDto.cs new file mode 100644 index 0000000..620950c --- /dev/null +++ b/Kavenegar.Core/Dto/Result/StatusMessageDto.cs @@ -0,0 +1,11 @@ +using Kavenegar.Core.Enums; +using Kavenegar.Core.Models.Enums; + +namespace Kavenegar.Core.Dto.Result; + +public class StatusMessageDto +{ + public long Messageid { get; set; } + public MessageStatus Status { get; set; } + public string StatusText { get; set; } = null!; +} \ No newline at end of file diff --git a/Kavenegar.Core/Dto/ResultDto.cs b/Kavenegar.Core/Dto/ResultDto.cs deleted file mode 100644 index 08b2cca..0000000 --- a/Kavenegar.Core/Dto/ResultDto.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Kavenegar.Core.Models; -using Newtonsoft.Json; - -namespace Kavenegar.Core.Dto; - -internal class ResultDto -{ - [JsonProperty("return")] - public Result Result { get; set; } = null!; - - [JsonProperty("entries")] - public T Value { get; set; } = default!; -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/Enums/MessageStatus.cs b/Kavenegar.Core/Enums/MessageStatus.cs similarity index 85% rename from Kavenegar.Core/Models/Enums/MessageStatus.cs rename to Kavenegar.Core/Enums/MessageStatus.cs index 4868220..8308897 100644 --- a/Kavenegar.Core/Models/Enums/MessageStatus.cs +++ b/Kavenegar.Core/Enums/MessageStatus.cs @@ -1,4 +1,4 @@ -namespace Kavenegar.Core.Models.Enums; +namespace Kavenegar.Core.Enums; public enum MessageStatus { diff --git a/Kavenegar.Core/Models/Enums/MessageType.cs b/Kavenegar.Core/Enums/MessageType.cs similarity index 72% rename from Kavenegar.Core/Models/Enums/MessageType.cs rename to Kavenegar.Core/Enums/MessageType.cs index e6d26b3..104630f 100644 --- a/Kavenegar.Core/Models/Enums/MessageType.cs +++ b/Kavenegar.Core/Enums/MessageType.cs @@ -1,4 +1,4 @@ -namespace Kavenegar.Core.Models.Enums; +namespace Kavenegar.Core.Enums; public enum MessageType { diff --git a/Kavenegar.Core/Models/Enums/MetaCode.cs b/Kavenegar.Core/Enums/MetaCode.cs similarity index 100% rename from Kavenegar.Core/Models/Enums/MetaCode.cs rename to Kavenegar.Core/Enums/MetaCode.cs diff --git a/Kavenegar.Core/Models/Enums/VerifyLookupType.cs b/Kavenegar.Core/Enums/VerifyLookupType.cs similarity index 60% rename from Kavenegar.Core/Models/Enums/VerifyLookupType.cs rename to Kavenegar.Core/Enums/VerifyLookupType.cs index 553a24d..9001236 100644 --- a/Kavenegar.Core/Models/Enums/VerifyLookupType.cs +++ b/Kavenegar.Core/Enums/VerifyLookupType.cs @@ -1,4 +1,4 @@ -namespace Kavenegar.Core.Models.Enums; +namespace Kavenegar.Core.Enums; public enum VerifyLookupType { diff --git a/Kavenegar.Core/Exceptions/ApiException.cs b/Kavenegar.Core/Exceptions/ApiException.cs deleted file mode 100644 index 4583167..0000000 --- a/Kavenegar.Core/Exceptions/ApiException.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Kavenegar.Core.Models.Enums; - -namespace Kavenegar.Core.Exceptions; - -public class ApiException : KavenegarException -{ - public ApiException( - string message, - int code) : base(message) - { - Code = (MetaCode)code; - } - - public MetaCode Code { get; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Exceptions/KavenegarException.cs b/Kavenegar.Core/Exceptions/KavenegarException.cs deleted file mode 100644 index 49da29e..0000000 --- a/Kavenegar.Core/Exceptions/KavenegarException.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; - -namespace Kavenegar.Core.Exceptions; - -public class KavenegarException : Exception -{ - public KavenegarException( - string message) : base(message) - { - } -} \ No newline at end of file diff --git a/Kavenegar.Core/IKavenegarApi.cs b/Kavenegar.Core/IKavenegarApi.cs index 9ce6232..519bf03 100644 --- a/Kavenegar.Core/IKavenegarApi.cs +++ b/Kavenegar.Core/IKavenegarApi.cs @@ -1,6 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; +using Kavenegar.Core.Dto.Message; +using Kavenegar.Core.Dto.Result; +using Kavenegar.Core.Enums; using Kavenegar.Core.Models; using Kavenegar.Core.Models.Enums; @@ -8,270 +8,95 @@ namespace Kavenegar.Core; public interface IKavenegarApi { - string ApiKey { set; get; } + Task Send( + SendSingleMessageRequest message, + CancellationToken cancellationToken = default); Task> Send( - string sender, - List receptor, - string message); + SendMultiMessageRequest messages, + CancellationToken cancellationToken = default); - Task Send( - string sender, - string receptor, - string message); - - Task Send( - string sender, - string receptor, - string message, - MessageType type, - DateTime date); - - Task> Send( - string sender, - List receptor, - string message, - MessageType type, - DateTime date); - - Task Send( - string sender, - string receptor, - string message, - MessageType type, - DateTime date, - string localId); - - Task Send( - string sender, - string receptor, - string message, - string localId); - - Task> Send( - string sender, - List receptors, - string message, - string localId); - - Task> Send( - string sender, - List receptor, - string message, - MessageType type, - DateTime date, - List localIds); - - Task> SendArray( - List senders, - List receptors, - List messages); - - Task> SendArray( - string sender, - List receptors, - List messages, - MessageType type, - DateTime date); - - Task> SendArray( - string sender, - List receptors, - List messages, - MessageType type, - DateTime date, - string localMessageIds); + Task Status( + string messageId, + CancellationToken cancellationToken = default); - Task> SendArray( - string sender, - List receptors, - List messages, - string localMessageId); + Task> Status( + List messageIds, + CancellationToken cancellationToken = default); - Task> SendArray( - List senders, - List receptors, - List messages, - string localMessageId); + Task StatusLocalMessageId( + string messageId, + CancellationToken cancellationToken = default); - Task> SendArray( - List senders, - List receptors, - List messages, - List types, - DateTime date, - List localMessageIds); - - Task> Status( - List messageIds); - - Task Status( - string messageId); - - Task> StatusLocalMessageId( - List messageIds); - - Task StatusLocalMessageId( - string messageId); - - Task> Select( - List messageIds); + Task> StatusLocalMessageId( + List messageIds, + CancellationToken cancellationToken = default); Task Select( - string messageId); - - Task> SelectOutbox( - DateTime startDate); + string messageId, + CancellationToken cancellationToken = default); - Task> SelectOutbox( - DateTime startDate, - DateTime endDate); + Task> Select( + List messageIds, + CancellationToken cancellationToken = default); Task> SelectOutbox( DateTime startDate, - DateTime endDate, - string sender); - - Task> LatestOutbox( - long pageSize); + DateTime? endDate, + string? sender, + CancellationToken cancellationToken = default); Task> LatestOutbox( - long pageSize, - string sender); - - Task CountOutbox( - DateTime startDate); - - Task CountOutbox( - DateTime startDate, - DateTime endDate); + long? pageSize, + string? sender, + CancellationToken cancellationToken = default); - Task CountOutbox( + Task CountOutbox( DateTime startDate, - DateTime endDate, - int status); + DateTime? endDate, + int? status, + CancellationToken cancellationToken = default); - Task> Cancel( - List ids); + Task Cancel( + string messageId, + CancellationToken cancellationToken = default); - Task Cancel( - string messageId); + Task> Cancel( + List ids, + CancellationToken cancellationToken = default); - Task> Receive( + Task> Receive( string line, - int isRead); + bool isRead, + CancellationToken cancellationToken = default); - Task CountInbox( + Task CountInbox( DateTime startDate, - string lineNumber); + DateTime? endDate, + string? lineNumber, + bool? isRead, + CancellationToken cancellationToken = default); - Task CountInbox( - DateTime startDate, - DateTime endDate, - string lineNumber); - - Task CountInbox( - DateTime startDate, - DateTime endDate, - string lineNumber, - int isRead); - - Task> CountPostalCode( - long postalcode); + Task AccountInfo( + CancellationToken cancellationToken = default); - Task> SendByPostalCode( - long postalcode, - string sender, - string message, - long mciStartIndex, - long mciCount, - long mtnStartIndex, - long mtnCount); - - Task> SendByPostalCode( - long postalcode, - string sender, - string message, - long mciStartIndex, - long mciCount, - long mtnStartIndex, - long mtnCount, - DateTime date); - - Task AccountInfo(); - - Task AccountConfig( + Task AccountConfig( string apiLogs, string dailyReport, string debugMode, string defaultSender, int? minCreditAlarm, - string resendFailed); - - Task VerifyLookup( - string receptor, - string token, - string template); + string resendFailed, + CancellationToken cancellationToken = default); Task VerifyLookup( string receptor, - string token, string template, - VerifyLookupType type); - - Task VerifyLookup( - string receptor, - string token, - string token2, - string token3, - string template); - - Task VerifyLookup( - string receptor, - string token, - string token2, - string token3, - string token10, - string template); - - Task VerifyLookup( - string receptor, - string token, - string token2, - string token3, - string template, - VerifyLookupType type); - - Task VerifyLookup( - string receptor, - string token, - string token2, - string token3, - string token10, - string template, - VerifyLookupType type); - - Task VerifyLookup( - string receptor, - string token, - string token2, - string token3, - string token10, - string token20, - string template, - VerifyLookupType type); - - Task CallMakeTts( - string message, - string receptor); - - Task> CallMakeTts( - string message, - List receptor); - - Task> CallMakeTts( - string message, - List receptor, - DateTime? date, - List localId); + string token1, + string? token2 = null, + string? token3 = null, + string? token4 = null, + string? token5 = null, + VerifyLookupType? type = null, + CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Kavenegar.Core/IKavenegarApi2.cs b/Kavenegar.Core/IKavenegarApi2.cs deleted file mode 100644 index a270655..0000000 --- a/Kavenegar.Core/IKavenegarApi2.cs +++ /dev/null @@ -1,103 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Kavenegar.Core.Models; -using Kavenegar.Core.Models.Enums; - -namespace Kavenegar.Core; - -public interface IKavenegarApi2 -{ - Task Send( - SendSingleMessageRequest message, - CancellationToken cancellationToken = default); - - Task> Send( - SendMultiMessageRequest messages, - CancellationToken cancellationToken = default); - - Task Status( - string messageId, - CancellationToken cancellationToken = default); - - Task> Status( - List messageIds, - CancellationToken cancellationToken = default); - - Task StatusLocalMessageId( - string messageId, - CancellationToken cancellationToken = default); - - Task> StatusLocalMessageId( - List messageIds, - CancellationToken cancellationToken = default); - - Task Select( - string messageId, - CancellationToken cancellationToken = default); - - Task> Select( - List messageIds, - CancellationToken cancellationToken = default); - - Task> SelectOutbox( - DateTime startDate, - DateTime? endDate, - string? sender, - CancellationToken cancellationToken = default); - - Task> LatestOutbox( - long? pageSize, - string? sender, - CancellationToken cancellationToken = default); - - Task CountOutbox( - DateTime startDate, - DateTime? endDate, - int? status, - CancellationToken cancellationToken = default); - - Task Cancel( - string messageId, - CancellationToken cancellationToken = default); - - Task> Cancel( - List ids, - CancellationToken cancellationToken = default); - - Task> Receive( - string line, - bool isRead, - CancellationToken cancellationToken = default); - - Task CountInbox( - DateTime startDate, - DateTime? endDate, - string? lineNumber, - bool? isRead, - CancellationToken cancellationToken = default); - - Task AccountInfo( - CancellationToken cancellationToken = default); - - Task AccountConfig( - string apiLogs, - string dailyReport, - string debugMode, - string defaultSender, - int? minCreditAlarm, - string resendFailed, - CancellationToken cancellationToken = default); - - Task VerifyLookup( - string receptor, - string template, - string token1, - string? token2 = null, - string? token3 = null, - string? token4 = null, - string? token5 = null, - VerifyLookupType? type = null, - CancellationToken cancellationToken = default); -} \ No newline at end of file diff --git a/Kavenegar.Core/Json/JsonArray.cs b/Kavenegar.Core/Json/JsonArray.cs deleted file mode 100644 index f0b88ff..0000000 --- a/Kavenegar.Core/Json/JsonArray.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System.Collections.Generic; - -namespace Kavenegar.Core.Json; - -public class JsonArray : JsonObject -{ - private List.Enumerator _e; - - public JsonArray() - { - Array = new List(); - } - - public List Array { get; set; } - - public int Count => Array.Count; - - public void AddElementToArray( - JsonObject arrayElement) - { - Array.Add(arrayElement); - } - - public JsonObject UpCast() - { - JsonObject objectJ = this; - return objectJ; - } - - public void AddList( - List lista) - { - Array = lista; - } - - public bool NextObject( - out JsonObject o) - { - JsonObject outObject; - _e = Array.GetEnumerator(); - - if (_e.MoveNext()) - { - outObject = _e.Current; - o = outObject; - return true; - } - - outObject = new JsonObject(); - o = outObject; - return false; - } -} \ No newline at end of file diff --git a/Kavenegar.Core/Json/JsonBoolean.cs b/Kavenegar.Core/Json/JsonBoolean.cs deleted file mode 100644 index d944ef2..0000000 --- a/Kavenegar.Core/Json/JsonBoolean.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace Kavenegar.Core.Json; - -public class JsonBoolean : JsonObject -{ - public JsonBoolean( - bool booleanValue) - { - BooleanValue = booleanValue; - } - - public bool BooleanValue { get; set; } - - public JsonObject UpCast() - { - JsonObject objectJ = this; - return objectJ; - } -} \ No newline at end of file diff --git a/Kavenegar.Core/Json/JsonNullable.cs b/Kavenegar.Core/Json/JsonNullable.cs deleted file mode 100644 index 6d198d4..0000000 --- a/Kavenegar.Core/Json/JsonNullable.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace Kavenegar.Core.Json; - -public class JsonNullable : JsonObject -{ - public JsonNullable() - { - Nullable = "Null"; - } - - public string Nullable { get; set; } - - public JsonObject UpCast() - { - JsonObject objectJ = this; - return objectJ; - } -} \ No newline at end of file diff --git a/Kavenegar.Core/Json/JsonNumber.cs b/Kavenegar.Core/Json/JsonNumber.cs deleted file mode 100644 index f4dee4e..0000000 --- a/Kavenegar.Core/Json/JsonNumber.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace Kavenegar.Core.Json; - -public class JsonNumber : JsonObject -{ - public JsonNumber( - float number) - { - Number = number; - } - - public float Number { get; set; } - - public JsonObject UpCast() - { - JsonObject objectJ = this; - return objectJ; - } -} \ No newline at end of file diff --git a/Kavenegar.Core/Json/JsonObject.cs b/Kavenegar.Core/Json/JsonObject.cs deleted file mode 100644 index 224df99..0000000 --- a/Kavenegar.Core/Json/JsonObject.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System.Collections.Generic; - -namespace Kavenegar.Core.Json; - -/// -/// JsonObject is the base class. -/// JsonString,JsonNumber,JsonBoolean,JsonNullable and JsonArray inherits from JsonObject. -/// A JsonArray object may contain objects of the base class -/// -public class JsonObject -{ - public Dictionary Values; - - public JsonObject() - { - Values = new Dictionary(); - } - - public void AddJsonValue( - string textTag, - JsonObject newObject) - { - if (!Values.ContainsKey(textTag)) Values.Add(textTag, newObject); - } - - public JsonObject GetObject( - string key) - { - var current = Values[key]; - return current; - } - - public int ElementsOfDictionary() - { - return Values.Count; - } - - - public bool IsJsonString() - { - if (this is JsonString) return true; - return false; - } - - public bool IsJsonNumber() - { - if (this is JsonNumber) return true; - return false; - } - - public bool IsJsonBoolean() - { - if (this is JsonBoolean) return true; - return false; - } - - public bool IsJsonNullable() - { - if (this is JsonNullable) return true; - return false; - } - - public bool IsJsonArray() - { - if (this is JsonArray) return true; - return false; - } - - public JsonString GetAsString() - { - return (JsonString)this; - } - - public JsonNumber GetAsNumber() - { - return (JsonNumber)this; - } - - public JsonArray GetAsArray() - { - return (JsonArray)this; - } -} \ No newline at end of file diff --git a/Kavenegar.Core/Json/JsonString.cs b/Kavenegar.Core/Json/JsonString.cs deleted file mode 100644 index cdbb011..0000000 --- a/Kavenegar.Core/Json/JsonString.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace Kavenegar.Core.Json; - -public class JsonString : JsonObject -{ - public JsonString( - string text) - { - Text = text; - } - - public string Text { get; set; } - - public JsonObject UpCast() - { - JsonObject objectJ = this; - return objectJ; - } -} \ No newline at end of file diff --git a/Kavenegar.Core/Json/Parser.cs b/Kavenegar.Core/Json/Parser.cs deleted file mode 100644 index 604b6f7..0000000 --- a/Kavenegar.Core/Json/Parser.cs +++ /dev/null @@ -1,481 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Kavenegar.Core.Json; - -/// -/// Contains the façade-style class to perform Json operations -/// -public class Parser -{ - private const char ObjectBegin = '{'; - private const char ObjectEnd = '}'; - private const char ArrayBegin = '['; - private const char ArrayEnd = ']'; - private const char DoubleQuotes = '"'; - private const char DoublePoint = ':'; - private const char Comma = ','; - private const char BackSlash = '\u005C'; - private const string NullValue = "null"; - private const string TrueValue = "true"; - private const string FalseValue = "false"; - - public JsonObject DocumentJson; - - /// - /// Deserialize a JSON document. This method does not perform a syntax checking so It assumes a valid Json input - /// - /// - /// A string which contains a valid Json array or object - /// - public JsonObject Parse( - string json) - { - if (json[0] == ArrayBegin) - { - json = json.Substring(1, json.Length - 2); - var arrayJson = SerializeArray(json); - JsonObject o = arrayJson; - return o; - } - - if (json[0] == ObjectBegin) return SerializeObject(json); - - return null; - } - - /// - /// This method performs deserialization of an object(except array) - /// - /// - /// JsonObject object as a deserialized JSON object - /// - /// - /// A string which contains a valid Json object - /// - private JsonObject SerializeObject( - string json) - { - json = json.Replace(@"\", ""); - var document = new JsonObject(); - var n = 1; - var lengthJson = json.Length; - var keyString = ""; - - while (n <= lengthJson - 1) - if (json[n] == DoubleQuotes && - json[n - 1] != DoublePoint) - { - var secondDoubleQuotes = FindNextQuote(json, n + 1); - keyString = json.Substring(n + 1, secondDoubleQuotes - (n + 1)); - n = secondDoubleQuotes + 1; - } - else if (json[n] == DoubleQuotes && - json[n - 1] == DoublePoint) - { - if (json[n + 1] != DoubleQuotes) - { - var secondDoublesQuotes = FindNextQuote(json, n + 1); - var text = json.Substring(n + 1, secondDoublesQuotes - (n + 1)); - var stringValue = new JsonString(text); - JsonObject o = stringValue; - document.AddJsonValue(keyString, o); - n = secondDoublesQuotes + 1; - } - else - { - JsonObject o = new JsonString(""); - document.AddJsonValue(keyString, o); - } - } - else if (json[n] == '-' || - json[n] == '0' || - json[n] == '1' || - json[n] == '2' || - json[n] == '3' || - json[n] == '4' || - json[n] == '5' || - json[n] == '6' || - json[n] == '7' || - json[n] == '8' || - json[n] == '9') - { - char[] arrayEndings = - { - ObjectEnd, - Comma - }; - var nextComma = json.IndexOfAny(arrayEndings, n); - var stringNumber = json.Substring(n, nextComma - n); - var valueNumber = Convert.ToDouble(stringNumber); - var floatNumber = (float)valueNumber; - var number = new JsonNumber(floatNumber); - JsonObject o = number; - document.AddJsonValue(keyString, o); - n = nextComma + 1; - } - else if (json[n] == ArrayBegin) - { - if (json[n + 1] != ArrayEnd) - { - var subJson = json.Substring(n, json.Length - n); - var arrayClose = CloseBracketArray(subJson); - var arrayUnknown = json.Substring(n + 1, arrayClose - 2); - var arrayObjects = SerializeArray(arrayUnknown); - JsonObject o = arrayObjects; - document.AddJsonValue(keyString, o); - n = n + arrayClose; - } - else - { - if (!string.IsNullOrEmpty(keyString)) - { - var arrayTempEmpty = new JsonArray - { - Array = null - }; - JsonObject emptyArray = arrayTempEmpty; - document.AddJsonValue(keyString, emptyArray); - keyString = ""; - } - else - { - n++; - } - } - } - else if (json[n] == ObjectBegin) - { - if (json[n + 1] != ObjectEnd) - { - var subJson = json.Substring(n, json.Length - n); - var objectClose = CloseBracketObject(subJson); - var objectUnknown = json.Substring(n, objectClose); - var o = SerializeObject(objectUnknown); - document.AddJsonValue(keyString, o); - n = n + objectClose + 1; - } - else - { - var o = new JsonObject - { - Values = null - }; - document.AddJsonValue(keyString, o); - } - } - else if (string.Compare( - SafeSubString( - json, - n, - 4), - NullValue, - StringComparison.Ordinal) == - 0) - { - JsonObject o = new JsonNullable(); - document.AddJsonValue(keyString, o); - n = n + 5; - } - else if (string.Compare( - SafeSubString( - json, - n, - 4), - TrueValue, - StringComparison.Ordinal) == - 0) - { - JsonObject o = new JsonBoolean(true); - document.AddJsonValue(keyString, o); - n = n + 5; - } - else if (string.Compare( - SafeSubString( - json, - n, - 5), - FalseValue, - StringComparison.Ordinal) == - 0) - { - JsonObject o = new JsonBoolean(false); - document.AddJsonValue(keyString, o); - n = n + 6; - } - else - { - n++; - } - - return document; - } - - /// - /// Search where is the ending of an object - /// - /// - /// the index of the '}' which closes an object - /// - /// - /// A valid json string ({........) - /// - private int CloseBracketObject( - string json) - { - var countObjectBegin = 0; - var countObjectEnd = 0; - var n = 0; - - do - { - if (json[n] == ObjectBegin) - countObjectBegin++; - else if (json[n] == ObjectEnd) countObjectEnd++; - - n++; - } - while (countObjectBegin != countObjectEnd); - - return n; - } - - /// - /// Search where is the ending of an array - /// - /// - /// he index of the ']' which closes an object - /// - /// - /// A valid Json string ([.....) - /// - private int CloseBracketArray( - string json) - { - var countArrayBegin = 0; - var countArrayEnd = 0; - var n = 0; - - do - { - if (json[n] == ArrayBegin) - countArrayBegin++; - else if (json[n] == ArrayEnd) countArrayEnd++; - - n++; - } - while (countArrayBegin != countArrayEnd); - - return n; - } - - /// - /// Deserialize a Json Array into an object JsonArray - /// - /// - /// JsonArray object as a deserialized JSON array - /// - /// - /// valid JSON array except the brackets - /// - private JsonArray SerializeArray( - string array) - { - var arrayObject = new JsonArray(); - var elements = SplitElements(array); - - foreach (var item in elements) - if (item[0] == DoubleQuotes) - { - var withoutQuotes = item.Trim(DoubleQuotes); - JsonObject o = new JsonString(withoutQuotes); - arrayObject.AddElementToArray(o); - } - else if (item[0] == ObjectBegin) - { - var o = SerializeObject(item); - arrayObject.AddElementToArray(o); - } - else if (item[0] == ArrayBegin) - { - var itemArray = item.Substring(1, item.Length - 2); - var secondaryArray = SerializeArray(itemArray); - JsonObject o = secondaryArray; - arrayObject.AddElementToArray(o); - } - else if (item[0] == '-' || - item[0] == '0' || - item[0] == '1' || - item[0] == '2' || - item[0] == '3' || - item[0] == '4' || - item[0] == '5' || - item[0] == '6' || - item[0] == '7' || - item[0] == '8' || - item[0] == '9') - { - var doubleValue = Convert.ToDouble(item); - var floatValue = (float)doubleValue; - JsonObject o = new JsonNumber(floatValue); - arrayObject.AddElementToArray(o); - } - else if (string.Compare( - SafeSubString( - item, - 0, - 4), - TrueValue, - StringComparison.Ordinal) == - 0) - { - JsonObject o = new JsonBoolean(true); - arrayObject.AddElementToArray(o); - } - else if (string.Compare( - SafeSubString( - item, - 0, - 5), - FalseValue, - StringComparison.Ordinal) == - 0) - { - JsonObject o = new JsonBoolean(false); - arrayObject.AddElementToArray(o); - } - else if (string.Compare( - SafeSubString( - item, - 0, - 4), - NullValue, - StringComparison.Ordinal) == - 0) - { - JsonObject o = new JsonNullable(); - arrayObject.AddElementToArray(o); - } - - return arrayObject; - } - - /// - /// Just a safe subString operation - /// - /// - /// A subString of the string input parameter text - /// - /// - /// A string - /// - /// - /// index of starting - /// - /// - /// Length of the subString - /// - private string SafeSubString( - string text, - int start, - int length) - { - var safeString = start + length < text.Length ? - text.Substring(start, length) : - text.Substring(start, text.Length - start); - - return safeString; - } - - /// - /// Finds the next '"' to close a String field - /// - /// - /// The next ' " ' - /// - /// - /// A valid JSON string - /// - /// - /// Index of starting - /// - private int FindNextQuote( - string text, - int index) - { - var nextQuote = text.IndexOf(DoubleQuotes, index); - while (text[nextQuote - 1] == BackSlash) nextQuote = text.IndexOf(DoubleQuotes, nextQuote + 1); - - return nextQuote; - } - - /// - /// Splits the elements of an Array - /// - /// - /// The elements in an array of Strings - /// - /// - /// - private string[] SplitElements( - string arrayText) - { - var n = 0; - var doubleQuotesCounter = 0; - var objectBeginCounter = 0; - var objectEndCounter = 0; - var arrayBeginCounter = 0; - var arrayEndCounter = 0; - var previousCommaIndex = 0; - var oneElement = true; - var textSplit = new List(); - - while (n <= arrayText.Length - 1) - if (arrayText[n] == DoubleQuotes && - arrayText[n - 1] != BackSlash) - { - doubleQuotesCounter++; - n++; - } - else if (arrayText[n] == ObjectBegin) - { - objectBeginCounter++; - n++; - } - else if (arrayText[n] == ObjectEnd) - { - objectEndCounter++; - n++; - } - else if (arrayText[n] == ArrayBegin) - { - arrayBeginCounter++; - n++; - } - else if (arrayText[n] == ArrayEnd) - { - arrayEndCounter++; - n++; - } - else if (arrayText[n] == Comma && - doubleQuotesCounter % 2 == 0 && - objectBeginCounter == objectEndCounter && - arrayBeginCounter == arrayEndCounter) - { - textSplit.Add(arrayText.Substring(previousCommaIndex, n - previousCommaIndex)); - previousCommaIndex = n + 1; - n++; - oneElement = false; - } - else - { - n++; - } - - textSplit.Add( - oneElement ? arrayText : arrayText.Substring(previousCommaIndex, arrayText.Length - previousCommaIndex)); - - var textSplitArray = textSplit.ToArray(); - return textSplitArray; - } -} \ No newline at end of file diff --git a/Kavenegar.Core/Kavenegar.Core.csproj b/Kavenegar.Core/Kavenegar.Core.csproj index cea0371..e9094f5 100644 --- a/Kavenegar.Core/Kavenegar.Core.csproj +++ b/Kavenegar.Core/Kavenegar.Core.csproj @@ -1,37 +1,17 @@ - 1.0.5 - A cross-platform library for the kavenegar sms provider; written in C# - Kavenegar.Core - Kavenegar.Core - - KavenegarDotNetCore - Kavenegar Core kavenegar.Core kavenegarCore Sms - https://github.com/kavenegar/Kavenegar.Core - - Library - true - true - HadiEskandari Ardavan HosseinRezaei Mberneti MohammadAmirriazi - git - https://github.com/kavenegar/Kavenegar.Core - Kavenegar - true - 11 - enable net6.0 - + enable + enable - - - + - + diff --git a/Kavenegar.Core/KavenegarApi.cs b/Kavenegar.Core/KavenegarApi.cs index 4d9baf8..2052d5f 100644 --- a/Kavenegar.Core/KavenegarApi.cs +++ b/Kavenegar.Core/KavenegarApi.cs @@ -1,892 +1,467 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Threading.Tasks; -using Kavenegar.Core.Exceptions; -using Kavenegar.Core.Models; -using Kavenegar.Core.Models.Enums; -using Kavenegar.Core.Utils; -using Newtonsoft.Json; +using System.Net; +using Kavenegar.Core.Dto.Message; +using Kavenegar.Core.Dto.Result; +using Kavenegar.Core.Enums; +using Shared.Infrastructure; namespace Kavenegar.Core; -public class KavenegarApi : IKavenegarApi +internal class KavenegarApi : IKavenegarApi { - private const string ApiPath = "{0}/{1}.{2}"; - private const string BaseUrl = "http://api.kavenegar.com/v1"; - private static HttpClient _client = null!; + private readonly HttpClientHelper _httpClientHelper; public KavenegarApi( - string apikey) + string apiKey) { - ApiKey = apikey; - - _client = new HttpClient + _httpClientHelper = new HttpClientHelper { - BaseAddress = new Uri($"{BaseUrl}/{ApiKey}/") + BaseAddress = $"https://api.kavenegar.com/v1/{apiKey}" }; } - public string ApiKey { set; get; } - - public async Task> Send( - string sender, - List receptor, - string message) - { - return await Send( - sender, - receptor, - message, - MessageType.MobileMemory, - DateTime.MinValue); - } - - public async Task Send( - string sender, - string receptor, - string message) - { - return await Send( - sender, - receptor, - message, - MessageType.MobileMemory, - DateTime.MinValue); - } - - public async Task Send( - string sender, - string receptor, - string message, - MessageType type, - DateTime date) - { - var receptors = new List - { - receptor - }; - return (await Send( - sender, - receptors, - message, - type, - date))[0]; - } - - public async Task> Send( - string sender, - List receptor, - string message, - MessageType type, - DateTime date) - { - return await Send( - sender, - receptor, - message, - type, - date, - null); - } - - public async Task Send( - string sender, - string receptor, - string message, - MessageType type, - DateTime date, - string localId) + public async Task Send( + SendSingleMessageRequest message, + CancellationToken cancellationToken = default) { - var receptors = new List - { - receptor - }; - var localIds = new List - { - localId - }; - return (await Send( - sender, - receptors, - message, - type, - date, - localIds))[0]; - } - - public async Task Send( - string sender, - string receptor, - string message, - string localId) - { - return await Send( - sender, - receptor, - message, - MessageType.MobileMemory, - DateTime.MinValue, - localId); - } - - public async Task> Send( - string sender, - List receptors, - string message, - string localId) - { - var localIds = new List(); - for (var i = 0; i <= receptors.Count - 1; i++) localIds.Add(localId); - return await Send( - sender, - receptors, - message, - MessageType.MobileMemory, - DateTime.MinValue, - localIds); - } - - public async Task> Send( - string sender, - List receptor, - string message, - MessageType type, - DateTime date, - List localIds) - { - var path = GetApiPath( - "sms", - "send", - "json"); - var param = new Dictionary + var queryParams = new Dictionary { { - "sender", WebUtility.HtmlEncode(sender) + "sender", message.MessageInfo.Sender }, { - "receptor", WebUtility.HtmlEncode(string.Join(",", receptor)) + "receptor", string.Join(',', message.ReceptorLocalMessageIds.Keys) }, { - "message", message + "message", message.MessageInfo.Message }, { - "type", (int)type + "type", (int)message.MessageInfo.Type }, { - "date", date == DateTime.MinValue ? 0 : date.ToUnixTimestamp() + "date", message.Date?.ToUnixTimestamp() ?? 0 } }; - if (localIds != null && - localIds.Count > 0) - param.Add("localId", string.Join(",", localIds)); - var responseBody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responseBody); - return l.entries; - } - public async Task> SendArray( - List senders, - List receptors, - List messages) - { - var types = new List(); - for (var i = 0; i <= senders.Count - 1; i++) types.Add(MessageType.MobileMemory); - return await SendArray( - senders, - receptors, - messages, - types, - DateTime.MinValue, - null); - } - - public async Task> SendArray( - string sender, - List receptors, - List messages, - MessageType type, - DateTime date) - { - var senders = new List(); - for (var i = 0; i < receptors.Count; i++) senders.Add(sender); - var types = new List(); - for (var i = 0; i <= senders.Count - 1; i++) types.Add(MessageType.MobileMemory); - return await SendArray( - senders, - receptors, - messages, - types, - date, - null); - } + if (message.ReceptorLocalMessageIds.Values.All(string.IsNullOrWhiteSpace)) + queryParams.Add("localId", string.Join(',', message.ReceptorLocalMessageIds.Values)); - public async Task> SendArray( - string sender, - List receptors, - List messages, - MessageType type, - DateTime date, - string localMessageIds) - { - var senders = new List(); - for (var i = 0; i < receptors.Count; i++) senders.Add(sender); - var types = new List(); - for (var i = 0; i <= senders.Count - 1; i++) types.Add(MessageType.MobileMemory); - return await SendArray( - senders, - receptors, - messages, - types, - date, - new List - { - localMessageIds - }); - } + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/sendarray.json", + null, + queryParams, + cancellationToken); - public async Task> SendArray( - string sender, - List receptors, - List messages, - string localMessageId) - { - var senders = new List(); - for (var i = 0; i < receptors.Count; i++) senders.Add(sender); - - return await SendArray( - senders, - receptors, - messages, - localMessageId); + return (await httpResponseMessage.Deserialize>>(cancellationToken))!.Value + .FirstOrDefault(); } - public async Task> SendArray( - List senders, - List receptors, - List messages, - string localMessageId) - { - var types = new List(); - for (var i = 0; i <= receptors.Count - 1; i++) types.Add(MessageType.MobileMemory); - var localMessageIds = new List(); - for (var i = 0; i <= receptors.Count - 1; i++) localMessageIds.Add(localMessageId); - return await SendArray( - senders, - receptors, - messages, - types, - DateTime.MinValue, - localMessageIds); - } - - public async Task> SendArray( - List senders, - List receptors, - List messages, - List types, - DateTime date, - List localMessageIds) + public async Task> Send( + SendMultiMessageRequest messages, + CancellationToken cancellationToken = default) { - var path = GetApiPath( - "sms", - "sendarray", - "json"); - var jsonSenders = JsonConvert.SerializeObject(senders); - var jsonReceptors = JsonConvert.SerializeObject(receptors); - var jsonMessages = JsonConvert.SerializeObject(messages); - var jsonTypes = JsonConvert.SerializeObject(types); - var param = new Dictionary + var requestParams = new Dictionary { { - "message", jsonMessages + "message", + await messages.SendMessageInfos + .Select(sendMessageInfo => WebUtility.HtmlEncode(sendMessageInfo.MessageInfo.Message)) + .ToList() + .Serialize(cancellationToken) }, { - "sender", jsonSenders + "sender", + await messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.MessageInfo.Sender) + .ToList() + .Serialize(cancellationToken) }, { - "receptor", jsonReceptors + "receptor", + await messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.Receptor) + .ToList() + .Serialize(cancellationToken) }, { - "type", jsonTypes + "type", + await messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.MessageInfo.Type.ToString()) + .Serialize(cancellationToken) }, { - "date", date == DateTime.MinValue ? 0 : date.ToUnixTimestamp() + "date", messages.Date == DateTime.MinValue ? 0 : messages.Date.ToUnixTimestamp() } }; - if (localMessageIds != null && - localMessageIds.Count > 0) - param.Add("localMessageIds", string.Join(",", localMessageIds)); - - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - if (l.entries == null) return new List(); - return l.entries; + + if (messages.SendMessageInfos.All( + sendMessageInfo => !string.IsNullOrWhiteSpace(sendMessageInfo.LocalMessageId))) + requestParams.Add( + "localMessageIds", + string.Join( + ",", + messages.SendMessageInfos.Select( + sendMessageInfo => !string.IsNullOrWhiteSpace(sendMessageInfo.LocalMessageId)))); + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/send.json", + null, + requestParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))!.Value; + } + + public async Task Status( + string messageId, + CancellationToken cancellationToken = default) + { + return (await Status( + new List + { + messageId + }, + cancellationToken)).FirstOrDefault()!; } - public async Task> Status( - List messageIds) + public async Task> Status( + List messageIds, + CancellationToken cancellationToken = default) { - var path = GetApiPath( - "sms", - "status", - "json"); - var param = new Dictionary + var queryParams = new Dictionary { { - "messageId", string.Join(",", messageIds) + "messageid", string.Join(',', messageIds) } }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - if (l.entries == null) return new List(); - return l.entries; + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/status.json", + null, + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? + new List(); } - public async Task Status( - string messageId) + public async Task StatusLocalMessageId( + string messageId, + CancellationToken cancellationToken = default) { - var ids = new List - { - messageId - }; - var result = await Status(ids); - return result.Count == 1 ? result[0] : null; + return (await StatusLocalMessageId( + new List + { + messageId + }, + cancellationToken)).FirstOrDefault()!; } - public async Task> StatusLocalMessageId( - List messageIds) + public async Task> StatusLocalMessageId( + List messageIds, + CancellationToken cancellationToken = default) { - var path = GetApiPath( - "sms", - "statuslocalmessageid", - "json"); - var param = new Dictionary + var queryParams = new Dictionary { { - "localId", string.Join(",", messageIds) + "messageid", string.Join(',', messageIds) } }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries; + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/statuslocalmessageid.json", + null, + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? + new List(); } - public async Task StatusLocalMessageId( - string messageId) + public async Task Select( + string messageId, + CancellationToken cancellationToken = default) { - var result = await StatusLocalMessageId( + return (await Select( new List { messageId - }); - return result.Count == 1 ? result[0] : null; + }, + cancellationToken)).FirstOrDefault()!; } public async Task> Select( - List messageIds) + List messageIds, + CancellationToken cancellationToken = default) { - var path = GetApiPath( - "sms", - "select", - "json"); - var param = new Dictionary + var queryParams = new Dictionary { { - "messageId", string.Join(",", messageIds) + "messageid", string.Join(',', messageIds) } }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - if (l.entries == null) return new List(); - return l.entries; - } - public async Task Select( - string messageId) - { - var ids = new List - { - messageId - }; - var result = await Select(ids); - return result.Count == 1 ? result[0] : null; - } + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/select.json", + null, + queryParams, + cancellationToken); - public async Task> SelectOutbox( - DateTime startDate) - { - return await SelectOutbox(startDate, DateTime.MaxValue); + return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? + new List(); } public async Task> SelectOutbox( DateTime startDate, - DateTime endDate) + DateTime? endDate, + string? sender, + CancellationToken cancellationToken = default) { - return await SelectOutbox( - startDate, - endDate, - null); - } + if (endDate <= startDate) throw new ArgumentException("تاریخ پایان باید از تاریخ شروع بزرگتر باشد."); - public async Task> SelectOutbox( - DateTime startDate, - DateTime endDate, - string sender) - { - var path = GetApiPath( - "sms", - "selectoutbox", - "json"); - var param = new Dictionary + if ((endDate - startDate)!.Value.TotalDays > 1) + throw new ArgumentException( + "حداکثر فاصله زمانی بین متغیر startDate تا متغیر endDate برابر با 1 روز می باشد."); + + if (startDate < DateTime.Now.AddDays(-60)) + throw new ArgumentException("تاریخ شروع startDate حداکثر باید تا 60 روز قبل باشد."); + + var queryParams = new Dictionary { { - "startDate", startDate == DateTime.MinValue ? 0 : startDate.ToUnixTimestamp() - }, - { - "endDate", endDate == DateTime.MinValue ? 0 : endDate.ToUnixTimestamp() - }, - { - "sender", sender + "startdate", startDate.ToUnixTimestamp() } }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries; - } - public async Task> LatestOutbox( - long pageSize) - { - return await LatestOutbox(pageSize, ""); + if (endDate.HasValue) queryParams.Add("enddate", endDate.Value.ToUnixTimestamp()); + + if (string.IsNullOrWhiteSpace(sender)) queryParams.Add("sender", sender); + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/selectoutbox.json", + null, + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? + new List(); } public async Task> LatestOutbox( - long pageSize, - string sender) + long? pageSize, + string? sender, + CancellationToken cancellationToken = default) { - var path = GetApiPath( - "sms", - "latestoutbox", - "json"); - var param = new Dictionary + if (pageSize is > 500) throw new ArgumentException("تعداد رکورد های خروجی این متد حداکثر 500 رکورد می‌باشد."); + + pageSize ??= 500; + + var queryParams = new Dictionary { { - "pageSize", pageSize - }, - { - "sender", sender + "pagesize", pageSize } }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries; - } - public async Task CountOutbox( - DateTime startDate) - { - return await CountOutbox( - startDate, - DateTime.MaxValue, - 10); - } + if (string.IsNullOrWhiteSpace(sender)) queryParams.Add("sender", sender); - public async Task CountOutbox( - DateTime startDate, - DateTime endDate) - { - return await CountOutbox( - startDate, - endDate, - 0); + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/latestoutbox.json", + null, + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? + new List(); } - public async Task CountOutbox( + public async Task CountOutbox( DateTime startDate, - DateTime endDate, - int status) + DateTime? endDate, + int? status, + CancellationToken cancellationToken = default) { - var path = GetApiPath( - "sms", - "countoutbox", - "json"); - var param = new Dictionary - { - { - "startDate", startDate == DateTime.MinValue ? 0 : startDate.ToUnixTimestamp() - }, - { - "endDate", endDate == DateTime.MinValue ? 0 : endDate.ToUnixTimestamp() - }, - { - "status", status - } - }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - if (l.entries == null || - l.entries[0] == null) - return new CountOutboxResult(); - return l.entries[0]; - } + if (endDate <= startDate) throw new ArgumentException("تاریخ پایان باید از تاریخ شروع بزرگتر باشد."); - public async Task> Cancel( - List ids) - { - var path = GetApiPath( - "sms", - "cancel", - "json"); - var param = new Dictionary - { - { - "messageId", string.Join(",", ids) - } - }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries; - } + if ((endDate - startDate)!.Value.TotalDays > 1) + throw new ArgumentException( + "حداکثر فاصله زمانی بین متغیر startdate تا متغیر endDate برابر با 1 روز می باشد."); - public async Task Cancel( - string messageId) - { - var ids = new List - { - messageId - }; - var result = await Cancel(ids); - return result.Count == 1 ? result[0] : null; - } + if (startDate < DateTime.Now.AddDays(-60)) + throw new ArgumentException("تاریخ شروع startdate حداکثر باید تا 60 روز قبل باشد."); - public async Task> Receive( - string line, - int isRead) - { - var path = GetApiPath( - "sms", - "receive", - "json"); - var param = new Dictionary + var queryParams = new Dictionary { { - "lineNumber", line - }, - { - "isRead", isRead + "startdate", startDate.ToUnixTimestamp() } }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - if (l.entries == null) return new List(); - return l.entries; - } - public async Task CountInbox( - DateTime startDate, - string lineNumber) - { - return await CountInbox( - startDate, - DateTime.MaxValue, - lineNumber, - 0); - } + if (endDate.HasValue) queryParams.Add("enddate", endDate.Value.ToUnixTimestamp()); - public async Task CountInbox( - DateTime startDate, - DateTime endDate, - string lineNumber) - { - return await CountInbox( - startDate, - endDate, - lineNumber, - 0); + if (status.HasValue) queryParams.Add("status", status); + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/countoutbox.json", + null, + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value + .FirstOrDefault() ?? + new CountOutboxDto(); } - public async Task CountInbox( - DateTime startDate, - DateTime endDate, - string lineNumber, - int isRead) + public async Task Cancel( + string messageId, + CancellationToken cancellationToken = default) { - var path = GetApiPath( - "sms", - "countoutbox", - "json"); - var param = new Dictionary - { - { - "startDate", startDate == DateTime.MinValue ? 0 : startDate.ToUnixTimestamp() - }, - { - "endDate", endDate == DateTime.MinValue ? 0 : endDate.ToUnixTimestamp() - }, + return (await Cancel( + new List { - "lineNumber", lineNumber + messageId }, - { - "isRead", isRead - } - }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries[0]; + cancellationToken)).FirstOrDefault()!; } - public async Task> CountPostalCode( - long postalcode) + public async Task> Cancel( + List ids, + CancellationToken cancellationToken = default) { - var path = GetApiPath( - "sms", - "countpostalcode", - "json"); - var param = new Dictionary + var queryParams = new Dictionary { { - "postalcode", postalcode + "messageid", string.Join(',', ids) } }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries; - } - public async Task> SendByPostalCode( - long postalcode, - string sender, - string message, - long mciStartIndex, - long mciCount, - long mtnStartIndex, - long mtnCount) - { - return await SendByPostalCode( - postalcode, - sender, - message, - mciStartIndex, - mciCount, - mtnStartIndex, - mtnCount, - DateTime.MinValue); + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/cancel.json", + null, + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? + new List(); } - public async Task> SendByPostalCode( - long postalcode, - string sender, - string message, - long mciStartIndex, - long mciCount, - long mtnStartIndex, - long mtnCount, - DateTime date) + public async Task> Receive( + string line, + bool isRead, + CancellationToken cancellationToken = default) { - var path = GetApiPath( - "sms", - "sendbypostalcode", - "json"); - var param = new Dictionary + var queryParams = new Dictionary { { - "postalcode", postalcode - }, - { - "sender", sender - }, - { - "message", WebUtility.HtmlEncode(message) + "linenumber", line }, { - "mciStartIndex", mciStartIndex - }, - { - "mciCount", mciCount - }, - { - "mtnStartIndex", mtnStartIndex - }, - { - "mtnCount", mtnCount - }, - { - "date", date == DateTime.MinValue ? 0 : date.ToUnixTimestamp() + "isread", isRead ? 1 : 0 } }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries; - } - public async Task AccountInfo() - { - var path = GetApiPath( - "account", - "info", - "json"); - var responsebody = await Execute(path, null); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries; + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/receive.json", + null, + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? + new List(); } - public async Task AccountConfig( - string apiLogs, - string dailyReport, - string debugMode, - string defaultSender, - int? minCreditAlarm, - string resendFailed) + public async Task CountInbox( + DateTime startDate, + DateTime? endDate, + string? lineNumber, + bool? isRead, + CancellationToken cancellationToken = default) { - var path = GetApiPath( - "account", - "config", - "json"); - var param = new Dictionary + if (endDate <= startDate) throw new ArgumentException("تاریخ پایان باید از تاریخ شروع بزرگتر باشد."); + + if ((endDate - startDate)!.Value.TotalDays > 1) + throw new ArgumentException( + "حداکثر فاصله زمانی بین متغیر startdate تا متغیر endDate برابر با 1 روز می باشد."); + + if (startDate < DateTime.Now.AddDays(-60)) + throw new ArgumentException("تاریخ شروع startdate حداکثر باید تا 60 روز قبل باشد."); + + var queryParams = new Dictionary { { - "apiLogs", apiLogs - }, - { - "dailyReport", dailyReport - }, - { - "debugMode", debugMode - }, - { - "defaultSender", defaultSender - }, - { - "minCreditAlarm", minCreditAlarm - }, - { - "resendFailed", resendFailed + "startdate", startDate.ToUnixTimestamp() } }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries; - } - public async Task VerifyLookup( - string receptor, - string token, - string template) - { - return await VerifyLookup( - receptor, - token, - null, + if (endDate.HasValue) queryParams.Add("enddate", endDate.Value.ToUnixTimestamp()); + if (string.IsNullOrWhiteSpace(lineNumber)) queryParams.Add("linenumber", lineNumber); + if (isRead.HasValue) queryParams.Add("isread", isRead.Value ? 1 : 0); + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "sms/countinbox.json", null, - template, - VerifyLookupType.Sms); + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value + .FirstOrDefault() ?? + new CountOutboxDto(); } - public async Task VerifyLookup( - string receptor, - string token, - string template, - VerifyLookupType type) + public async Task AccountInfo( + CancellationToken cancellationToken = default) { - return await VerifyLookup( - receptor, - token, + var httpResponseMessage = await _httpClientHelper.PostAsync( + "account/info.json", null, null, - template, - type); - } + cancellationToken); - public async Task VerifyLookup( - string receptor, - string token, - string token2, - string token3, - string template) - { - return await VerifyLookup( - receptor, - token, - token2, - token3, - template, - VerifyLookupType.Sms); + return (await httpResponseMessage.Deserialize>(cancellationToken))?.Value ?? + new AccountInfoDto(); } - public async Task VerifyLookup( - string receptor, - string token, - string token2, - string token3, - string token10, - string template) + public async Task AccountConfig( + string? apiLogs, + string? dailyReport, + string? debugMode, + string? defaultSender, + int? minCreditAlarm, + string? resendFailed, + CancellationToken cancellationToken = default) { - return await VerifyLookup( - receptor, - token, - token2, - token3, - token10, - template, - VerifyLookupType.Sms); - } + var queryParams = new Dictionary(); - public async Task VerifyLookup( - string receptor, - string token, - string token2, - string token3, - string template, - VerifyLookupType type) - { - return await VerifyLookup( - receptor, - token, - token2, - token3, - null, - template, - type); - } + if (string.IsNullOrWhiteSpace(apiLogs)) queryParams.Add("apilogs", apiLogs); - public async Task VerifyLookup( - string receptor, - string token, - string token2, - string token3, - string token10, - string template, - VerifyLookupType type) - { - return await VerifyLookup( - receptor, - token, - token2, - token3, - token10, + if (string.IsNullOrWhiteSpace(dailyReport)) queryParams.Add("dailyreport", dailyReport); + + if (string.IsNullOrWhiteSpace(debugMode)) queryParams.Add("debugmode", debugMode); + + if (string.IsNullOrWhiteSpace(defaultSender)) queryParams.Add("defaultsender", defaultSender); + + queryParams.Add("mincreditalarm", minCreditAlarm); + + if (string.IsNullOrWhiteSpace(resendFailed)) queryParams.Add("resendfailed", resendFailed); + + var httpResponseMessage = await _httpClientHelper.PostAsync( + "account/config.json", null, - template, - type); + queryParams, + cancellationToken); + + return (await httpResponseMessage.Deserialize>(cancellationToken))?.Value ?? + new AccountConfigDto(); } public async Task VerifyLookup( string receptor, - string token, - string token2, - string token3, - string token10, - string token20, string template, - VerifyLookupType type) - { - var path = GetApiPath( - "verify", - "lookup", - "json"); - var param = new Dictionary + string token1, + string? token2 = null, + string? token3 = null, + string? token4 = null, + string? token5 = null, + VerifyLookupType? type = null, + CancellationToken cancellationToken = default) + { + var queryParams = new Dictionary { { "receptor", receptor @@ -895,115 +470,28 @@ public async Task VerifyLookup( "template", template }, { - "token", token - }, - { - "token2", token2 - }, - { - "token3", token3 - }, - { - "token10", token10 - }, - { - "token20", token20 - }, - { - "type", type + "token", token1 } }; - var responsebody = await Execute(path, param); - var l = JsonConvert.DeserializeObject(responsebody); - return l.entries[0]; - } - private string GetApiPath( - string @base, - string method, - string output) - { - return string.Format( - ApiPath, - @base, - method, - output); - } + if (string.IsNullOrWhiteSpace(token2)) queryParams.Add("token2", token2); - private async Task Execute( - string path, - Dictionary @params) - { - var nvc = @params?.Select(x => new KeyValuePair(x.Key, x.Value?.ToString())); - - var postdata = new FormUrlEncodedContent(nvc); - - var response = await _client.PostAsync(path, postdata); - var responseBody = await response.Content.ReadAsStringAsync(); - - var result = JsonConvert.DeserializeObject(responseBody); + if (string.IsNullOrWhiteSpace(token3)) queryParams.Add("token3", token3); - if (response.StatusCode != HttpStatusCode.OK) - throw new ApiException(result.Return.Message, result.Return.Status); - - return responseBody; - } + if (string.IsNullOrWhiteSpace(token4)) queryParams.Add("token10", token4); + if (string.IsNullOrWhiteSpace(token5)) queryParams.Add("token20", token5); - #region << CallMakeTts >> + if (type.HasValue) queryParams.Add("type", type.Value.ToString()); - public async Task CallMakeTts( - string message, - string receptor) - { - return (await CallMakeTts( - message, - new List - { - receptor - }, - null, - null))[0]; - } - - public async Task> CallMakeTts( - string message, - List receptor) - { - return await CallMakeTts( - message, - receptor, + var httpResponseMessage = await _httpClientHelper.PostAsync( + "verify/lookup.json", null, - null); - } - - public async Task> CallMakeTts( - string message, - List receptor, - DateTime? date, - List localId) - { - var path = GetApiPath( - "call", - "maketts", - "json"); - var param = new Dictionary - { - { - "receptor", string.Join(",", receptor) - }, - { - "message", WebUtility.HtmlEncode(message) - } - }; - if (date != null) param.Add("date", date.Value.ToUnixTimestamp()); - if (localId != null && - localId.Count > 0) - param.Add("localId", string.Join(",", localId)); - var responseBody = await Execute(path, param); + queryParams, + cancellationToken); - return JsonConvert.DeserializeObject(responseBody).entries; + return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value + .FirstOrDefault() ?? + new SendResult(); } - - #endregion << CallMakeTts >> } \ No newline at end of file diff --git a/Kavenegar.Core/KavenegarApi2.cs b/Kavenegar.Core/KavenegarApi2.cs deleted file mode 100644 index 5f4860f..0000000 --- a/Kavenegar.Core/KavenegarApi2.cs +++ /dev/null @@ -1,449 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using AutoMapper; -using Kavenegar.Core.Dto; -using Kavenegar.Core.Models; -using Kavenegar.Core.Models.Enums; -using Kavenegar.Core.Utils; -using Shared.Infrastructure; - -namespace Kavenegar.Core; - -internal class KavenegarApi2 : IKavenegarApi2 -{ - private readonly HttpClientHelper _httpClientHelper; - private readonly IMapper _mapper; - - public KavenegarApi2( - string apiKey, - IMapper mapper) - { - _mapper = mapper; - _httpClientHelper = new HttpClientHelper - { - BaseAddress = $"https://api.kavenegar.com/v1/{apiKey}" - }; - } - - public async Task Send( - SendSingleMessageRequest message, - CancellationToken cancellationToken = default) - { - var requestParams = _mapper.Map(message).ParametrizeObject(); - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/send.json", - null, - requestParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))!.Value - .FirstOrDefault(); - } - - public async Task> Send( - SendMultiMessageRequest messages, - CancellationToken cancellationToken = default) - { - var requestParams = _mapper.Map(messages).ParametrizeObject(); - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/send.json", - null, - requestParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))!.Value; - } - - public async Task Status( - string messageId, - CancellationToken cancellationToken = default) - { - return (await Status( - new List - { - messageId - }, - cancellationToken)).FirstOrDefault()!; - } - - public async Task> Status( - List messageIds, - CancellationToken cancellationToken = default) - { - var queryParams = new Dictionary - { - { - "messageid", string.Join(',', messageIds) - } - }; - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/status.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? - new List(); - } - - public async Task StatusLocalMessageId( - string messageId, - CancellationToken cancellationToken = default) - { - return (await StatusLocalMessageId( - new List - { - messageId - }, - cancellationToken)).FirstOrDefault()!; - } - - public async Task> StatusLocalMessageId( - List messageIds, - CancellationToken cancellationToken = default) - { - var queryParams = new Dictionary - { - { - "messageid", string.Join(',', messageIds) - } - }; - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/statuslocalmessageid.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken)) - ?.Value ?? - new List(); - } - - public async Task Select( - string messageId, - CancellationToken cancellationToken = default) - { - return (await Select( - new List - { - messageId - }, - cancellationToken)).FirstOrDefault()!; - } - - public async Task> Select( - List messageIds, - CancellationToken cancellationToken = default) - { - var queryParams = new Dictionary - { - { - "messageid", string.Join(',', messageIds) - } - }; - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/select.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? - new List(); - } - - public async Task> SelectOutbox( - DateTime startDate, - DateTime? endDate, - string? sender, - CancellationToken cancellationToken = default) - { - if (endDate <= startDate) throw new ArgumentException("تاریخ پایان نباید از تاریخ شروع کوچکتر باشد."); - - if ((endDate - startDate)!.Value.TotalDays > 1) - throw new ArgumentException( - "حداکثر فاصله زمانی بین متغیر startdate تا متغیر enddate برابر با 1 روز می باشد."); - - if (startDate < DateTime.Now.AddDays(-60)) - throw new ArgumentException("تاریخ شروع startdate حداکثر باید تا 60 روز قبل باشد."); - - var queryParams = new Dictionary - { - { - "startdate", startDate.ToUnixTimestamp() - } - }; - - if (endDate.HasValue) queryParams.Add("endate", endDate.Value.ToUnixTimestamp()); - - if (string.IsNullOrWhiteSpace(sender)) queryParams.Add("sender", sender); - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/selectoutbox.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? - new List(); - } - - public async Task> LatestOutbox( - long? pageSize, - string? sender, - CancellationToken cancellationToken = default) - { - if (pageSize is > 500) throw new ArgumentException("تعداد رکورد های خروجی این متد حداکثر 500 رکورد می‌باشد."); - - pageSize ??= 500; - - var queryParams = new Dictionary - { - { - "pagesize", pageSize - } - }; - - if (string.IsNullOrWhiteSpace(sender)) queryParams.Add("sender", sender); - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/latestoutbox.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? - new List(); - } - - public async Task CountOutbox( - DateTime startDate, - DateTime? endDate, - int? status, - CancellationToken cancellationToken = default) - { - if (endDate <= startDate) throw new ArgumentException("تاریخ پایان نباید از تاریخ شروع کوچکتر باشد."); - - if ((endDate - startDate)!.Value.TotalDays > 1) - throw new ArgumentException( - "حداکثر فاصله زمانی بین متغیر startdate تا متغیر enddate برابر با 1 روز می باشد."); - - if (startDate < DateTime.Now.AddDays(-60)) - throw new ArgumentException("تاریخ شروع startdate حداکثر باید تا 60 روز قبل باشد."); - - var queryParams = new Dictionary - { - { - "startdate", startDate.ToUnixTimestamp() - } - }; - - if (endDate.HasValue) queryParams.Add("endate", endDate.Value.ToUnixTimestamp()); - - if (status.HasValue) queryParams.Add("status", status); - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/countoutbox.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value - .FirstOrDefault() ?? - new CountOutboxResult(); - } - - public async Task Cancel( - string messageId, - CancellationToken cancellationToken = default) - { - return (await Cancel( - new List - { - messageId - }, - cancellationToken)).FirstOrDefault()!; - } - - public async Task> Cancel( - List ids, - CancellationToken cancellationToken = default) - { - var queryParams = new Dictionary - { - { - "messageid", string.Join(',', ids) - } - }; - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/cancel.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? - new List(); - } - - public async Task> Receive( - string line, - bool isRead, - CancellationToken cancellationToken = default) - { - var queryParams = new Dictionary - { - { - "linenumber", line - }, - { - "isread", isRead ? 1 : 0 - } - }; - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/receive.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? - new List(); - } - - public async Task CountInbox( - DateTime startDate, - DateTime? endDate, - string? lineNumber, - bool? isRead, - CancellationToken cancellationToken = default) - { - if (endDate <= startDate) throw new ArgumentException("تاریخ پایان نباید از تاریخ شروع کوچکتر باشد."); - - if ((endDate - startDate)!.Value.TotalDays > 1) - throw new ArgumentException( - "حداکثر فاصله زمانی بین متغیر startdate تا متغیر enddate برابر با 1 روز می باشد."); - - if (startDate < DateTime.Now.AddDays(-60)) - throw new ArgumentException("تاریخ شروع startdate حداکثر باید تا 60 روز قبل باشد."); - - var queryParams = new Dictionary - { - { - "startdate", startDate.ToUnixTimestamp() - } - }; - - if (endDate.HasValue) queryParams.Add("endate", endDate.Value.ToUnixTimestamp()); - if (string.IsNullOrWhiteSpace(lineNumber)) queryParams.Add("linenumber", lineNumber); - if (isRead.HasValue) queryParams.Add("isread", isRead.Value ? 1 : 0); - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/countinbox.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value - .FirstOrDefault() ?? - new CountOutboxResult(); - } - - public async Task AccountInfo( - CancellationToken cancellationToken = default) - { - var httpResponseMessage = await _httpClientHelper.PostAsync( - "account/info.json", - null, - null, - cancellationToken); - - return (await httpResponseMessage.Deserialize>(cancellationToken))?.Value ?? - new AccountInfoResult(); - } - - public async Task AccountConfig( - string? apiLogs, - string? dailyReport, - string? debugMode, - string? defaultSender, - int? minCreditAlarm, - string? resendFailed, - CancellationToken cancellationToken = default) - { - var queryParams = new Dictionary(); - - if (string.IsNullOrWhiteSpace(apiLogs)) queryParams.Add("apilogs", apiLogs); - - if (string.IsNullOrWhiteSpace(dailyReport)) queryParams.Add("dailyreport", dailyReport); - - if (string.IsNullOrWhiteSpace(debugMode)) queryParams.Add("debugmode", debugMode); - - if (string.IsNullOrWhiteSpace(defaultSender)) queryParams.Add("defaultsender", defaultSender); - - queryParams.Add("mincreditalarm", minCreditAlarm); - - if (string.IsNullOrWhiteSpace(resendFailed)) queryParams.Add("resendfailed", resendFailed); - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "account/config.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>(cancellationToken))?.Value ?? - new AccountConfigResult(); - } - - public async Task VerifyLookup( - string receptor, - string template, - string token1, - string? token2 = null, - string? token3 = null, - string? token4 = null, - string? token5 = null, - VerifyLookupType? type = null, - CancellationToken cancellationToken = default) - { - var queryParams = new Dictionary - { - { - "receptor", receptor - }, - { - "template", template - }, - { - "token", token1 - } - }; - - if (string.IsNullOrWhiteSpace(token2)) queryParams.Add("token2", token2); - - if (string.IsNullOrWhiteSpace(token3)) queryParams.Add("token3", token3); - - if (string.IsNullOrWhiteSpace(token4)) queryParams.Add("token10", token4); - - if (string.IsNullOrWhiteSpace(token5)) queryParams.Add("token20", token5); - - if (type.HasValue) queryParams.Add("type", type.Value.ToString()); - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "verify/lookup.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value - .FirstOrDefault() ?? - new SendResult(); - } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/AccountConfigResult.cs b/Kavenegar.Core/Models/AccountConfigResult.cs deleted file mode 100644 index 0d844c2..0000000 --- a/Kavenegar.Core/Models/AccountConfigResult.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Kavenegar.Core.Models; - -public class AccountConfigResult -{ - public string ApiLogs { get; set; } - public string DailyReport { get; set; } - public string DebugMode { get; set; } - public string DefaultSender { get; set; } - public string MinCreditAlarm { get; set; } - public string ResendFailed { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/AccountInfoResult.cs b/Kavenegar.Core/Models/AccountInfoResult.cs deleted file mode 100644 index 01aa475..0000000 --- a/Kavenegar.Core/Models/AccountInfoResult.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using Kavenegar.Core.Utils; - -namespace Kavenegar.Core.Models; - -public class AccountInfoResult -{ - public long RemainCredit { get; set; } - public long Expiredate { get; set; } - - public DateTime GregorianExpiredate => Expiredate.ToDateTime(); - - public string Type { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/CountOutboxResult.cs b/Kavenegar.Core/Models/CountOutboxResult.cs deleted file mode 100644 index 9efa686..0000000 --- a/Kavenegar.Core/Models/CountOutboxResult.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Kavenegar.Core.Models; - -public class CountOutboxResult : CountInboxResult -{ - public long SumPart { get; set; } - public long Cost { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/CountPostalCodeResult.cs b/Kavenegar.Core/Models/CountPostalCodeResult.cs deleted file mode 100644 index 2a312df..0000000 --- a/Kavenegar.Core/Models/CountPostalCodeResult.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Kavenegar.Core.Models; - -public class CountPostalCodeResult -{ - public string Section { get; set; } - public int Value { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/MessageInfo.cs b/Kavenegar.Core/Models/MessageInfo.cs deleted file mode 100644 index 7f00171..0000000 --- a/Kavenegar.Core/Models/MessageInfo.cs +++ /dev/null @@ -1,11 +0,0 @@ -using Kavenegar.Core.Models.Enums; - -namespace Kavenegar.Core.Models; - -public class MessageInfo -{ - public string Sender { get; set; } = null!; - public string Message { get; set; } = null!; - public MessageType Type { get; set; } - public string LocalMessageId { get; set; } = null!; -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/ReceiveResult.cs b/Kavenegar.Core/Models/ReceiveResult.cs deleted file mode 100644 index de2f86f..0000000 --- a/Kavenegar.Core/Models/ReceiveResult.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using Kavenegar.Core.Utils; - -namespace Kavenegar.Core.Models; - -public class ReceiveResult -{ - public long Date { get; set; } - - public DateTime GregorianDate => Date.ToDateTime(); - - public long MessageId { get; set; } - - public string Sender { get; set; } - - public string Message { get; set; } - - public string Receptor { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/ReturnAccountConfig.cs b/Kavenegar.Core/Models/ReturnAccountConfig.cs deleted file mode 100644 index b71fb3c..0000000 --- a/Kavenegar.Core/Models/ReturnAccountConfig.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Kavenegar.Core.Models; - -namespace Kavenegar.Core; - -internal class ReturnAccountConfig -{ - public Result result { get; set; } - public AccountConfigResult entries { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/ReturnAccountInfo.cs b/Kavenegar.Core/Models/ReturnAccountInfo.cs deleted file mode 100644 index a31b52b..0000000 --- a/Kavenegar.Core/Models/ReturnAccountInfo.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Kavenegar.Core.Models; - -namespace Kavenegar.Core; - -internal class ReturnAccountInfo -{ - public Result result { get; set; } - public AccountInfoResult entries { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/ReturnCountInbox.cs b/Kavenegar.Core/Models/ReturnCountInbox.cs deleted file mode 100644 index e77f9b3..0000000 --- a/Kavenegar.Core/Models/ReturnCountInbox.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Collections.Generic; -using Kavenegar.Core.Models; - -namespace Kavenegar.Core; - -internal class ReturnCountInbox -{ - public Result result { get; set; } - public List entries { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/ReturnCountOutbox.cs b/Kavenegar.Core/Models/ReturnCountOutbox.cs deleted file mode 100644 index 10ea22a..0000000 --- a/Kavenegar.Core/Models/ReturnCountOutbox.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Collections.Generic; -using Kavenegar.Core.Models; - -namespace Kavenegar.Core; - -internal class ReturnCountOutbox -{ - public Result result { get; set; } - public List entries { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/ReturnCountPostalCode.cs b/Kavenegar.Core/Models/ReturnCountPostalCode.cs deleted file mode 100644 index 002f51c..0000000 --- a/Kavenegar.Core/Models/ReturnCountPostalCode.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Collections.Generic; -using Kavenegar.Core.Models; - -namespace Kavenegar.Core; - -internal class ReturnCountPostalCode -{ - public Result result { get; set; } - public List entries { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/ReturnReceive.cs b/Kavenegar.Core/Models/ReturnReceive.cs deleted file mode 100644 index aded919..0000000 --- a/Kavenegar.Core/Models/ReturnReceive.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Collections.Generic; -using Kavenegar.Core.Models; - -namespace Kavenegar.Core; - -internal class ReturnReceive -{ - public Result result { get; set; } - public List entries { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/ReturnResult.cs b/Kavenegar.Core/Models/ReturnResult.cs deleted file mode 100644 index 3633bec..0000000 --- a/Kavenegar.Core/Models/ReturnResult.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Kavenegar.Core.Models; - -namespace Kavenegar.Core; - -internal class ReturnResult -{ - public Result Return { get; set; } - public object entries { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/ReturnSend.cs b/Kavenegar.Core/Models/ReturnSend.cs deleted file mode 100644 index 0581a88..0000000 --- a/Kavenegar.Core/Models/ReturnSend.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Collections.Generic; -using Kavenegar.Core.Models; - -namespace Kavenegar.Core; - -internal class ReturnSend -{ - public Result Return { get; set; } - public List entries { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/ReturnStatus.cs b/Kavenegar.Core/Models/ReturnStatus.cs deleted file mode 100644 index 37589f7..0000000 --- a/Kavenegar.Core/Models/ReturnStatus.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Collections.Generic; -using Kavenegar.Core.Models; - -namespace Kavenegar.Core; - -internal class ReturnStatus -{ - public Result result { get; set; } - public List entries { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/ReturnStatusLocalMessageId.cs b/Kavenegar.Core/Models/ReturnStatusLocalMessageId.cs deleted file mode 100644 index d124aad..0000000 --- a/Kavenegar.Core/Models/ReturnStatusLocalMessageId.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Collections.Generic; -using Kavenegar.Core.Models; - -namespace Kavenegar.Core; - -internal class ReturnStatusLocalMessageId -{ - public Result result { get; set; } - public List entries { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/SendMultiMessageRequest.cs b/Kavenegar.Core/Models/SendMultiMessageRequest.cs deleted file mode 100644 index fc3df2f..0000000 --- a/Kavenegar.Core/Models/SendMultiMessageRequest.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Kavenegar.Core.Models; - -public class SendMultiMessageRequest -{ - public Dictionary Messages { get; set; } = null!; - public DateTime Date { get; set; } - public bool Hide { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/SendMultiMessageRequestDto.cs b/Kavenegar.Core/Models/SendMultiMessageRequestDto.cs deleted file mode 100644 index 4630d2d..0000000 --- a/Kavenegar.Core/Models/SendMultiMessageRequestDto.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.ComponentModel.DataAnnotations.Schema; - -namespace Kavenegar.Core.Models; - -internal class SendMultiMessageRequestDto -{ - [Column("receptor", Order = 1)] - public string Receptors { get; set; } = null!; - - [Column("sender", Order = 2)] - public string? Sender { get; set; } - - [Column("message", Order = 3)] - public string Message { get; set; } = null!; - - [Column("date", Order = 4)] - public long Date { get; set; } - - [Column("type", Order = 5)] - public int Type { get; set; } - - [Column("localmessageids", Order = 6)] - public string LocalMessageId { get; set; } = null!; - - [Column("hide", Order = 7)] - public int Hide { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/SendSingleMessageRequest.cs b/Kavenegar.Core/Models/SendSingleMessageRequest.cs deleted file mode 100644 index d856bf4..0000000 --- a/Kavenegar.Core/Models/SendSingleMessageRequest.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Kavenegar.Core.Models; - -public class SendSingleMessageRequest -{ - public MessageInfo MessageInfo { get; set; } = null!; - public IEnumerable Receptors { get; set; } = null!; - public DateTime Date { get; set; } - public bool Hide { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/SendSingleMessageRequestDto.cs b/Kavenegar.Core/Models/SendSingleMessageRequestDto.cs deleted file mode 100644 index a50f74e..0000000 --- a/Kavenegar.Core/Models/SendSingleMessageRequestDto.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.ComponentModel.DataAnnotations.Schema; - -namespace Kavenegar.Core.Models; - -internal class SendSingleMessageRequestDto -{ - [Column("receptor", Order = 1)] - public string Receptors { get; set; } = null!; - - [Column("sender", Order = 2)] - public string? Sender { get; set; } - - [Column("message", Order = 3)] - public string Message { get; set; } = null!; - - [Column("date", Order = 4)] - public long Date { get; set; } - - [Column("type", Order = 5)] - public int Type { get; set; } - - [Column("localid", Order = 6)] - public string LocalMessageId { get; set; } = null!; - - [Column("hide", Order = 7)] - public int Hide { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/StatusLocalMessageIdResult.cs b/Kavenegar.Core/Models/StatusLocalMessageIdResult.cs deleted file mode 100644 index 088063e..0000000 --- a/Kavenegar.Core/Models/StatusLocalMessageIdResult.cs +++ /dev/null @@ -1,11 +0,0 @@ -using Kavenegar.Core.Models.Enums; - -namespace Kavenegar.Core.Models; - -public class StatusLocalMessageIdResult -{ - public long Messageid { get; set; } - public long Localid { get; set; } - public MessageStatus Status { get; set; } - public string Statustext { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.Core/Models/StatusResult.cs b/Kavenegar.Core/Models/StatusResult.cs deleted file mode 100644 index 298216f..0000000 --- a/Kavenegar.Core/Models/StatusResult.cs +++ /dev/null @@ -1,10 +0,0 @@ -using Kavenegar.Core.Models.Enums; - -namespace Kavenegar.Core.Models; - -public class StatusResult -{ - public long Messageid { get; set; } - public MessageStatus Status { get; set; } - public string Statustext { get; set; } -} \ No newline at end of file diff --git a/Kavenegar.sln b/Kavenegar.sln index 65964ff..5a867be 100644 --- a/Kavenegar.sln +++ b/Kavenegar.sln @@ -1,25 +1,25 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kavenegar.Core", "Kavenegar.Core\Kavenegar.Core.csproj", "{4B4EA3FD-4296-4A75-9A59-04BC580BC846}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Shared", "Shared", "{0E27FAE0-128A-4B33-86AC-EC949911C220}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Shared.Infrastructure", "Shared\Shared.Infrastructure\Shared.Infrastructure.csproj", "{5A102430-241D-46A1-A615-0149411194D5}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kavenegar.Core", "Kavenegar.Core\Kavenegar.Core.csproj", "{35D0DBF6-25F0-4DEB-9BC8-D3C3B65933EB}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {4B4EA3FD-4296-4A75-9A59-04BC580BC846}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4B4EA3FD-4296-4A75-9A59-04BC580BC846}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4B4EA3FD-4296-4A75-9A59-04BC580BC846}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4B4EA3FD-4296-4A75-9A59-04BC580BC846}.Release|Any CPU.Build.0 = Release|Any CPU {5A102430-241D-46A1-A615-0149411194D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5A102430-241D-46A1-A615-0149411194D5}.Debug|Any CPU.Build.0 = Debug|Any CPU {5A102430-241D-46A1-A615-0149411194D5}.Release|Any CPU.ActiveCfg = Release|Any CPU {5A102430-241D-46A1-A615-0149411194D5}.Release|Any CPU.Build.0 = Release|Any CPU + {35D0DBF6-25F0-4DEB-9BC8-D3C3B65933EB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {35D0DBF6-25F0-4DEB-9BC8-D3C3B65933EB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {35D0DBF6-25F0-4DEB-9BC8-D3C3B65933EB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {35D0DBF6-25F0-4DEB-9BC8-D3C3B65933EB}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {5A102430-241D-46A1-A615-0149411194D5} = {0E27FAE0-128A-4B33-86AC-EC949911C220} diff --git a/Kavenegar.sln.DotSettings b/Kavenegar.sln.DotSettings index a44ce49..17fefcb 100644 --- a/Kavenegar.sln.DotSettings +++ b/Kavenegar.sln.DotSettings @@ -1,2 +1,36 @@  - True \ No newline at end of file + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True \ No newline at end of file diff --git a/Kavenegar.Core/Utils/DateHelper.cs b/Shared/Shared.Infrastructure/DateHelper.cs similarity index 94% rename from Kavenegar.Core/Utils/DateHelper.cs rename to Shared/Shared.Infrastructure/DateHelper.cs index c50c2a4..686df89 100644 --- a/Kavenegar.Core/Utils/DateHelper.cs +++ b/Shared/Shared.Infrastructure/DateHelper.cs @@ -1,6 +1,4 @@ -using System; - -namespace Kavenegar.Core.Utils; +namespace Shared.Infrastructure; public static class DateHelper { From a789c61c7c20ed6baaecb549eb45a01cf15c797d Mon Sep 17 00:00:00 2001 From: alireza995 <88311706+alireza995@users.noreply.github.com> Date: Sun, 4 Dec 2022 01:12:57 +0330 Subject: [PATCH 05/14] refactor(Solution) : Remove unused enum Remove unused enum closes nothing --- Kavenegar.Core/Dto/Message/MessageInfo.cs | 14 +++++------- .../Dto/Message/SendSingleMessageRequest.cs | 9 ++++---- Kavenegar.Core/Dto/Result/AccountConfigDto.cs | 10 ++++----- Kavenegar.Core/Dto/Result/LocalStatusDto.cs | 1 - .../Dto/Result/ReceivedMessageDto.cs | 6 ++--- Kavenegar.Core/Dto/Result/StatusMessageDto.cs | 1 - Kavenegar.Core/Enums/MessageStatus.cs | 2 +- Kavenegar.Core/Enums/MetaCode.cs | 22 ------------------- Kavenegar.Core/IKavenegarApi.cs | 2 -- Kavenegar.Core/Kavenegar.Core.csproj | 4 ++-- Kavenegar.sln | 3 --- 11 files changed, 22 insertions(+), 52 deletions(-) delete mode 100644 Kavenegar.Core/Enums/MetaCode.cs diff --git a/Kavenegar.Core/Dto/Message/MessageInfo.cs b/Kavenegar.Core/Dto/Message/MessageInfo.cs index 1392503..c7053bc 100644 --- a/Kavenegar.Core/Dto/Message/MessageInfo.cs +++ b/Kavenegar.Core/Dto/Message/MessageInfo.cs @@ -1,12 +1,10 @@ using Kavenegar.Core.Enums; -using Kavenegar.Core.Models.Enums; -namespace Kavenegar.Core.Dto.Message +namespace Kavenegar.Core.Dto.Message; + +public class MessageInfo { - public class MessageInfo - { - public string Sender { get; set; } = null!; - public string Message { get; set; } = null!; - public MessageType Type { get; set; } - } + public string Sender { get; set; } = null!; + public string Message { get; set; } = null!; + public MessageType Type { get; set; } } \ No newline at end of file diff --git a/Kavenegar.Core/Dto/Message/SendSingleMessageRequest.cs b/Kavenegar.Core/Dto/Message/SendSingleMessageRequest.cs index e5edf01..a16414f 100644 --- a/Kavenegar.Core/Dto/Message/SendSingleMessageRequest.cs +++ b/Kavenegar.Core/Dto/Message/SendSingleMessageRequest.cs @@ -3,12 +3,13 @@ public class SendSingleMessageRequest { public MessageInfo MessageInfo { get; set; } = null!; - + /// - /// Key is receptor - /// Value is local message id + /// Key is receptor + /// Value is local message id /// - public Dictionary ReceptorLocalMessageIds { get; set; } = null!; + public Dictionary ReceptorLocalMessageIds { get; set; } = null!; + public DateTime? Date { get; set; } public bool Hide { get; set; } } \ No newline at end of file diff --git a/Kavenegar.Core/Dto/Result/AccountConfigDto.cs b/Kavenegar.Core/Dto/Result/AccountConfigDto.cs index 403d579..73517d8 100644 --- a/Kavenegar.Core/Dto/Result/AccountConfigDto.cs +++ b/Kavenegar.Core/Dto/Result/AccountConfigDto.cs @@ -3,9 +3,9 @@ namespace Kavenegar.Core.Dto.Result; public class AccountConfigDto { public string ApiLogs { get; set; } = null!; - public string DailyReport { get; set; }= null!; - public string DebugMode { get; set; }= null!; - public string DefaultSender { get; set; }= null!; - public string MinCreditAlarm { get; set; }= null!; - public string ResendFailed { get; set; }= null!; + public string DailyReport { get; set; } = null!; + public string DebugMode { get; set; } = null!; + public string DefaultSender { get; set; } = null!; + public string MinCreditAlarm { get; set; } = null!; + public string ResendFailed { get; set; } = null!; } \ No newline at end of file diff --git a/Kavenegar.Core/Dto/Result/LocalStatusDto.cs b/Kavenegar.Core/Dto/Result/LocalStatusDto.cs index 3d2f1d8..9e16a07 100644 --- a/Kavenegar.Core/Dto/Result/LocalStatusDto.cs +++ b/Kavenegar.Core/Dto/Result/LocalStatusDto.cs @@ -1,5 +1,4 @@ using Kavenegar.Core.Enums; -using Kavenegar.Core.Models.Enums; namespace Kavenegar.Core.Dto.Result; diff --git a/Kavenegar.Core/Dto/Result/ReceivedMessageDto.cs b/Kavenegar.Core/Dto/Result/ReceivedMessageDto.cs index b3806b8..9a082ed 100644 --- a/Kavenegar.Core/Dto/Result/ReceivedMessageDto.cs +++ b/Kavenegar.Core/Dto/Result/ReceivedMessageDto.cs @@ -7,7 +7,7 @@ public class ReceivedMessageDto public long Date { get; set; } public DateTime GregorianDate => Date.ToDateTime(); public long MessageId { get; set; } - public string Sender { get; set; }= null!; - public string Message { get; set; }= null!; - public string Receptor { get; set; }= null!; + public string Sender { get; set; } = null!; + public string Message { get; set; } = null!; + public string Receptor { get; set; } = null!; } \ No newline at end of file diff --git a/Kavenegar.Core/Dto/Result/StatusMessageDto.cs b/Kavenegar.Core/Dto/Result/StatusMessageDto.cs index 620950c..825b927 100644 --- a/Kavenegar.Core/Dto/Result/StatusMessageDto.cs +++ b/Kavenegar.Core/Dto/Result/StatusMessageDto.cs @@ -1,5 +1,4 @@ using Kavenegar.Core.Enums; -using Kavenegar.Core.Models.Enums; namespace Kavenegar.Core.Dto.Result; diff --git a/Kavenegar.Core/Enums/MessageStatus.cs b/Kavenegar.Core/Enums/MessageStatus.cs index 8308897..9f00180 100644 --- a/Kavenegar.Core/Enums/MessageStatus.cs +++ b/Kavenegar.Core/Enums/MessageStatus.cs @@ -5,7 +5,7 @@ public enum MessageStatus Queued = 1, Scheduled = 2, SentToCenter = 4, - AlsoSentToCenter = 5, + SentToCenter2 = 5, Delivered = 10, Undelivered = 11, Canceled = 13, diff --git a/Kavenegar.Core/Enums/MetaCode.cs b/Kavenegar.Core/Enums/MetaCode.cs deleted file mode 100644 index 3d4ddaf..0000000 --- a/Kavenegar.Core/Enums/MetaCode.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace Kavenegar.Core.Models.Enums; - -public enum MetaCode -{ - NotChecked = 99, - Approved = 100, - InvalidApiKey = 101, - ExpiredApiKey = 102, - AccountDisabled = 103, - NotEnoughCredit = 104, - ServerisBusy = 105, - UndefinedCommand = 106, - RequestFailed = 107, - ParametersBroken = 108, - InvalidRecp = 110, - InvalidSenderNumber = 111, - EmptyMessage = 112, - RecpIsTooLarge = 113, - InvalidDate = 114, - MsgIsTooLarge = 115, - RecpNotEqualWithMessage = 116 -} \ No newline at end of file diff --git a/Kavenegar.Core/IKavenegarApi.cs b/Kavenegar.Core/IKavenegarApi.cs index 519bf03..379ce1f 100644 --- a/Kavenegar.Core/IKavenegarApi.cs +++ b/Kavenegar.Core/IKavenegarApi.cs @@ -1,8 +1,6 @@ using Kavenegar.Core.Dto.Message; using Kavenegar.Core.Dto.Result; using Kavenegar.Core.Enums; -using Kavenegar.Core.Models; -using Kavenegar.Core.Models.Enums; namespace Kavenegar.Core; diff --git a/Kavenegar.Core/Kavenegar.Core.csproj b/Kavenegar.Core/Kavenegar.Core.csproj index e9094f5..7117abf 100644 --- a/Kavenegar.Core/Kavenegar.Core.csproj +++ b/Kavenegar.Core/Kavenegar.Core.csproj @@ -7,11 +7,11 @@ - + - + diff --git a/Kavenegar.sln b/Kavenegar.sln index 5a867be..a636930 100644 --- a/Kavenegar.sln +++ b/Kavenegar.sln @@ -1,7 +1,5 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Shared", "Shared", "{0E27FAE0-128A-4B33-86AC-EC949911C220}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Shared.Infrastructure", "Shared\Shared.Infrastructure\Shared.Infrastructure.csproj", "{5A102430-241D-46A1-A615-0149411194D5}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kavenegar.Core", "Kavenegar.Core\Kavenegar.Core.csproj", "{35D0DBF6-25F0-4DEB-9BC8-D3C3B65933EB}" @@ -22,6 +20,5 @@ Global {35D0DBF6-25F0-4DEB-9BC8-D3C3B65933EB}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution - {5A102430-241D-46A1-A615-0149411194D5} = {0E27FAE0-128A-4B33-86AC-EC949911C220} EndGlobalSection EndGlobal From f307c4ebe063225416e950a05d12fb3b711dfd55 Mon Sep 17 00:00:00 2001 From: alireza995 <88311706+alireza995@users.noreply.github.com> Date: Sun, 4 Dec 2022 01:22:13 +0330 Subject: [PATCH 06/14] test(Solution) : relocate codes and create test project relocate codes and create test project --- .../Kavenegar.Core}/DependencyManager.cs | 0 .../Kavenegar.Core}/Dto/Message/MessageInfo.cs | 0 .../Dto/Message/SendMessageInfo.cs | 0 .../Dto/Message/SendMultiMessageRequest.cs | 0 .../Dto/Message/SendSingleMessageRequest.cs | 0 .../Dto/Result/AccountConfigDto.cs | 0 .../Dto/Result/AccountInfoDto.cs | 0 .../Kavenegar.Core}/Dto/Result/CountInboxDto.cs | 0 .../Dto/Result/CountOutboxDto.cs | 0 .../Dto/Result/LocalStatusDto.cs | 0 .../Dto/Result/ReceivedMessageDto.cs | 0 .../Kavenegar.Core}/Dto/Result/ResultDto.cs | 0 .../Kavenegar.Core}/Dto/Result/ResultStatus.cs | 0 .../Kavenegar.Core}/Dto/Result/SendResult.cs | 0 .../Dto/Result/StatusMessageDto.cs | 0 .../Kavenegar.Core}/Enums/MessageStatus.cs | 0 .../Kavenegar.Core}/Enums/MessageType.cs | 0 .../Kavenegar.Core}/Enums/VerifyLookupType.cs | 0 .../Kavenegar.Core}/IKavenegarApi.cs | 0 .../Kavenegar.Core}/Kavenegar.Core.csproj | 0 .../Kavenegar.Core}/KavenegarApi.cs | 0 .../Shared}/Shared.Infrastructure/DateHelper.cs | 0 .../Shared.Infrastructure/HttpClientHelper.cs | 0 .../Shared.Infrastructure/JsonUtility.cs | 0 .../Shared.Infrastructure/QueryParamHelper.cs | 0 .../Shared.Infrastructure.csproj | 0 Kavenegar.sln | 17 +++++++++++++++-- Test/Kavenegar.Core/Kavenegar.Core.csproj | 17 +++++++++++++++++ 28 files changed, 32 insertions(+), 2 deletions(-) rename {Kavenegar.Core => Code/Kavenegar.Core}/DependencyManager.cs (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/Dto/Message/MessageInfo.cs (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/Dto/Message/SendMessageInfo.cs (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/Dto/Message/SendMultiMessageRequest.cs (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/Dto/Message/SendSingleMessageRequest.cs (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/Dto/Result/AccountConfigDto.cs (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/Dto/Result/AccountInfoDto.cs (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/Dto/Result/CountInboxDto.cs (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/Dto/Result/CountOutboxDto.cs (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/Dto/Result/LocalStatusDto.cs (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/Dto/Result/ReceivedMessageDto.cs (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/Dto/Result/ResultDto.cs (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/Dto/Result/ResultStatus.cs (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/Dto/Result/SendResult.cs (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/Dto/Result/StatusMessageDto.cs (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/Enums/MessageStatus.cs (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/Enums/MessageType.cs (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/Enums/VerifyLookupType.cs (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/IKavenegarApi.cs (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/Kavenegar.Core.csproj (100%) rename {Kavenegar.Core => Code/Kavenegar.Core}/KavenegarApi.cs (100%) rename {Shared => Code/Shared}/Shared.Infrastructure/DateHelper.cs (100%) rename {Shared => Code/Shared}/Shared.Infrastructure/HttpClientHelper.cs (100%) rename {Shared => Code/Shared}/Shared.Infrastructure/JsonUtility.cs (100%) rename {Shared => Code/Shared}/Shared.Infrastructure/QueryParamHelper.cs (100%) rename {Shared => Code/Shared}/Shared.Infrastructure/Shared.Infrastructure.csproj (100%) create mode 100644 Test/Kavenegar.Core/Kavenegar.Core.csproj diff --git a/Kavenegar.Core/DependencyManager.cs b/Code/Kavenegar.Core/DependencyManager.cs similarity index 100% rename from Kavenegar.Core/DependencyManager.cs rename to Code/Kavenegar.Core/DependencyManager.cs diff --git a/Kavenegar.Core/Dto/Message/MessageInfo.cs b/Code/Kavenegar.Core/Dto/Message/MessageInfo.cs similarity index 100% rename from Kavenegar.Core/Dto/Message/MessageInfo.cs rename to Code/Kavenegar.Core/Dto/Message/MessageInfo.cs diff --git a/Kavenegar.Core/Dto/Message/SendMessageInfo.cs b/Code/Kavenegar.Core/Dto/Message/SendMessageInfo.cs similarity index 100% rename from Kavenegar.Core/Dto/Message/SendMessageInfo.cs rename to Code/Kavenegar.Core/Dto/Message/SendMessageInfo.cs diff --git a/Kavenegar.Core/Dto/Message/SendMultiMessageRequest.cs b/Code/Kavenegar.Core/Dto/Message/SendMultiMessageRequest.cs similarity index 100% rename from Kavenegar.Core/Dto/Message/SendMultiMessageRequest.cs rename to Code/Kavenegar.Core/Dto/Message/SendMultiMessageRequest.cs diff --git a/Kavenegar.Core/Dto/Message/SendSingleMessageRequest.cs b/Code/Kavenegar.Core/Dto/Message/SendSingleMessageRequest.cs similarity index 100% rename from Kavenegar.Core/Dto/Message/SendSingleMessageRequest.cs rename to Code/Kavenegar.Core/Dto/Message/SendSingleMessageRequest.cs diff --git a/Kavenegar.Core/Dto/Result/AccountConfigDto.cs b/Code/Kavenegar.Core/Dto/Result/AccountConfigDto.cs similarity index 100% rename from Kavenegar.Core/Dto/Result/AccountConfigDto.cs rename to Code/Kavenegar.Core/Dto/Result/AccountConfigDto.cs diff --git a/Kavenegar.Core/Dto/Result/AccountInfoDto.cs b/Code/Kavenegar.Core/Dto/Result/AccountInfoDto.cs similarity index 100% rename from Kavenegar.Core/Dto/Result/AccountInfoDto.cs rename to Code/Kavenegar.Core/Dto/Result/AccountInfoDto.cs diff --git a/Kavenegar.Core/Dto/Result/CountInboxDto.cs b/Code/Kavenegar.Core/Dto/Result/CountInboxDto.cs similarity index 100% rename from Kavenegar.Core/Dto/Result/CountInboxDto.cs rename to Code/Kavenegar.Core/Dto/Result/CountInboxDto.cs diff --git a/Kavenegar.Core/Dto/Result/CountOutboxDto.cs b/Code/Kavenegar.Core/Dto/Result/CountOutboxDto.cs similarity index 100% rename from Kavenegar.Core/Dto/Result/CountOutboxDto.cs rename to Code/Kavenegar.Core/Dto/Result/CountOutboxDto.cs diff --git a/Kavenegar.Core/Dto/Result/LocalStatusDto.cs b/Code/Kavenegar.Core/Dto/Result/LocalStatusDto.cs similarity index 100% rename from Kavenegar.Core/Dto/Result/LocalStatusDto.cs rename to Code/Kavenegar.Core/Dto/Result/LocalStatusDto.cs diff --git a/Kavenegar.Core/Dto/Result/ReceivedMessageDto.cs b/Code/Kavenegar.Core/Dto/Result/ReceivedMessageDto.cs similarity index 100% rename from Kavenegar.Core/Dto/Result/ReceivedMessageDto.cs rename to Code/Kavenegar.Core/Dto/Result/ReceivedMessageDto.cs diff --git a/Kavenegar.Core/Dto/Result/ResultDto.cs b/Code/Kavenegar.Core/Dto/Result/ResultDto.cs similarity index 100% rename from Kavenegar.Core/Dto/Result/ResultDto.cs rename to Code/Kavenegar.Core/Dto/Result/ResultDto.cs diff --git a/Kavenegar.Core/Dto/Result/ResultStatus.cs b/Code/Kavenegar.Core/Dto/Result/ResultStatus.cs similarity index 100% rename from Kavenegar.Core/Dto/Result/ResultStatus.cs rename to Code/Kavenegar.Core/Dto/Result/ResultStatus.cs diff --git a/Kavenegar.Core/Dto/Result/SendResult.cs b/Code/Kavenegar.Core/Dto/Result/SendResult.cs similarity index 100% rename from Kavenegar.Core/Dto/Result/SendResult.cs rename to Code/Kavenegar.Core/Dto/Result/SendResult.cs diff --git a/Kavenegar.Core/Dto/Result/StatusMessageDto.cs b/Code/Kavenegar.Core/Dto/Result/StatusMessageDto.cs similarity index 100% rename from Kavenegar.Core/Dto/Result/StatusMessageDto.cs rename to Code/Kavenegar.Core/Dto/Result/StatusMessageDto.cs diff --git a/Kavenegar.Core/Enums/MessageStatus.cs b/Code/Kavenegar.Core/Enums/MessageStatus.cs similarity index 100% rename from Kavenegar.Core/Enums/MessageStatus.cs rename to Code/Kavenegar.Core/Enums/MessageStatus.cs diff --git a/Kavenegar.Core/Enums/MessageType.cs b/Code/Kavenegar.Core/Enums/MessageType.cs similarity index 100% rename from Kavenegar.Core/Enums/MessageType.cs rename to Code/Kavenegar.Core/Enums/MessageType.cs diff --git a/Kavenegar.Core/Enums/VerifyLookupType.cs b/Code/Kavenegar.Core/Enums/VerifyLookupType.cs similarity index 100% rename from Kavenegar.Core/Enums/VerifyLookupType.cs rename to Code/Kavenegar.Core/Enums/VerifyLookupType.cs diff --git a/Kavenegar.Core/IKavenegarApi.cs b/Code/Kavenegar.Core/IKavenegarApi.cs similarity index 100% rename from Kavenegar.Core/IKavenegarApi.cs rename to Code/Kavenegar.Core/IKavenegarApi.cs diff --git a/Kavenegar.Core/Kavenegar.Core.csproj b/Code/Kavenegar.Core/Kavenegar.Core.csproj similarity index 100% rename from Kavenegar.Core/Kavenegar.Core.csproj rename to Code/Kavenegar.Core/Kavenegar.Core.csproj diff --git a/Kavenegar.Core/KavenegarApi.cs b/Code/Kavenegar.Core/KavenegarApi.cs similarity index 100% rename from Kavenegar.Core/KavenegarApi.cs rename to Code/Kavenegar.Core/KavenegarApi.cs diff --git a/Shared/Shared.Infrastructure/DateHelper.cs b/Code/Shared/Shared.Infrastructure/DateHelper.cs similarity index 100% rename from Shared/Shared.Infrastructure/DateHelper.cs rename to Code/Shared/Shared.Infrastructure/DateHelper.cs diff --git a/Shared/Shared.Infrastructure/HttpClientHelper.cs b/Code/Shared/Shared.Infrastructure/HttpClientHelper.cs similarity index 100% rename from Shared/Shared.Infrastructure/HttpClientHelper.cs rename to Code/Shared/Shared.Infrastructure/HttpClientHelper.cs diff --git a/Shared/Shared.Infrastructure/JsonUtility.cs b/Code/Shared/Shared.Infrastructure/JsonUtility.cs similarity index 100% rename from Shared/Shared.Infrastructure/JsonUtility.cs rename to Code/Shared/Shared.Infrastructure/JsonUtility.cs diff --git a/Shared/Shared.Infrastructure/QueryParamHelper.cs b/Code/Shared/Shared.Infrastructure/QueryParamHelper.cs similarity index 100% rename from Shared/Shared.Infrastructure/QueryParamHelper.cs rename to Code/Shared/Shared.Infrastructure/QueryParamHelper.cs diff --git a/Shared/Shared.Infrastructure/Shared.Infrastructure.csproj b/Code/Shared/Shared.Infrastructure/Shared.Infrastructure.csproj similarity index 100% rename from Shared/Shared.Infrastructure/Shared.Infrastructure.csproj rename to Code/Shared/Shared.Infrastructure/Shared.Infrastructure.csproj diff --git a/Kavenegar.sln b/Kavenegar.sln index a636930..05f8859 100644 --- a/Kavenegar.sln +++ b/Kavenegar.sln @@ -1,8 +1,14 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Shared.Infrastructure", "Shared\Shared.Infrastructure\Shared.Infrastructure.csproj", "{5A102430-241D-46A1-A615-0149411194D5}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Shared.Infrastructure", "Code\Shared\Shared.Infrastructure\Shared.Infrastructure.csproj", "{5A102430-241D-46A1-A615-0149411194D5}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kavenegar.Core", "Kavenegar.Core\Kavenegar.Core.csproj", "{35D0DBF6-25F0-4DEB-9BC8-D3C3B65933EB}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kavenegar.Core", "Code\Kavenegar.Core\Kavenegar.Core.csproj", "{35D0DBF6-25F0-4DEB-9BC8-D3C3B65933EB}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Code", "Code", "{67BC444E-84C9-493C-B776-55FE5D54D560}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{17B39BF3-CC26-40C5-AEB0-87CA2D71B93E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kavenegar.Core", "Test\Kavenegar.Core\Kavenegar.Core.csproj", "{6E36B3F6-2B1D-4506-BA92-007AC00EF317}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -18,7 +24,14 @@ Global {35D0DBF6-25F0-4DEB-9BC8-D3C3B65933EB}.Debug|Any CPU.Build.0 = Debug|Any CPU {35D0DBF6-25F0-4DEB-9BC8-D3C3B65933EB}.Release|Any CPU.ActiveCfg = Release|Any CPU {35D0DBF6-25F0-4DEB-9BC8-D3C3B65933EB}.Release|Any CPU.Build.0 = Release|Any CPU + {6E36B3F6-2B1D-4506-BA92-007AC00EF317}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6E36B3F6-2B1D-4506-BA92-007AC00EF317}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6E36B3F6-2B1D-4506-BA92-007AC00EF317}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6E36B3F6-2B1D-4506-BA92-007AC00EF317}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution + {35D0DBF6-25F0-4DEB-9BC8-D3C3B65933EB} = {67BC444E-84C9-493C-B776-55FE5D54D560} + {5A102430-241D-46A1-A615-0149411194D5} = {67BC444E-84C9-493C-B776-55FE5D54D560} + {6E36B3F6-2B1D-4506-BA92-007AC00EF317} = {17B39BF3-CC26-40C5-AEB0-87CA2D71B93E} EndGlobalSection EndGlobal diff --git a/Test/Kavenegar.Core/Kavenegar.Core.csproj b/Test/Kavenegar.Core/Kavenegar.Core.csproj new file mode 100644 index 0000000..65a4f7b --- /dev/null +++ b/Test/Kavenegar.Core/Kavenegar.Core.csproj @@ -0,0 +1,17 @@ + + + + net6.0 + enable + + false + + + + + + + + + + From 1fb3165aa6ef14fb388afd58531c57bbad035acc Mon Sep 17 00:00:00 2001 From: alireza995 <88311706+alireza995@users.noreply.github.com> Date: Fri, 9 Dec 2022 03:00:35 +0330 Subject: [PATCH 07/14] Refactor(Solution) : refactor and add new methods refactor with separating classes into related activities add new methods to send messages easier dependency manager completed closes nothing --- Code/Kavenegar.Core/BaseKavenegarApi.cs | 35 ++ Code/Kavenegar.Core/DependencyManager.cs | 11 +- .../Kavenegar.Core/Dto/Message/MessageInfo.cs | 2 +- Code/Kavenegar.Core/Dto/Result/SendResult.cs | 13 - .../Dto/Result/SendResultDto.cs | 32 ++ Code/Kavenegar.Core/Enums/MessageStatus.cs | 2 +- .../Kavenegar.Core/IKavenegarMessageSender.cs | 75 +++ ...avenegarApi.cs => IKavenegarProfileApi.cs} | 55 +- Code/Kavenegar.Core/KavenegarApi.cs | 497 ------------------ Code/Kavenegar.Core/KavenegarMessageSender.cs | 234 +++++++++ Code/Kavenegar.Core/KavenegarProfileApi.cs | 314 +++++++++++ .../Shared.Infrastructure/HttpClientHelper.cs | 2 +- .../IHttpClientHelper.cs | 12 + .../Shared.Infrastructure/JsonUtility.cs | 2 +- 14 files changed, 733 insertions(+), 553 deletions(-) create mode 100644 Code/Kavenegar.Core/BaseKavenegarApi.cs delete mode 100644 Code/Kavenegar.Core/Dto/Result/SendResult.cs create mode 100644 Code/Kavenegar.Core/Dto/Result/SendResultDto.cs create mode 100644 Code/Kavenegar.Core/IKavenegarMessageSender.cs rename Code/Kavenegar.Core/{IKavenegarApi.cs => IKavenegarProfileApi.cs} (55%) delete mode 100644 Code/Kavenegar.Core/KavenegarApi.cs create mode 100644 Code/Kavenegar.Core/KavenegarMessageSender.cs create mode 100644 Code/Kavenegar.Core/KavenegarProfileApi.cs create mode 100644 Code/Shared/Shared.Infrastructure/IHttpClientHelper.cs diff --git a/Code/Kavenegar.Core/BaseKavenegarApi.cs b/Code/Kavenegar.Core/BaseKavenegarApi.cs new file mode 100644 index 0000000..e404acd --- /dev/null +++ b/Code/Kavenegar.Core/BaseKavenegarApi.cs @@ -0,0 +1,35 @@ +using Kavenegar.Core.Dto.Result; +using Shared.Infrastructure; + +namespace Kavenegar.Core; + +public class BaseKavenegarApi +{ + private const string ApiAddress = "https://api.kavenegar.com/v1"; + protected readonly IHttpClientHelper HttpClientHelper; + + protected BaseKavenegarApi( + IHttpClientHelper httpClientHelper, + string apiKey) + { + HttpClientHelper = httpClientHelper; + HttpClientHelper.BaseAddress = Path.Combine(ApiAddress, apiKey); + } + + protected async Task RequestSender( + string requestUri, + object? body, + Dictionary? queryParams, + CancellationToken cancellationToken) + { + var httpResponseMessage = await HttpClientHelper.PostAsync( + requestUri, + body, + queryParams, + cancellationToken); + + var deserializedObj = await httpResponseMessage.Deserialize>(cancellationToken); + + return deserializedObj == null ? default : deserializedObj.Value; + } +} \ No newline at end of file diff --git a/Code/Kavenegar.Core/DependencyManager.cs b/Code/Kavenegar.Core/DependencyManager.cs index 9d37983..8e87a0f 100644 --- a/Code/Kavenegar.Core/DependencyManager.cs +++ b/Code/Kavenegar.Core/DependencyManager.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.DependencyInjection; +using Shared.Infrastructure; namespace Kavenegar.Core; @@ -8,6 +9,14 @@ public static IServiceCollection AddKavenegar( this IServiceCollection serviceCollection, string apiKey) { - return serviceCollection.AddTransient(_ => new KavenegarApi(apiKey)); + return serviceCollection.AddScoped() + .AddScoped( + serviceProvider => new KavenegarProfileApi( + serviceProvider.GetRequiredService(), + apiKey)) + .AddScoped( + serviceProvider => new KavenegarMessageSender( + serviceProvider.GetRequiredService(), + apiKey)); } } \ No newline at end of file diff --git a/Code/Kavenegar.Core/Dto/Message/MessageInfo.cs b/Code/Kavenegar.Core/Dto/Message/MessageInfo.cs index c7053bc..0f0b087 100644 --- a/Code/Kavenegar.Core/Dto/Message/MessageInfo.cs +++ b/Code/Kavenegar.Core/Dto/Message/MessageInfo.cs @@ -6,5 +6,5 @@ public class MessageInfo { public string Sender { get; set; } = null!; public string Message { get; set; } = null!; - public MessageType Type { get; set; } + public MessageType Type { get; set; } = MessageType.Flash; } \ No newline at end of file diff --git a/Code/Kavenegar.Core/Dto/Result/SendResult.cs b/Code/Kavenegar.Core/Dto/Result/SendResult.cs deleted file mode 100644 index 21852ea..0000000 --- a/Code/Kavenegar.Core/Dto/Result/SendResult.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Kavenegar.Core.Dto.Result; - -public class SendResult -{ - public long MessageId { get; set; } - public string Message { get; set; } = null!; - public int Status { get; set; } - public string StatusText { get; set; } = null!; - public string Sender { get; set; } = null!; - public string Receptor { get; set; } = null!; - public long Date { get; set; } - public int Cost { get; set; } -} \ No newline at end of file diff --git a/Code/Kavenegar.Core/Dto/Result/SendResultDto.cs b/Code/Kavenegar.Core/Dto/Result/SendResultDto.cs new file mode 100644 index 0000000..40922aa --- /dev/null +++ b/Code/Kavenegar.Core/Dto/Result/SendResultDto.cs @@ -0,0 +1,32 @@ +using System.Text.Json.Serialization; +using Kavenegar.Core.Enums; +using Shared.Infrastructure; + +namespace Kavenegar.Core.Dto.Result; + +public class SendResultDto +{ + public long MessageId { get; set; } + public string Message { get; set; } = null!; + + [JsonPropertyName("Status")] + public int StatusNumber { get; set; } + + public MessageStatus Status => StatusCaster(StatusNumber); + public string StatusText { get; set; } = null!; + public string Sender { get; set; } = null!; + public string Receptor { get; set; } = null!; + + [JsonPropertyName("Date")] + public long UnixDate { get; set; } + + public DateTime DateTime => UnixDate.ToDateTime(); + public int Cost { get; set; } + + private MessageStatus StatusCaster( + int status) + { + if (Enum.IsDefined(typeof(MessageStatus), StatusNumber)) return (MessageStatus)status; + return status == 5 ? MessageStatus.SentToCenter : MessageStatus.Unknown; + } +} \ No newline at end of file diff --git a/Code/Kavenegar.Core/Enums/MessageStatus.cs b/Code/Kavenegar.Core/Enums/MessageStatus.cs index 9f00180..ecc71c5 100644 --- a/Code/Kavenegar.Core/Enums/MessageStatus.cs +++ b/Code/Kavenegar.Core/Enums/MessageStatus.cs @@ -2,10 +2,10 @@ namespace Kavenegar.Core.Enums; public enum MessageStatus { + Unknown = 0, Queued = 1, Scheduled = 2, SentToCenter = 4, - SentToCenter2 = 5, Delivered = 10, Undelivered = 11, Canceled = 13, diff --git a/Code/Kavenegar.Core/IKavenegarMessageSender.cs b/Code/Kavenegar.Core/IKavenegarMessageSender.cs new file mode 100644 index 0000000..95c70ca --- /dev/null +++ b/Code/Kavenegar.Core/IKavenegarMessageSender.cs @@ -0,0 +1,75 @@ +using Kavenegar.Core.Dto.Message; +using Kavenegar.Core.Dto.Result; +using Kavenegar.Core.Enums; + +namespace Kavenegar.Core; + +public interface IKavenegarMessageSender +{ + /// + /// Send one message for only the receptor + /// + /// Message text. + /// Who receives message. + /// Number to send message if you set it empty the default number will be used. + /// Unique id which you set for the id. + /// The date time you wand the message to be sent. If it is null message will be send asap. + /// If true receptor number will be hidden. + /// Type of message. + /// Token to cancel request. + /// + Task Send( + string message, + string receptor, + string sender = "", + string localMessageId = "", + DateTime? dateTime = null, + bool hide = false, + MessageType messageType = MessageType.AppMemory, + CancellationToken cancellationToken = default); + + /// + /// Send message text for each receptor with the localMessageId + /// + /// Message text. + /// Key for receptor and value is for local message id. + /// Number to send message if you set it empty the default number will be used. + /// The date time you wand the message to be sent. If it is null message will be send asap. + /// If true receptor number will be hidden. + /// Type of message. + /// Token to cancel request. + /// + Task?> Send( + string message, + Dictionary receptors, + string sender = "", + DateTime? dateTime = null, + bool hide = false, + MessageType messageType = MessageType.AppMemory, + CancellationToken cancellationToken = default); + + public Task?> Send( + SendSingleMessageRequest message, + CancellationToken cancellationToken = default); + + Task?> Send( + IEnumerable sendMessageInfos, + bool hide = false, + DateTime? dateTime = null, + CancellationToken cancellationToken = default); + + Task?> Send( + SendMultiMessageRequest messages, + CancellationToken cancellationToken = default); + + Task VerifyLookup( + string? receptor, + string? template, + string? token1, + string? token2 = null, + string? token3 = null, + string? token4 = null, + string? token5 = null, + VerifyLookupType? type = null, + CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/Code/Kavenegar.Core/IKavenegarApi.cs b/Code/Kavenegar.Core/IKavenegarProfileApi.cs similarity index 55% rename from Code/Kavenegar.Core/IKavenegarApi.cs rename to Code/Kavenegar.Core/IKavenegarProfileApi.cs index 379ce1f..bf54d6a 100644 --- a/Code/Kavenegar.Core/IKavenegarApi.cs +++ b/Code/Kavenegar.Core/IKavenegarProfileApi.cs @@ -1,84 +1,74 @@ -using Kavenegar.Core.Dto.Message; -using Kavenegar.Core.Dto.Result; -using Kavenegar.Core.Enums; +using Kavenegar.Core.Dto.Result; namespace Kavenegar.Core; -public interface IKavenegarApi +public interface IKavenegarProfileApi { - Task Send( - SendSingleMessageRequest message, - CancellationToken cancellationToken = default); - - Task> Send( - SendMultiMessageRequest messages, - CancellationToken cancellationToken = default); - - Task Status( + Task Status( string messageId, CancellationToken cancellationToken = default); - Task> Status( + Task?> Status( List messageIds, CancellationToken cancellationToken = default); - Task StatusLocalMessageId( + Task StatusLocalMessageId( string messageId, CancellationToken cancellationToken = default); - Task> StatusLocalMessageId( + Task?> StatusLocalMessageId( List messageIds, CancellationToken cancellationToken = default); - Task Select( + Task Select( string messageId, CancellationToken cancellationToken = default); - Task> Select( + Task?> Select( List messageIds, CancellationToken cancellationToken = default); - Task> SelectOutbox( + Task?> SelectOutbox( DateTime startDate, DateTime? endDate, string? sender, CancellationToken cancellationToken = default); - Task> LatestOutbox( + Task?> LatestOutbox( long? pageSize, string? sender, CancellationToken cancellationToken = default); - Task CountOutbox( + Task CountOutbox( DateTime startDate, DateTime? endDate, int? status, CancellationToken cancellationToken = default); - Task Cancel( + Task Cancel( string messageId, CancellationToken cancellationToken = default); - Task> Cancel( + Task?> Cancel( List ids, CancellationToken cancellationToken = default); - Task> Receive( + Task?> Receive( string line, bool isRead, CancellationToken cancellationToken = default); - Task CountInbox( + Task CountInbox( DateTime startDate, DateTime? endDate, string? lineNumber, bool? isRead, CancellationToken cancellationToken = default); - Task AccountInfo( + Task AccountInfo( CancellationToken cancellationToken = default); - Task AccountConfig( + Task AccountConfig( string apiLogs, string dailyReport, string debugMode, @@ -86,15 +76,4 @@ Task AccountConfig( int? minCreditAlarm, string resendFailed, CancellationToken cancellationToken = default); - - Task VerifyLookup( - string receptor, - string template, - string token1, - string? token2 = null, - string? token3 = null, - string? token4 = null, - string? token5 = null, - VerifyLookupType? type = null, - CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Code/Kavenegar.Core/KavenegarApi.cs b/Code/Kavenegar.Core/KavenegarApi.cs deleted file mode 100644 index 2052d5f..0000000 --- a/Code/Kavenegar.Core/KavenegarApi.cs +++ /dev/null @@ -1,497 +0,0 @@ -using System.Net; -using Kavenegar.Core.Dto.Message; -using Kavenegar.Core.Dto.Result; -using Kavenegar.Core.Enums; -using Shared.Infrastructure; - -namespace Kavenegar.Core; - -internal class KavenegarApi : IKavenegarApi -{ - private readonly HttpClientHelper _httpClientHelper; - - public KavenegarApi( - string apiKey) - { - _httpClientHelper = new HttpClientHelper - { - BaseAddress = $"https://api.kavenegar.com/v1/{apiKey}" - }; - } - - public async Task Send( - SendSingleMessageRequest message, - CancellationToken cancellationToken = default) - { - var queryParams = new Dictionary - { - { - "sender", message.MessageInfo.Sender - }, - { - "receptor", string.Join(',', message.ReceptorLocalMessageIds.Keys) - }, - { - "message", message.MessageInfo.Message - }, - { - "type", (int)message.MessageInfo.Type - }, - { - "date", message.Date?.ToUnixTimestamp() ?? 0 - } - }; - - if (message.ReceptorLocalMessageIds.Values.All(string.IsNullOrWhiteSpace)) - queryParams.Add("localId", string.Join(',', message.ReceptorLocalMessageIds.Values)); - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/sendarray.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))!.Value - .FirstOrDefault(); - } - - public async Task> Send( - SendMultiMessageRequest messages, - CancellationToken cancellationToken = default) - { - var requestParams = new Dictionary - { - { - "message", - await messages.SendMessageInfos - .Select(sendMessageInfo => WebUtility.HtmlEncode(sendMessageInfo.MessageInfo.Message)) - .ToList() - .Serialize(cancellationToken) - }, - { - "sender", - await messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.MessageInfo.Sender) - .ToList() - .Serialize(cancellationToken) - }, - { - "receptor", - await messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.Receptor) - .ToList() - .Serialize(cancellationToken) - }, - { - "type", - await messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.MessageInfo.Type.ToString()) - .Serialize(cancellationToken) - }, - { - "date", messages.Date == DateTime.MinValue ? 0 : messages.Date.ToUnixTimestamp() - } - }; - - if (messages.SendMessageInfos.All( - sendMessageInfo => !string.IsNullOrWhiteSpace(sendMessageInfo.LocalMessageId))) - requestParams.Add( - "localMessageIds", - string.Join( - ",", - messages.SendMessageInfos.Select( - sendMessageInfo => !string.IsNullOrWhiteSpace(sendMessageInfo.LocalMessageId)))); - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/send.json", - null, - requestParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))!.Value; - } - - public async Task Status( - string messageId, - CancellationToken cancellationToken = default) - { - return (await Status( - new List - { - messageId - }, - cancellationToken)).FirstOrDefault()!; - } - - public async Task> Status( - List messageIds, - CancellationToken cancellationToken = default) - { - var queryParams = new Dictionary - { - { - "messageid", string.Join(',', messageIds) - } - }; - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/status.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? - new List(); - } - - public async Task StatusLocalMessageId( - string messageId, - CancellationToken cancellationToken = default) - { - return (await StatusLocalMessageId( - new List - { - messageId - }, - cancellationToken)).FirstOrDefault()!; - } - - public async Task> StatusLocalMessageId( - List messageIds, - CancellationToken cancellationToken = default) - { - var queryParams = new Dictionary - { - { - "messageid", string.Join(',', messageIds) - } - }; - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/statuslocalmessageid.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? - new List(); - } - - public async Task Select( - string messageId, - CancellationToken cancellationToken = default) - { - return (await Select( - new List - { - messageId - }, - cancellationToken)).FirstOrDefault()!; - } - - public async Task> Select( - List messageIds, - CancellationToken cancellationToken = default) - { - var queryParams = new Dictionary - { - { - "messageid", string.Join(',', messageIds) - } - }; - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/select.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? - new List(); - } - - public async Task> SelectOutbox( - DateTime startDate, - DateTime? endDate, - string? sender, - CancellationToken cancellationToken = default) - { - if (endDate <= startDate) throw new ArgumentException("تاریخ پایان باید از تاریخ شروع بزرگتر باشد."); - - if ((endDate - startDate)!.Value.TotalDays > 1) - throw new ArgumentException( - "حداکثر فاصله زمانی بین متغیر startDate تا متغیر endDate برابر با 1 روز می باشد."); - - if (startDate < DateTime.Now.AddDays(-60)) - throw new ArgumentException("تاریخ شروع startDate حداکثر باید تا 60 روز قبل باشد."); - - var queryParams = new Dictionary - { - { - "startdate", startDate.ToUnixTimestamp() - } - }; - - if (endDate.HasValue) queryParams.Add("enddate", endDate.Value.ToUnixTimestamp()); - - if (string.IsNullOrWhiteSpace(sender)) queryParams.Add("sender", sender); - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/selectoutbox.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? - new List(); - } - - public async Task> LatestOutbox( - long? pageSize, - string? sender, - CancellationToken cancellationToken = default) - { - if (pageSize is > 500) throw new ArgumentException("تعداد رکورد های خروجی این متد حداکثر 500 رکورد می‌باشد."); - - pageSize ??= 500; - - var queryParams = new Dictionary - { - { - "pagesize", pageSize - } - }; - - if (string.IsNullOrWhiteSpace(sender)) queryParams.Add("sender", sender); - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/latestoutbox.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? - new List(); - } - - public async Task CountOutbox( - DateTime startDate, - DateTime? endDate, - int? status, - CancellationToken cancellationToken = default) - { - if (endDate <= startDate) throw new ArgumentException("تاریخ پایان باید از تاریخ شروع بزرگتر باشد."); - - if ((endDate - startDate)!.Value.TotalDays > 1) - throw new ArgumentException( - "حداکثر فاصله زمانی بین متغیر startdate تا متغیر endDate برابر با 1 روز می باشد."); - - if (startDate < DateTime.Now.AddDays(-60)) - throw new ArgumentException("تاریخ شروع startdate حداکثر باید تا 60 روز قبل باشد."); - - var queryParams = new Dictionary - { - { - "startdate", startDate.ToUnixTimestamp() - } - }; - - if (endDate.HasValue) queryParams.Add("enddate", endDate.Value.ToUnixTimestamp()); - - if (status.HasValue) queryParams.Add("status", status); - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/countoutbox.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value - .FirstOrDefault() ?? - new CountOutboxDto(); - } - - public async Task Cancel( - string messageId, - CancellationToken cancellationToken = default) - { - return (await Cancel( - new List - { - messageId - }, - cancellationToken)).FirstOrDefault()!; - } - - public async Task> Cancel( - List ids, - CancellationToken cancellationToken = default) - { - var queryParams = new Dictionary - { - { - "messageid", string.Join(',', ids) - } - }; - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/cancel.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? - new List(); - } - - public async Task> Receive( - string line, - bool isRead, - CancellationToken cancellationToken = default) - { - var queryParams = new Dictionary - { - { - "linenumber", line - }, - { - "isread", isRead ? 1 : 0 - } - }; - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/receive.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value ?? - new List(); - } - - public async Task CountInbox( - DateTime startDate, - DateTime? endDate, - string? lineNumber, - bool? isRead, - CancellationToken cancellationToken = default) - { - if (endDate <= startDate) throw new ArgumentException("تاریخ پایان باید از تاریخ شروع بزرگتر باشد."); - - if ((endDate - startDate)!.Value.TotalDays > 1) - throw new ArgumentException( - "حداکثر فاصله زمانی بین متغیر startdate تا متغیر endDate برابر با 1 روز می باشد."); - - if (startDate < DateTime.Now.AddDays(-60)) - throw new ArgumentException("تاریخ شروع startdate حداکثر باید تا 60 روز قبل باشد."); - - var queryParams = new Dictionary - { - { - "startdate", startDate.ToUnixTimestamp() - } - }; - - if (endDate.HasValue) queryParams.Add("enddate", endDate.Value.ToUnixTimestamp()); - if (string.IsNullOrWhiteSpace(lineNumber)) queryParams.Add("linenumber", lineNumber); - if (isRead.HasValue) queryParams.Add("isread", isRead.Value ? 1 : 0); - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "sms/countinbox.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value - .FirstOrDefault() ?? - new CountOutboxDto(); - } - - public async Task AccountInfo( - CancellationToken cancellationToken = default) - { - var httpResponseMessage = await _httpClientHelper.PostAsync( - "account/info.json", - null, - null, - cancellationToken); - - return (await httpResponseMessage.Deserialize>(cancellationToken))?.Value ?? - new AccountInfoDto(); - } - - public async Task AccountConfig( - string? apiLogs, - string? dailyReport, - string? debugMode, - string? defaultSender, - int? minCreditAlarm, - string? resendFailed, - CancellationToken cancellationToken = default) - { - var queryParams = new Dictionary(); - - if (string.IsNullOrWhiteSpace(apiLogs)) queryParams.Add("apilogs", apiLogs); - - if (string.IsNullOrWhiteSpace(dailyReport)) queryParams.Add("dailyreport", dailyReport); - - if (string.IsNullOrWhiteSpace(debugMode)) queryParams.Add("debugmode", debugMode); - - if (string.IsNullOrWhiteSpace(defaultSender)) queryParams.Add("defaultsender", defaultSender); - - queryParams.Add("mincreditalarm", minCreditAlarm); - - if (string.IsNullOrWhiteSpace(resendFailed)) queryParams.Add("resendfailed", resendFailed); - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "account/config.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>(cancellationToken))?.Value ?? - new AccountConfigDto(); - } - - public async Task VerifyLookup( - string receptor, - string template, - string token1, - string? token2 = null, - string? token3 = null, - string? token4 = null, - string? token5 = null, - VerifyLookupType? type = null, - CancellationToken cancellationToken = default) - { - var queryParams = new Dictionary - { - { - "receptor", receptor - }, - { - "template", template - }, - { - "token", token1 - } - }; - - if (string.IsNullOrWhiteSpace(token2)) queryParams.Add("token2", token2); - - if (string.IsNullOrWhiteSpace(token3)) queryParams.Add("token3", token3); - - if (string.IsNullOrWhiteSpace(token4)) queryParams.Add("token10", token4); - - if (string.IsNullOrWhiteSpace(token5)) queryParams.Add("token20", token5); - - if (type.HasValue) queryParams.Add("type", type.Value.ToString()); - - var httpResponseMessage = await _httpClientHelper.PostAsync( - "verify/lookup.json", - null, - queryParams, - cancellationToken); - - return (await httpResponseMessage.Deserialize>>(cancellationToken))?.Value - .FirstOrDefault() ?? - new SendResult(); - } -} \ No newline at end of file diff --git a/Code/Kavenegar.Core/KavenegarMessageSender.cs b/Code/Kavenegar.Core/KavenegarMessageSender.cs new file mode 100644 index 0000000..1bd18d4 --- /dev/null +++ b/Code/Kavenegar.Core/KavenegarMessageSender.cs @@ -0,0 +1,234 @@ +using System.Net; +using Kavenegar.Core.Dto.Message; +using Kavenegar.Core.Dto.Result; +using Kavenegar.Core.Enums; +using Shared.Infrastructure; + +namespace Kavenegar.Core; + +public class KavenegarMessageSender + : BaseKavenegarApi, + IKavenegarMessageSender +{ + public KavenegarMessageSender( + IHttpClientHelper httpClientHelper, + string apiKey) : base(httpClientHelper, apiKey) + { + } + + /// + /// Send one message for only the receptor + /// + /// Message text. + /// Who receives message. + /// Number to send message if you set it empty the default number will be used. + /// Unique id which you set for the id. + /// The date time you wand the message to be sent. If it is null message will be send asap. + /// If true receptor number will be hidden. + /// Type of message. + /// Token to cancel request. + /// + public async Task Send( + string message, + string receptor, + string sender = "", + string localMessageId = "", + DateTime? dateTime = null, + bool hide = false, + MessageType messageType = MessageType.AppMemory, + CancellationToken cancellationToken = default) + { + return (await Send( + new SendSingleMessageRequest + { + Date = dateTime ?? DateTime.Now, + Hide = hide, + MessageInfo = new MessageInfo + { + Message = message, + Sender = sender, + Type = messageType + }, + ReceptorLocalMessageIds = new Dictionary + { + { + receptor, localMessageId + } + } + }, + cancellationToken))?.FirstOrDefault(); + } + + /// + /// Send message text for each receptor with the localMessageId + /// + /// Message text. + /// Key for receptor and value is for local message id. + /// Number to send message if you set it empty the default number will be used. + /// The date time you wand the message to be sent. If it is null message will be send asap. + /// If true receptor number will be hidden. + /// Type of message. + /// Token to cancel request. + /// + public async Task?> Send( + string message, + Dictionary receptors, + string sender = "", + DateTime? dateTime = null, + bool hide = false, + MessageType messageType = MessageType.AppMemory, + CancellationToken cancellationToken = default) + { + return await Send( + new SendSingleMessageRequest + { + Date = dateTime ?? DateTime.Now, + Hide = hide, + MessageInfo = new MessageInfo + { + Message = message, + Sender = sender, + Type = messageType + }, + ReceptorLocalMessageIds = receptors + }, + cancellationToken); + } + + public async Task?> Send( + SendSingleMessageRequest message, + CancellationToken cancellationToken = default) + { + var queryParams = new Dictionary + { + { + "sender", message.MessageInfo.Sender + }, + { + "receptor", string.Join(',', message.ReceptorLocalMessageIds.Keys) + }, + { + "message", message.MessageInfo.Message + }, + { + "type", (int)message.MessageInfo.Type + }, + { + "date", message.Date?.ToUnixTimestamp() ?? 0 + } + }; + + if (message.ReceptorLocalMessageIds.Values.All(string.IsNullOrWhiteSpace)) + queryParams.Add("localId", string.Join(',', message.ReceptorLocalMessageIds.Values)); + + return await RequestSender>( + "sms/send.json", + null, + queryParams, + cancellationToken); + } + + public async Task?> Send( + IEnumerable sendMessageInfos, + bool hide = false, + DateTime? dateTime = null, + CancellationToken cancellationToken = default) + { + return await Send( + new SendMultiMessageRequest + { + Date = dateTime ?? DateTime.Now, + Hide = hide, + SendMessageInfos = sendMessageInfos + }, + cancellationToken); + } + + public async Task?> Send( + SendMultiMessageRequest messages, + CancellationToken cancellationToken = default) + { + var requestParams = new Dictionary + { + { + "message", + await messages.SendMessageInfos + .Select(sendMessageInfo => WebUtility.HtmlEncode(sendMessageInfo.MessageInfo.Message)) + .ToList() + .Serialize(cancellationToken) + }, + { + "sender", + await messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.MessageInfo.Sender) + .ToList() + .Serialize(cancellationToken) + }, + { + "receptor", + await messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.Receptor) + .ToList() + .Serialize(cancellationToken) + }, + { + "type", + await messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.MessageInfo.Type.ToString()) + .Serialize(cancellationToken) + }, + { + "date", messages.Date == DateTime.MinValue ? 0 : messages.Date.ToUnixTimestamp() + } + }; + + if (messages.SendMessageInfos.All( + sendMessageInfo => !string.IsNullOrWhiteSpace(sendMessageInfo.LocalMessageId))) + requestParams.Add( + "localMessageIds", + string.Join( + ",", + messages.SendMessageInfos.Select( + sendMessageInfo => !string.IsNullOrWhiteSpace(sendMessageInfo.LocalMessageId)))); + + return await RequestSender>( + "sms/sendarray.json", + null, + requestParams, + cancellationToken); + } + + public async Task VerifyLookup( + string? receptor, + string? template, + string? token1, + string? token2 = null, + string? token3 = null, + string? token4 = null, + string? token5 = null, + VerifyLookupType? type = null, + CancellationToken cancellationToken = default) + { + var queryParams = new Dictionary + { + { + "receptor", receptor + }, + { + "template", template + }, + { + "token", token1 + } + }; + + if (string.IsNullOrWhiteSpace(token2)) queryParams.Add("token2", token2); + if (string.IsNullOrWhiteSpace(token3)) queryParams.Add("token3", token3); + if (string.IsNullOrWhiteSpace(token4)) queryParams.Add("token10", token4); + if (string.IsNullOrWhiteSpace(token5)) queryParams.Add("token20", token5); + if (type.HasValue) queryParams.Add("type", type.Value.ToString()); + + return (await RequestSender>( + "verify/lookup.json", + null, + queryParams, + cancellationToken))?.FirstOrDefault(); + } +} \ No newline at end of file diff --git a/Code/Kavenegar.Core/KavenegarProfileApi.cs b/Code/Kavenegar.Core/KavenegarProfileApi.cs new file mode 100644 index 0000000..d016e0e --- /dev/null +++ b/Code/Kavenegar.Core/KavenegarProfileApi.cs @@ -0,0 +1,314 @@ +using Kavenegar.Core.Dto.Result; +using Shared.Infrastructure; + +namespace Kavenegar.Core; + +public class KavenegarProfileApi + : BaseKavenegarApi, + IKavenegarProfileApi +{ + public KavenegarProfileApi( + IHttpClientHelper httpClientHelper, + string apiKey) : base(httpClientHelper, apiKey) + { + } + + public async Task Status( + string messageId, + CancellationToken cancellationToken = default) + { + return (await Status( + new List + { + messageId + }, + cancellationToken))?.FirstOrDefault()!; + } + + public async Task?> Status( + List messageIds, + CancellationToken cancellationToken = default) + { + var queryParams = new Dictionary + { + { + "messageid", string.Join(',', messageIds) + } + }; + + return await RequestSender>( + "sms/status.json", + null, + queryParams, + cancellationToken); + } + + public async Task StatusLocalMessageId( + string messageId, + CancellationToken cancellationToken = default) + { + return (await StatusLocalMessageId( + new List + { + messageId + }, + cancellationToken))?.FirstOrDefault()!; + } + + public async Task?> StatusLocalMessageId( + List messageIds, + CancellationToken cancellationToken = default) + { + var queryParams = new Dictionary + { + { + "messageid", string.Join(',', messageIds) + } + }; + + return await RequestSender>( + "sms/statuslocalmessageid.json", + null, + queryParams, + cancellationToken); + } + + public async Task Select( + string messageId, + CancellationToken cancellationToken = default) + { + return (await Select( + new List + { + messageId + }, + cancellationToken))?.FirstOrDefault()!; + } + + public async Task?> Select( + List messageIds, + CancellationToken cancellationToken = default) + { + var queryParams = new Dictionary + { + { + "messageid", string.Join(',', messageIds) + } + }; + + return await RequestSender>( + "sms/select.json", + null, + queryParams, + cancellationToken); + } + + public async Task?> SelectOutbox( + DateTime startDate, + DateTime? endDate, + string? sender, + CancellationToken cancellationToken = default) + { + if (endDate <= startDate) throw new ArgumentException("تاریخ پایان باید از تاریخ شروع بزرگتر باشد."); + + if ((endDate - startDate)!.Value.TotalDays > 1) + throw new ArgumentException( + "حداکثر فاصله زمانی بین متغیر startDate تا متغیر endDate برابر با 1 روز می باشد."); + + if (startDate < DateTime.Now.AddDays(-60)) + throw new ArgumentException("تاریخ شروع startDate حداکثر باید تا 60 روز قبل باشد."); + + var queryParams = new Dictionary + { + { + "startdate", startDate.ToUnixTimestamp() + } + }; + + if (endDate.HasValue) queryParams.Add("enddate", endDate.Value.ToUnixTimestamp()); + if (string.IsNullOrWhiteSpace(sender)) queryParams.Add("sender", sender); + + return await RequestSender>( + "sms/selectoutbox.json", + null, + queryParams, + cancellationToken); + } + + public async Task?> LatestOutbox( + long? pageSize, + string? sender, + CancellationToken cancellationToken = default) + { + if (pageSize is > 500) throw new ArgumentException("تعداد رکورد های خروجی این متد حداکثر 500 رکورد می‌باشد."); + + pageSize ??= 500; + + var queryParams = new Dictionary + { + { + "pagesize", pageSize + } + }; + + if (string.IsNullOrWhiteSpace(sender)) queryParams.Add("sender", sender); + + return await RequestSender>( + "sms/latestoutbox.json", + null, + queryParams, + cancellationToken); + } + + public async Task CountOutbox( + DateTime startDate, + DateTime? endDate, + int? status, + CancellationToken cancellationToken = default) + { + if (endDate <= startDate) throw new ArgumentException("تاریخ پایان باید از تاریخ شروع بزرگتر باشد."); + + if ((endDate - startDate)!.Value.TotalDays > 1) + throw new ArgumentException( + "حداکثر فاصله زمانی بین متغیر startdate تا متغیر endDate برابر با 1 روز می باشد."); + + if (startDate < DateTime.Now.AddDays(-60)) + throw new ArgumentException("تاریخ شروع startdate حداکثر باید تا 60 روز قبل باشد."); + + var queryParams = new Dictionary + { + { + "startdate", startDate.ToUnixTimestamp() + } + }; + + if (endDate.HasValue) queryParams.Add("enddate", endDate.Value.ToUnixTimestamp()); + if (status.HasValue) queryParams.Add("status", status); + + return (await RequestSender>( + "sms/countoutbox.json", + null, + queryParams, + cancellationToken))?.FirstOrDefault(); + } + + public async Task Cancel( + string messageId, + CancellationToken cancellationToken = default) + { + return (await Cancel( + new List + { + messageId + }, + cancellationToken))?.FirstOrDefault()!; + } + + public async Task?> Cancel( + List ids, + CancellationToken cancellationToken = default) + { + var queryParams = new Dictionary + { + { + "messageid", string.Join(',', ids) + } + }; + return await RequestSender>( + "sms/cancel.json", + null, + queryParams, + cancellationToken); + } + + public async Task?> Receive( + string line, + bool isRead, + CancellationToken cancellationToken = default) + { + var queryParams = new Dictionary + { + { + "linenumber", line + }, + { + "isread", isRead ? 1 : 0 + } + }; + + return await RequestSender>( + "sms/receive.json", + null, + queryParams, + cancellationToken); + } + + public async Task CountInbox( + DateTime startDate, + DateTime? endDate, + string? lineNumber, + bool? isRead, + CancellationToken cancellationToken = default) + { + if (endDate <= startDate) throw new ArgumentException("تاریخ پایان باید از تاریخ شروع بزرگتر باشد."); + + if ((endDate - startDate)!.Value.TotalDays > 1) + throw new ArgumentException( + "حداکثر فاصله زمانی بین متغیر startdate تا متغیر endDate برابر با 1 روز می باشد."); + + if (startDate < DateTime.Now.AddDays(-60)) + throw new ArgumentException("تاریخ شروع startdate حداکثر باید تا 60 روز قبل باشد."); + + var queryParams = new Dictionary + { + { + "startdate", startDate.ToUnixTimestamp() + } + }; + + if (endDate.HasValue) queryParams.Add("enddate", endDate.Value.ToUnixTimestamp()); + if (string.IsNullOrWhiteSpace(lineNumber)) queryParams.Add("linenumber", lineNumber); + if (isRead.HasValue) queryParams.Add("isread", isRead.Value ? 1 : 0); + + return (await RequestSender>( + "sms/countinbox.json", + null, + queryParams, + cancellationToken))?.FirstOrDefault(); + } + + public async Task AccountInfo( + CancellationToken cancellationToken = default) + { + return await RequestSender( + "account/info.json", + null, + null, + cancellationToken); + } + + public async Task AccountConfig( + string? apiLogs, + string? dailyReport, + string? debugMode, + string? defaultSender, + int? minCreditAlarm, + string? resendFailed, + CancellationToken cancellationToken = default) + { + var queryParams = new Dictionary(); + + if (string.IsNullOrWhiteSpace(apiLogs)) queryParams.Add("apilogs", apiLogs); + if (string.IsNullOrWhiteSpace(dailyReport)) queryParams.Add("dailyreport", dailyReport); + if (string.IsNullOrWhiteSpace(debugMode)) queryParams.Add("debugmode", debugMode); + if (string.IsNullOrWhiteSpace(defaultSender)) queryParams.Add("defaultsender", defaultSender); + queryParams.Add("mincreditalarm", minCreditAlarm); + if (string.IsNullOrWhiteSpace(resendFailed)) queryParams.Add("resendfailed", resendFailed); + + return await RequestSender( + "account/config.json", + null, + queryParams, + cancellationToken); + } +} \ No newline at end of file diff --git a/Code/Shared/Shared.Infrastructure/HttpClientHelper.cs b/Code/Shared/Shared.Infrastructure/HttpClientHelper.cs index a871bf4..e5083be 100644 --- a/Code/Shared/Shared.Infrastructure/HttpClientHelper.cs +++ b/Code/Shared/Shared.Infrastructure/HttpClientHelper.cs @@ -1,6 +1,6 @@ namespace Shared.Infrastructure; -public class HttpClientHelper +public class HttpClientHelper : IHttpClientHelper { private readonly HttpClient _httpClient = new(); diff --git a/Code/Shared/Shared.Infrastructure/IHttpClientHelper.cs b/Code/Shared/Shared.Infrastructure/IHttpClientHelper.cs new file mode 100644 index 0000000..97f650d --- /dev/null +++ b/Code/Shared/Shared.Infrastructure/IHttpClientHelper.cs @@ -0,0 +1,12 @@ +namespace Shared.Infrastructure; + +public interface IHttpClientHelper +{ + string BaseAddress { get; set; } + + Task PostAsync( + string requestUri, + object? body = null, + Dictionary? queryParams = null, + CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/Code/Shared/Shared.Infrastructure/JsonUtility.cs b/Code/Shared/Shared.Infrastructure/JsonUtility.cs index 566f80c..cc3a95c 100644 --- a/Code/Shared/Shared.Infrastructure/JsonUtility.cs +++ b/Code/Shared/Shared.Infrastructure/JsonUtility.cs @@ -5,7 +5,7 @@ namespace Shared.Infrastructure; public static class JsonUtility { - public static async Task Serialize( + public static async Task Serialize( this T obj, CancellationToken cancellationToken = default) { From ab70fc5cfa2d4efbf8879d31e445a86bb220a301 Mon Sep 17 00:00:00 2001 From: alireza995 <88311706+alireza995@users.noreply.github.com> Date: Fri, 9 Dec 2022 21:00:44 +0330 Subject: [PATCH 08/14] test(KavenegarMessageSender) : Test KavenegarMessage Sender Separate KavenegarApi class into and make it testable and create test class for methods which send single message closes nothing --- Code/Kavenegar.Core/BaseKavenegarApi.cs | 8 +- .../Dto/Result/SendResultDto.cs | 2 +- Code/Kavenegar.Core/KavenegarMessageSender.cs | 69 +-- .../Shared.Infrastructure/HttpClientHelper.cs | 2 +- .../Shared.Infrastructure/JsonUtility.cs | 12 +- .../Shared.Infrastructure/StringUtility.cs | 16 + Kavenegar.sln | 2 +- .../SingleMessageSendToManyBaseMethodTests.cs | 533 ++++++++++++++++++ .../SingleMessageSendToManyTests.cs | 439 +++++++++++++++ .../SingleMessageSendToOneTests.cs | 381 +++++++++++++ .../Test.Kavenegar.Core.csproj} | 5 + 11 files changed, 1417 insertions(+), 52 deletions(-) create mode 100644 Code/Shared/Shared.Infrastructure/StringUtility.cs create mode 100644 Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToManyBaseMethodTests.cs create mode 100644 Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToManyTests.cs create mode 100644 Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToOneTests.cs rename Test/{Kavenegar.Core/Kavenegar.Core.csproj => Test.Kavenegar.Core/Test.Kavenegar.Core.csproj} (74%) diff --git a/Code/Kavenegar.Core/BaseKavenegarApi.cs b/Code/Kavenegar.Core/BaseKavenegarApi.cs index e404acd..6ccb08c 100644 --- a/Code/Kavenegar.Core/BaseKavenegarApi.cs +++ b/Code/Kavenegar.Core/BaseKavenegarApi.cs @@ -6,14 +6,14 @@ namespace Kavenegar.Core; public class BaseKavenegarApi { private const string ApiAddress = "https://api.kavenegar.com/v1"; - protected readonly IHttpClientHelper HttpClientHelper; + private readonly IHttpClientHelper _httpClientHelper; protected BaseKavenegarApi( IHttpClientHelper httpClientHelper, string apiKey) { - HttpClientHelper = httpClientHelper; - HttpClientHelper.BaseAddress = Path.Combine(ApiAddress, apiKey); + _httpClientHelper = httpClientHelper; + _httpClientHelper.BaseAddress = Path.Combine(ApiAddress, apiKey); } protected async Task RequestSender( @@ -22,7 +22,7 @@ protected BaseKavenegarApi( Dictionary? queryParams, CancellationToken cancellationToken) { - var httpResponseMessage = await HttpClientHelper.PostAsync( + var httpResponseMessage = await _httpClientHelper.PostAsync( requestUri, body, queryParams, diff --git a/Code/Kavenegar.Core/Dto/Result/SendResultDto.cs b/Code/Kavenegar.Core/Dto/Result/SendResultDto.cs index 40922aa..8cff73f 100644 --- a/Code/Kavenegar.Core/Dto/Result/SendResultDto.cs +++ b/Code/Kavenegar.Core/Dto/Result/SendResultDto.cs @@ -12,7 +12,7 @@ public class SendResultDto [JsonPropertyName("Status")] public int StatusNumber { get; set; } - public MessageStatus Status => StatusCaster(StatusNumber); + public MessageStatus MessageStatus => StatusCaster(StatusNumber); public string StatusText { get; set; } = null!; public string Sender { get; set; } = null!; public string Receptor { get; set; } = null!; diff --git a/Code/Kavenegar.Core/KavenegarMessageSender.cs b/Code/Kavenegar.Core/KavenegarMessageSender.cs index 1bd18d4..fcf614e 100644 --- a/Code/Kavenegar.Core/KavenegarMessageSender.cs +++ b/Code/Kavenegar.Core/KavenegarMessageSender.cs @@ -35,28 +35,29 @@ public KavenegarMessageSender( string localMessageId = "", DateTime? dateTime = null, bool hide = false, - MessageType messageType = MessageType.AppMemory, + MessageType messageType = MessageType.Flash, CancellationToken cancellationToken = default) { - return (await Send( - new SendSingleMessageRequest + var sendSingleMessageRequest = new SendSingleMessageRequest + { + Hide = hide, + MessageInfo = new MessageInfo + { + Message = message, + Sender = sender, + Type = messageType + }, + ReceptorLocalMessageIds = new Dictionary { - Date = dateTime ?? DateTime.Now, - Hide = hide, - MessageInfo = new MessageInfo - { - Message = message, - Sender = sender, - Type = messageType - }, - ReceptorLocalMessageIds = new Dictionary { - { - receptor, localMessageId - } + receptor, localMessageId } - }, - cancellationToken))?.FirstOrDefault(); + } + }; + + if (dateTime.HasValue) sendSingleMessageRequest.Date = dateTime; + + return (await Send(sendSingleMessageRequest, cancellationToken))?.FirstOrDefault(); } /// @@ -76,23 +77,24 @@ public KavenegarMessageSender( string sender = "", DateTime? dateTime = null, bool hide = false, - MessageType messageType = MessageType.AppMemory, + MessageType messageType = MessageType.Flash, CancellationToken cancellationToken = default) { - return await Send( - new SendSingleMessageRequest + var sendSingleMessageRequest = new SendSingleMessageRequest + { + Hide = hide, + MessageInfo = new MessageInfo { - Date = dateTime ?? DateTime.Now, - Hide = hide, - MessageInfo = new MessageInfo - { - Message = message, - Sender = sender, - Type = messageType - }, - ReceptorLocalMessageIds = receptors + Message = message, + Sender = sender, + Type = messageType }, - cancellationToken); + ReceptorLocalMessageIds = receptors + }; + + if (dateTime.HasValue) sendSingleMessageRequest.Date = dateTime; + + return await Send(sendSingleMessageRequest, cancellationToken); } public async Task?> Send( @@ -101,9 +103,6 @@ public KavenegarMessageSender( { var queryParams = new Dictionary { - { - "sender", message.MessageInfo.Sender - }, { "receptor", string.Join(',', message.ReceptorLocalMessageIds.Keys) }, @@ -118,7 +117,9 @@ public KavenegarMessageSender( } }; - if (message.ReceptorLocalMessageIds.Values.All(string.IsNullOrWhiteSpace)) + if (message.MessageInfo.Sender.IsNotNullOrWhiteSpace()) queryParams.Add("sender", message.MessageInfo.Sender); + + if (message.ReceptorLocalMessageIds.Values.All(i => i.IsNotNullOrWhiteSpace())) queryParams.Add("localId", string.Join(',', message.ReceptorLocalMessageIds.Values)); return await RequestSender>( diff --git a/Code/Shared/Shared.Infrastructure/HttpClientHelper.cs b/Code/Shared/Shared.Infrastructure/HttpClientHelper.cs index e5083be..6ae1fea 100644 --- a/Code/Shared/Shared.Infrastructure/HttpClientHelper.cs +++ b/Code/Shared/Shared.Infrastructure/HttpClientHelper.cs @@ -26,6 +26,6 @@ private async Task SerializeBody( object obj, CancellationToken cancellationToken) { - return new StringContent(await obj.Serialize(cancellationToken)); + return new StringContent(await obj.Serialize(cancellationToken) ?? ""); } } \ No newline at end of file diff --git a/Code/Shared/Shared.Infrastructure/JsonUtility.cs b/Code/Shared/Shared.Infrastructure/JsonUtility.cs index cc3a95c..04f1930 100644 --- a/Code/Shared/Shared.Infrastructure/JsonUtility.cs +++ b/Code/Shared/Shared.Infrastructure/JsonUtility.cs @@ -19,21 +19,11 @@ await JsonSerializer.SerializeAsync( return await streamReader.ReadToEndAsync(); } - public static async Task Deserialize( - Stream json, - CancellationToken cancellationToken = default) - { - return await JsonSerializer.DeserializeAsync(json, cancellationToken: cancellationToken); - } - public static async Task Deserialize( this HttpResponseMessage httpResponseMessage, CancellationToken cancellationToken = default) { var content = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken); - var stream = new MemoryStream(); - var streamWriter = new StreamWriter(stream, Encoding.UTF8); - await streamWriter.WriteAsync(content); - return await Deserialize(stream, cancellationToken); + return JsonSerializer.Deserialize(content); } } \ No newline at end of file diff --git a/Code/Shared/Shared.Infrastructure/StringUtility.cs b/Code/Shared/Shared.Infrastructure/StringUtility.cs new file mode 100644 index 0000000..65bab68 --- /dev/null +++ b/Code/Shared/Shared.Infrastructure/StringUtility.cs @@ -0,0 +1,16 @@ +namespace Shared.Infrastructure; + +public static class StringUtility +{ + public static bool IsNullOrWhiteSpace( + this string text) + { + return string.IsNullOrWhiteSpace(text); + } + + public static bool IsNotNullOrWhiteSpace( + this string text) + { + return !text.IsNullOrWhiteSpace(); + } +} \ No newline at end of file diff --git a/Kavenegar.sln b/Kavenegar.sln index 05f8859..7f88a4a 100644 --- a/Kavenegar.sln +++ b/Kavenegar.sln @@ -8,7 +8,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Code", "Code", "{67BC444E-8 EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{17B39BF3-CC26-40C5-AEB0-87CA2D71B93E}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kavenegar.Core", "Test\Kavenegar.Core\Kavenegar.Core.csproj", "{6E36B3F6-2B1D-4506-BA92-007AC00EF317}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test.Kavenegar.Core", "Test\Test.Kavenegar.Core\Test.Kavenegar.Core.csproj", "{6E36B3F6-2B1D-4506-BA92-007AC00EF317}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToManyBaseMethodTests.cs b/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToManyBaseMethodTests.cs new file mode 100644 index 0000000..a0363fe --- /dev/null +++ b/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToManyBaseMethodTests.cs @@ -0,0 +1,533 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Kavenegar.Core.Dto.Message; +using Kavenegar.Core.Dto.Result; +using Kavenegar.Core.Enums; +using Moq; +using NUnit.Framework; +using Shared.Infrastructure; +using MessageSender = Kavenegar.Core.KavenegarMessageSender; + +namespace Test.Kavenegar.Core.KavenegarMessageSender; + +[TestFixture] +public class SingleMessageSendToManyBaseMethodTests +{ + [SetUp] + public void SetUp() + { + _mockHttpClientHelper = new Mock(); + _kavenegarMessageSender = new MessageSender(_mockHttpClientHelper.Object, ""); + } + + private MessageSender _kavenegarMessageSender = null!; + private Mock _mockHttpClientHelper = null!; + + [Test] + public async Task Send_WhenCalled_CallsPostAsync() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send( + new SendSingleMessageRequest + { + MessageInfo = new MessageInfo + { + Message = "message" + }, + ReceptorLocalMessageIds = new Dictionary + { + { + "receptor", "" + } + } + }); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + public async Task Send_SenderIsEmpty_SenderNotInParams() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send( + new SendSingleMessageRequest + { + MessageInfo = new MessageInfo + { + Message = "message" + }, + ReceptorLocalMessageIds = new Dictionary + { + { + "receptor", "" + } + } + }); + + Assert.That(passedQueryParams.ContainsKey("sender"), Is.False); + } + + [Test] + public async Task Send_SenderNotEmpty_SenderInParams() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send( + new SendSingleMessageRequest + { + MessageInfo = new MessageInfo + { + Message = "message", + Sender = "sender" + }, + ReceptorLocalMessageIds = new Dictionary + { + { + "receptor", "" + } + } + }); + + Assert.That(passedQueryParams["sender"], Is.EqualTo("sender")); + } + + [Test] + public async Task Send_LocalMessageIdsAreNotQualified_LocalIdNotInParams() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send( + new SendSingleMessageRequest + { + MessageInfo = new MessageInfo + { + Message = "message" + }, + ReceptorLocalMessageIds = new Dictionary + { + { + "receptor", "" + } + } + }); + + Assert.That(passedQueryParams.ContainsKey("localId"), Is.False); + } + + [Test] + public async Task Send_LocalMessageIdsAreQualified_LocalIdInParams() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send( + new SendSingleMessageRequest + { + MessageInfo = new MessageInfo + { + Message = "message" + }, + ReceptorLocalMessageIds = new Dictionary + { + { + "receptor", "localMessageId" + } + } + }); + + Assert.That(passedQueryParams["localId"], Is.EqualTo("localMessageId")); + } + + [Test] + public async Task Send_WhenCalled_CheckStaticParams() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send( + new SendSingleMessageRequest + { + MessageInfo = new MessageInfo + { + Message = "message" + }, + ReceptorLocalMessageIds = new Dictionary + { + { + "receptor1", "" + }, + { + "receptor2", "" + } + } + }); + + Assert.That(passedQueryParams["receptor"], Is.EqualTo("receptor1,receptor2")); + Assert.That(passedQueryParams["message"], Is.EqualTo("message")); + } + + [Test] + public async Task Send_DefaultDate_DateParamIsZero() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send( + new SendSingleMessageRequest + { + MessageInfo = new MessageInfo + { + Message = "message" + }, + ReceptorLocalMessageIds = new Dictionary + { + { + "receptor", "" + } + } + }); + + Assert.That(passedQueryParams["date"], Is.EqualTo(0)); + } + + [Test] + public async Task Send_SetDate_DateParamHasValue() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + var dt = DateTime.Now; + + await _kavenegarMessageSender.Send( + new SendSingleMessageRequest + { + MessageInfo = new MessageInfo + { + Message = "message" + }, + ReceptorLocalMessageIds = new Dictionary + { + { + "receptor", "" + } + }, + Date = dt + }); + + Assert.That(passedQueryParams["date"], Is.EqualTo(dt.ToUnixTimestamp())); + } + + [Test] + public async Task Send_TypeNotSet_TypeValueIsDefault() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send( + new SendSingleMessageRequest + { + MessageInfo = new MessageInfo + { + Message = "message" + }, + ReceptorLocalMessageIds = new Dictionary + { + { + "receptor", "" + } + } + }); + + Assert.That(passedQueryParams["type"], Is.EqualTo((int)MessageType.Flash)); + } + + [Test] + [TestCase(MessageType.AppMemory)] + [TestCase(MessageType.MobileMemory)] + [TestCase(MessageType.SimMemory)] + public async Task Send_TypeSet_CheckTypeValue( + MessageType messageType) + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send( + new SendSingleMessageRequest + { + MessageInfo = new MessageInfo + { + Message = "message", + Type = messageType + }, + ReceptorLocalMessageIds = new Dictionary + { + { + "receptor", "" + } + } + }); + + Assert.That(passedQueryParams["type"], Is.EqualTo((int)messageType)); + } + + [Test] + public async Task Send_PostRequestReturnsNoResult_ResultIsNull() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + var result = await _kavenegarMessageSender.Send( + new SendSingleMessageRequest + { + MessageInfo = new MessageInfo + { + Message = "message" + }, + ReceptorLocalMessageIds = new Dictionary + { + { + "receptor", "" + } + } + }); + + Assert.That(result, Is.Null); + } + + [Test] + public async Task Send_PostRequestReturnsResult_ResultSendResultDto() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":[{}]}", Encoding.UTF8) + }); + + var result = await _kavenegarMessageSender.Send( + new SendSingleMessageRequest + { + MessageInfo = new MessageInfo + { + Message = "message" + }, + ReceptorLocalMessageIds = new Dictionary + { + { + "receptor", "" + } + } + }); + + Assert.That(result, Is.TypeOf()); + } +} \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToManyTests.cs b/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToManyTests.cs new file mode 100644 index 0000000..8ce11f4 --- /dev/null +++ b/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToManyTests.cs @@ -0,0 +1,439 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Kavenegar.Core.Dto.Result; +using Kavenegar.Core.Enums; +using Moq; +using NUnit.Framework; +using Shared.Infrastructure; +using MessageSender = Kavenegar.Core.KavenegarMessageSender; + +namespace Test.Kavenegar.Core.KavenegarMessageSender; + +[TestFixture] +public class SingleMessageSendToManyTests +{ + [SetUp] + public void SetUp() + { + _mockHttpClientHelper = new Mock(); + _kavenegarMessageSender = new MessageSender(_mockHttpClientHelper.Object, ""); + } + + private MessageSender _kavenegarMessageSender = null!; + private Mock _mockHttpClientHelper = null!; + + [Test] + public async Task Send_WhenCalled_CallsPostAsync() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send( + "message", + new Dictionary + { + { + "receptor", "" + } + }); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + public async Task Send_SenderIsEmpty_SenderNotInParams() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send( + "message", + new Dictionary + { + { + "receptor", "" + } + }); + Assert.That(passedQueryParams.ContainsKey("sender"), Is.False); + } + + [Test] + public async Task Send_SenderNotEmpty_SenderInParams() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send( + "message", + new Dictionary + { + { + "receptor", "" + } + }, + "sender"); + + Assert.That(passedQueryParams["sender"], Is.EqualTo("sender")); + } + + [Test] + public async Task Send_LocalMessageIdsAreNotQualified_LocalIdNotInParams() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + await _kavenegarMessageSender.Send( + "message", + new Dictionary + { + { + "receptor", "" + } + }); + + Assert.That(passedQueryParams.ContainsKey("localId"), Is.False); + } + + [Test] + public async Task Send_LocalMessageIdsAreQualified_LocalIdInParams() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + await _kavenegarMessageSender.Send( + "message", + new Dictionary + { + { + "receptor", "localMessageId" + } + }); + + Assert.That(passedQueryParams["localId"], Is.EqualTo("localMessageId")); + } + + [Test] + public async Task Send_WhenCalled_CheckStaticParams() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + await _kavenegarMessageSender.Send( + "message", + new Dictionary + { + { + "receptor1", "" + }, + { + "receptor2", "" + } + }); + + Assert.That(passedQueryParams["receptor"], Is.EqualTo("receptor1,receptor2")); + Assert.That(passedQueryParams["message"], Is.EqualTo("message")); + } + + [Test] + public async Task Send_DefaultDate_DateParamIsZero() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + await _kavenegarMessageSender.Send( + "message", + new Dictionary + { + { + "receptor", "" + } + }); + + Assert.That(passedQueryParams["date"], Is.EqualTo(0)); + } + + [Test] + public async Task Send_SetDate_DateParamHasValue() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + var dt = DateTime.Now; + + await _kavenegarMessageSender.Send( + "message", + new Dictionary + { + { + "receptor", "" + } + }, + dateTime: dt); + + Assert.That(passedQueryParams["date"], Is.EqualTo(dt.ToUnixTimestamp())); + } + + [Test] + public async Task Send_TypeNotSet_TypeValueIsDefault() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + await _kavenegarMessageSender.Send( + "message", + new Dictionary + { + { + "receptor", "" + } + }); + + Assert.That(passedQueryParams["type"], Is.EqualTo((int)MessageType.Flash)); + } + + [Test] + [TestCase(MessageType.AppMemory)] + [TestCase(MessageType.MobileMemory)] + [TestCase(MessageType.SimMemory)] + public async Task Send_TypeSet_CheckTypeValue( + MessageType messageType) + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + await _kavenegarMessageSender.Send( + "message", + new Dictionary + { + { + "receptor", "" + } + }, + messageType: messageType); + + Assert.That(passedQueryParams["type"], Is.EqualTo((int)messageType)); + } + + [Test] + public async Task Send_PostRequestReturnsNoResult_ResultIsNull() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + var result = await _kavenegarMessageSender.Send("message", "receptor"); + + Assert.That(result, Is.Null); + } + + [Test] + public async Task Send_PostRequestReturnsResult_ResultSendResultDto() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":[{}]}", Encoding.UTF8) + }); + + var result = await _kavenegarMessageSender.Send("message", "receptor"); + + Assert.That(result, Is.TypeOf()); + } +} \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToOneTests.cs b/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToOneTests.cs new file mode 100644 index 0000000..15beb54 --- /dev/null +++ b/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToOneTests.cs @@ -0,0 +1,381 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Kavenegar.Core.Dto.Result; +using Kavenegar.Core.Enums; +using Moq; +using NUnit.Framework; +using Shared.Infrastructure; +using MessageSender = Kavenegar.Core.KavenegarMessageSender; + +namespace Test.Kavenegar.Core.KavenegarMessageSender; + +[TestFixture] +public class SingleMessageSendToOneTests +{ + [SetUp] + public void SetUp() + { + _mockHttpClientHelper = new Mock(); + _kavenegarMessageSender = new MessageSender(_mockHttpClientHelper.Object, ""); + } + + private MessageSender _kavenegarMessageSender = null!; + private Mock _mockHttpClientHelper = null!; + + [Test] + public async Task Send_WhenCalled_CallsPostAsync() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send("message", "receptor"); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + public async Task Send_SenderIsEmpty_SenderNotInParams() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send("message", "receptor"); + + Assert.That(passedQueryParams.ContainsKey("sender"), Is.False); + } + + [Test] + public async Task Send_SenderNotEmpty_SenderInParams() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send( + "message", + "receptor", + "sender"); + + Assert.That(passedQueryParams["sender"], Is.EqualTo("sender")); + } + + [Test] + public async Task Send_LocalMessageIdsAreNotQualified_LocalIdNotInParams() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send("message", "receptor"); + + Assert.That(passedQueryParams.ContainsKey("localId"), Is.False); + } + + [Test] + public async Task Send_LocalMessageIdsAreQualified_LocalIdInParams() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send( + "message", + "receptor", + localMessageId: "localMessageId"); + + Assert.That(passedQueryParams.ContainsKey("localId"), Is.True); + } + + [Test] + public async Task Send_WhenCalled_CheckStaticParams() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send("message", "receptor"); + + Assert.That(passedQueryParams["receptor"], Is.EqualTo("receptor")); + Assert.That(passedQueryParams["message"], Is.EqualTo("message")); + } + + [Test] + public async Task Send_DefaultDate_DateParamIsZero() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send("message", "receptor"); + + Assert.That(passedQueryParams["date"], Is.EqualTo(0)); + } + + [Test] + public async Task Send_SpecificDate_DateParamHasValue() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + var dt = DateTime.Now; + await _kavenegarMessageSender.Send( + "message", + "receptor", + dateTime: dt); + + Assert.That(passedQueryParams["date"], Is.EqualTo(dt.ToUnixTimestamp())); + } + + [Test] + public async Task Send_TypeNotSet_TypeValueIsDefault() + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send("message", "receptor"); + + Assert.That(passedQueryParams["type"], Is.EqualTo((int)MessageType.Flash)); + } + + [Test] + [TestCase(MessageType.AppMemory)] + [TestCase(MessageType.MobileMemory)] + [TestCase(MessageType.SimMemory)] + public async Task Send_TypeSet_CheckTypeValue( + MessageType messageType) + { + Dictionary passedQueryParams = null!; + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + await _kavenegarMessageSender.Send( + "message", + "receptor", + messageType: messageType); + + Assert.That(passedQueryParams["type"], Is.EqualTo((int)messageType)); + } + + [Test] + public async Task Send_PostRequestReturnsNoResult_ResultIsNull() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}", Encoding.UTF8) + }); + + var result = await _kavenegarMessageSender.Send("message", "receptor"); + + Assert.That(result, Is.Null); + } + + [Test] + public async Task Send_PostRequestReturnsResult_ResultSendResultDto() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/send.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":[{}]}", Encoding.UTF8) + }); + + var result = await _kavenegarMessageSender.Send("message", "receptor"); + + Assert.That(result, Is.TypeOf()); + } +} \ No newline at end of file diff --git a/Test/Kavenegar.Core/Kavenegar.Core.csproj b/Test/Test.Kavenegar.Core/Test.Kavenegar.Core.csproj similarity index 74% rename from Test/Kavenegar.Core/Kavenegar.Core.csproj rename to Test/Test.Kavenegar.Core/Test.Kavenegar.Core.csproj index 65a4f7b..58ab01c 100644 --- a/Test/Kavenegar.Core/Kavenegar.Core.csproj +++ b/Test/Test.Kavenegar.Core/Test.Kavenegar.Core.csproj @@ -9,9 +9,14 @@ + + + + + From cdc0384fa9ddba8233066259b52338fb674e40e8 Mon Sep 17 00:00:00 2001 From: alireza995 <88311706+alireza995@users.noreply.github.com> Date: Mon, 12 Dec 2022 00:57:50 +0330 Subject: [PATCH 09/14] test(KavenegarMessageSender) : test all methods test all methods of KavenegarMessageSender class closes nothing --- .../Kavenegar.Core/Dto/Message/MessageInfo.cs | 10 +- .../Dto/Message/SendMessageInfo.cs | 12 +- .../Dto/Message/SendMultiMessageRequest.cs | 8 +- .../Dto/Message/SendSingleMessageRequest.cs | 12 +- .../Dto/Message/VerifyLookupRequest.cs | 25 + .../Kavenegar.Core/IKavenegarMessageSender.cs | 8 +- Code/Kavenegar.Core/Kavenegar.Core.csproj | 4 +- Code/Kavenegar.Core/KavenegarMessageSender.cs | 110 ++-- .../Shared.Infrastructure/HttpClientHelper.cs | 6 +- .../Shared.Infrastructure/JsonUtility.cs | 14 +- .../Shared.Infrastructure/StringUtility.cs | 4 +- .../MultiMessage/SendWithDtoTests.cs | 378 ++++++++++++ .../MultiMessage/SendWithParamsTests.cs | 372 ++++++++++++ .../SendToManyBaseMethodTests.cs} | 175 ++---- .../SendToManyTests.cs} | 24 +- .../SendToOneTests.cs} | 4 +- .../VerifyLookup/VerifyLookupWithDto.cs | 550 ++++++++++++++++++ .../VerifyLookup/VerifyLookupWithParam.cs | 524 +++++++++++++++++ .../Test.Kavenegar.Core.csproj | 12 +- 19 files changed, 2044 insertions(+), 208 deletions(-) create mode 100644 Code/Kavenegar.Core/Dto/Message/VerifyLookupRequest.cs create mode 100644 Test/Test.Kavenegar.Core/KavenegarMessageSender/MultiMessage/SendWithDtoTests.cs create mode 100644 Test/Test.Kavenegar.Core/KavenegarMessageSender/MultiMessage/SendWithParamsTests.cs rename Test/Test.Kavenegar.Core/KavenegarMessageSender/{SingleMessageSendToManyBaseMethodTests.cs => SingleMessage/SendToManyBaseMethodTests.cs} (77%) rename Test/Test.Kavenegar.Core/KavenegarMessageSender/{SingleMessageSendToManyTests.cs => SingleMessage/SendToManyTests.cs} (96%) rename Test/Test.Kavenegar.Core/KavenegarMessageSender/{SingleMessageSendToOneTests.cs => SingleMessage/SendToOneTests.cs} (99%) create mode 100644 Test/Test.Kavenegar.Core/KavenegarMessageSender/VerifyLookup/VerifyLookupWithDto.cs create mode 100644 Test/Test.Kavenegar.Core/KavenegarMessageSender/VerifyLookup/VerifyLookupWithParam.cs diff --git a/Code/Kavenegar.Core/Dto/Message/MessageInfo.cs b/Code/Kavenegar.Core/Dto/Message/MessageInfo.cs index 0f0b087..ade3c35 100644 --- a/Code/Kavenegar.Core/Dto/Message/MessageInfo.cs +++ b/Code/Kavenegar.Core/Dto/Message/MessageInfo.cs @@ -4,7 +4,13 @@ namespace Kavenegar.Core.Dto.Message; public class MessageInfo { - public string Sender { get; set; } = null!; - public string Message { get; set; } = null!; + public MessageInfo( + string message) + { + Message = message; + } + + public string? Sender { get; set; } + public string Message { get; set; } public MessageType Type { get; set; } = MessageType.Flash; } \ No newline at end of file diff --git a/Code/Kavenegar.Core/Dto/Message/SendMessageInfo.cs b/Code/Kavenegar.Core/Dto/Message/SendMessageInfo.cs index 6a09e09..bfb9505 100644 --- a/Code/Kavenegar.Core/Dto/Message/SendMessageInfo.cs +++ b/Code/Kavenegar.Core/Dto/Message/SendMessageInfo.cs @@ -2,7 +2,15 @@ public class SendMessageInfo { - public MessageInfo MessageInfo { get; set; } = null!; - public string Receptor { get; set; } = null!; + public SendMessageInfo( + MessageInfo messageInfo, + string receptor) + { + MessageInfo = messageInfo; + Receptor = receptor; + } + + public MessageInfo MessageInfo { get; set; } + public string Receptor { get; set; } public string LocalMessageId { get; set; } = null!; } \ No newline at end of file diff --git a/Code/Kavenegar.Core/Dto/Message/SendMultiMessageRequest.cs b/Code/Kavenegar.Core/Dto/Message/SendMultiMessageRequest.cs index 4be63d1..cd12628 100644 --- a/Code/Kavenegar.Core/Dto/Message/SendMultiMessageRequest.cs +++ b/Code/Kavenegar.Core/Dto/Message/SendMultiMessageRequest.cs @@ -2,7 +2,13 @@ public class SendMultiMessageRequest { - public IEnumerable SendMessageInfos { get; set; } = null!; + public SendMultiMessageRequest( + IEnumerable sendMessageInfos) + { + SendMessageInfos = sendMessageInfos; + } + + public IEnumerable SendMessageInfos { get; set; } public DateTime Date { get; set; } public bool Hide { get; set; } } \ No newline at end of file diff --git a/Code/Kavenegar.Core/Dto/Message/SendSingleMessageRequest.cs b/Code/Kavenegar.Core/Dto/Message/SendSingleMessageRequest.cs index a16414f..a46ec14 100644 --- a/Code/Kavenegar.Core/Dto/Message/SendSingleMessageRequest.cs +++ b/Code/Kavenegar.Core/Dto/Message/SendSingleMessageRequest.cs @@ -2,13 +2,21 @@ public class SendSingleMessageRequest { - public MessageInfo MessageInfo { get; set; } = null!; + public SendSingleMessageRequest( + MessageInfo messageInfo, + Dictionary receptorLocalMessageIds) + { + MessageInfo = messageInfo; + ReceptorLocalMessageIds = receptorLocalMessageIds; + } + + public MessageInfo MessageInfo { get; set; } /// /// Key is receptor /// Value is local message id /// - public Dictionary ReceptorLocalMessageIds { get; set; } = null!; + public Dictionary ReceptorLocalMessageIds { get; set; } public DateTime? Date { get; set; } public bool Hide { get; set; } diff --git a/Code/Kavenegar.Core/Dto/Message/VerifyLookupRequest.cs b/Code/Kavenegar.Core/Dto/Message/VerifyLookupRequest.cs new file mode 100644 index 0000000..18a8de1 --- /dev/null +++ b/Code/Kavenegar.Core/Dto/Message/VerifyLookupRequest.cs @@ -0,0 +1,25 @@ +using Kavenegar.Core.Enums; + +namespace Kavenegar.Core.Dto.Message; + +public class VerifyLookupRequest +{ + public VerifyLookupRequest( + string receptor, + string template, + string token1) + { + Receptor = receptor; + Template = template; + Token1 = token1; + } + + public string Receptor { get; set; } + public string Template { get; set; } + public string Token1 { get; set; } + public string? Token2 { get; set; } + public string? Token3 { get; set; } + public string? Token4 { get; set; } + public string? Token5 { get; set; } + public VerifyLookupType? VerifyLookupType { get; set; } = null!; +} \ No newline at end of file diff --git a/Code/Kavenegar.Core/IKavenegarMessageSender.cs b/Code/Kavenegar.Core/IKavenegarMessageSender.cs index 95c70ca..076c359 100644 --- a/Code/Kavenegar.Core/IKavenegarMessageSender.cs +++ b/Code/Kavenegar.Core/IKavenegarMessageSender.cs @@ -41,7 +41,7 @@ public interface IKavenegarMessageSender /// Task?> Send( string message, - Dictionary receptors, + Dictionary receptors, string sender = "", DateTime? dateTime = null, bool hide = false, @@ -63,9 +63,9 @@ public interface IKavenegarMessageSender CancellationToken cancellationToken = default); Task VerifyLookup( - string? receptor, - string? template, - string? token1, + string receptor, + string template, + string token1, string? token2 = null, string? token3 = null, string? token4 = null, diff --git a/Code/Kavenegar.Core/Kavenegar.Core.csproj b/Code/Kavenegar.Core/Kavenegar.Core.csproj index 7117abf..672080c 100644 --- a/Code/Kavenegar.Core/Kavenegar.Core.csproj +++ b/Code/Kavenegar.Core/Kavenegar.Core.csproj @@ -7,11 +7,11 @@ - + - + diff --git a/Code/Kavenegar.Core/KavenegarMessageSender.cs b/Code/Kavenegar.Core/KavenegarMessageSender.cs index fcf614e..f9252e4 100644 --- a/Code/Kavenegar.Core/KavenegarMessageSender.cs +++ b/Code/Kavenegar.Core/KavenegarMessageSender.cs @@ -38,23 +38,24 @@ public KavenegarMessageSender( MessageType messageType = MessageType.Flash, CancellationToken cancellationToken = default) { - var sendSingleMessageRequest = new SendSingleMessageRequest + var messageInfo = new MessageInfo(message) + { + Sender = sender, + Type = messageType + }; + + var receptorLocalMessageIds = new Dictionary { - Hide = hide, - MessageInfo = new MessageInfo - { - Message = message, - Sender = sender, - Type = messageType - }, - ReceptorLocalMessageIds = new Dictionary { - { - receptor, localMessageId - } + receptor, localMessageId } }; + var sendSingleMessageRequest = new SendSingleMessageRequest(messageInfo, receptorLocalMessageIds) + { + Hide = hide + }; + if (dateTime.HasValue) sendSingleMessageRequest.Date = dateTime; return (await Send(sendSingleMessageRequest, cancellationToken))?.FirstOrDefault(); @@ -73,23 +74,22 @@ public KavenegarMessageSender( /// public async Task?> Send( string message, - Dictionary receptors, + Dictionary receptors, string sender = "", DateTime? dateTime = null, bool hide = false, MessageType messageType = MessageType.Flash, CancellationToken cancellationToken = default) { - var sendSingleMessageRequest = new SendSingleMessageRequest - { - Hide = hide, - MessageInfo = new MessageInfo + var sendSingleMessageRequest = new SendSingleMessageRequest( + new MessageInfo(message) { - Message = message, Sender = sender, Type = messageType }, - ReceptorLocalMessageIds = receptors + receptors) + { + Hide = hide }; if (dateTime.HasValue) sendSingleMessageRequest.Date = dateTime; @@ -136,11 +136,10 @@ public KavenegarMessageSender( CancellationToken cancellationToken = default) { return await Send( - new SendMultiMessageRequest + new SendMultiMessageRequest(sendMessageInfos) { Date = dateTime ?? DateTime.Now, - Hide = hide, - SendMessageInfos = sendMessageInfos + Hide = hide }, cancellationToken); } @@ -153,26 +152,20 @@ public KavenegarMessageSender( { { "message", - await messages.SendMessageInfos + messages.SendMessageInfos .Select(sendMessageInfo => WebUtility.HtmlEncode(sendMessageInfo.MessageInfo.Message)) .ToList() .Serialize(cancellationToken) }, - { - "sender", - await messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.MessageInfo.Sender) - .ToList() - .Serialize(cancellationToken) - }, { "receptor", - await messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.Receptor) + messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.Receptor) .ToList() .Serialize(cancellationToken) }, { "type", - await messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.MessageInfo.Type.ToString()) + messages.SendMessageInfos.Select(sendMessageInfo => (int)sendMessageInfo.MessageInfo.Type) .Serialize(cancellationToken) }, { @@ -180,14 +173,19 @@ await messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.Messag } }; + if (messages.SendMessageInfos.All( + sendMessageInfo => sendMessageInfo.MessageInfo.Sender.IsNotNullOrWhiteSpace())) + requestParams.Add( + "sender", + messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.MessageInfo.Sender) + .ToList() + .Serialize(cancellationToken)); + if (messages.SendMessageInfos.All( sendMessageInfo => !string.IsNullOrWhiteSpace(sendMessageInfo.LocalMessageId))) requestParams.Add( "localMessageIds", - string.Join( - ",", - messages.SendMessageInfos.Select( - sendMessageInfo => !string.IsNullOrWhiteSpace(sendMessageInfo.LocalMessageId)))); + string.Join(",", messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.LocalMessageId))); return await RequestSender>( "sms/sendarray.json", @@ -197,34 +195,54 @@ await messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.Messag } public async Task VerifyLookup( - string? receptor, - string? template, - string? token1, + string receptor, + string template, + string token1, string? token2 = null, string? token3 = null, string? token4 = null, string? token5 = null, VerifyLookupType? type = null, CancellationToken cancellationToken = default) + { + return await VerifyLookup( + new VerifyLookupRequest( + receptor, + template, + token1) + { + Token2 = token2, + Token3 = token3, + Token4 = token4, + Token5 = token5, + VerifyLookupType = type + }, + cancellationToken); + } + + public async Task VerifyLookup( + VerifyLookupRequest verifyLookupRequest, + CancellationToken cancellationToken = default) { var queryParams = new Dictionary { { - "receptor", receptor + "receptor", verifyLookupRequest.Receptor }, { - "template", template + "template", verifyLookupRequest.Template }, { - "token", token1 + "token", verifyLookupRequest.Token1 } }; - if (string.IsNullOrWhiteSpace(token2)) queryParams.Add("token2", token2); - if (string.IsNullOrWhiteSpace(token3)) queryParams.Add("token3", token3); - if (string.IsNullOrWhiteSpace(token4)) queryParams.Add("token10", token4); - if (string.IsNullOrWhiteSpace(token5)) queryParams.Add("token20", token5); - if (type.HasValue) queryParams.Add("type", type.Value.ToString()); + if (verifyLookupRequest.Token2.IsNotNullOrWhiteSpace()) queryParams.Add("token2", verifyLookupRequest.Token2); + if (verifyLookupRequest.Token3.IsNotNullOrWhiteSpace()) queryParams.Add("token3", verifyLookupRequest.Token3); + if (verifyLookupRequest.Token4.IsNotNullOrWhiteSpace()) queryParams.Add("token10", verifyLookupRequest.Token4); + if (verifyLookupRequest.Token5.IsNotNullOrWhiteSpace()) queryParams.Add("token20", verifyLookupRequest.Token5); + if (verifyLookupRequest.VerifyLookupType.HasValue) + queryParams.Add("type", (int)verifyLookupRequest.VerifyLookupType.Value); return (await RequestSender>( "verify/lookup.json", diff --git a/Code/Shared/Shared.Infrastructure/HttpClientHelper.cs b/Code/Shared/Shared.Infrastructure/HttpClientHelper.cs index 6ae1fea..156017a 100644 --- a/Code/Shared/Shared.Infrastructure/HttpClientHelper.cs +++ b/Code/Shared/Shared.Infrastructure/HttpClientHelper.cs @@ -18,14 +18,14 @@ public async Task PostAsync( return await _httpClient.PostAsync( address, - body == null ? null : await SerializeBody(body, cancellationToken), + body == null ? null : SerializeBody(body, cancellationToken), cancellationToken); } - private async Task SerializeBody( + private StringContent SerializeBody( object obj, CancellationToken cancellationToken) { - return new StringContent(await obj.Serialize(cancellationToken) ?? ""); + return new StringContent(obj.Serialize(cancellationToken)); } } \ No newline at end of file diff --git a/Code/Shared/Shared.Infrastructure/JsonUtility.cs b/Code/Shared/Shared.Infrastructure/JsonUtility.cs index 04f1930..80cddd0 100644 --- a/Code/Shared/Shared.Infrastructure/JsonUtility.cs +++ b/Code/Shared/Shared.Infrastructure/JsonUtility.cs @@ -1,22 +1,14 @@ -using System.Text; -using System.Text.Json; +using System.Text.Json; namespace Shared.Infrastructure; public static class JsonUtility { - public static async Task Serialize( + public static string Serialize( this T obj, CancellationToken cancellationToken = default) { - var stream = new MemoryStream(); - await JsonSerializer.SerializeAsync( - stream, - obj, - cancellationToken: cancellationToken); - - var streamReader = new StreamReader(stream, Encoding.UTF8); - return await streamReader.ReadToEndAsync(); + return JsonSerializer.Serialize(obj, obj!.GetType()); } public static async Task Deserialize( diff --git a/Code/Shared/Shared.Infrastructure/StringUtility.cs b/Code/Shared/Shared.Infrastructure/StringUtility.cs index 65bab68..cbb6eae 100644 --- a/Code/Shared/Shared.Infrastructure/StringUtility.cs +++ b/Code/Shared/Shared.Infrastructure/StringUtility.cs @@ -3,13 +3,13 @@ public static class StringUtility { public static bool IsNullOrWhiteSpace( - this string text) + this string? text) { return string.IsNullOrWhiteSpace(text); } public static bool IsNotNullOrWhiteSpace( - this string text) + this string? text) { return !text.IsNullOrWhiteSpace(); } diff --git a/Test/Test.Kavenegar.Core/KavenegarMessageSender/MultiMessage/SendWithDtoTests.cs b/Test/Test.Kavenegar.Core/KavenegarMessageSender/MultiMessage/SendWithDtoTests.cs new file mode 100644 index 0000000..7cad31d --- /dev/null +++ b/Test/Test.Kavenegar.Core/KavenegarMessageSender/MultiMessage/SendWithDtoTests.cs @@ -0,0 +1,378 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Kavenegar.Core.Dto.Message; +using Kavenegar.Core.Enums; +using Moq; +using NUnit.Framework; +using Shared.Infrastructure; +using MessageSender = Kavenegar.Core.KavenegarMessageSender; + +namespace Test.Kavenegar.Core.KavenegarMessageSender.MultiMessage; + +[TestFixture] +public class SendWithDtoTests +{ + [SetUp] + public void SetUp() + { + _mockHttpClientHelper = new Mock(); + _kavenegarMessageSender = new MessageSender(_mockHttpClientHelper.Object, ""); + } + + private MessageSender _kavenegarMessageSender = null!; + private Mock _mockHttpClientHelper = null!; + + [Test] + public async Task Send_WhenCalled_CallsPostAsync() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/sendarray.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.Send(new SendMultiMessageRequest(new List())); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "sms/sendarray.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + [TestCase("test")] + [TestCase("تست")] + public async Task Send_WhenCalled_CheckMessageQueryParam( + string message) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/sendarray.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.Send( + new SendMultiMessageRequest( + new List + { + new(new MessageInfo(message), ""), + new(new MessageInfo(message), "") + })); + + var expectedMessages = new List + { + WebUtility.HtmlEncode(message), + WebUtility.HtmlEncode(message) + }.Serialize(); + + Assert.That(passedQueryParams["message"], Is.EqualTo(expectedMessages)); + } + + [Test] + public async Task Send_WithNoSender_QueryParamsNotIncludeSender() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/sendarray.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.Send( + new SendMultiMessageRequest( + new List + { + new(new MessageInfo(""), "") + })); + + Assert.That(passedQueryParams.ContainsKey("sender"), Is.False); + } + + [Test] + [TestCase("1")] + [TestCase("2")] + public async Task Send_WithSender_QueryParamsIncludeSender( + string sender) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/sendarray.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.Send( + new SendMultiMessageRequest( + new List + { + new(new MessageInfo(""), "") + { + MessageInfo = new MessageInfo("") + { + Sender = sender + } + }, + new(new MessageInfo(""), "") + { + MessageInfo = new MessageInfo("") + { + Sender = sender + } + } + })); + + Assert.That(passedQueryParams["sender"], Is.EqualTo($"[\"{sender}\",\"{sender}\"]")); + } + + [Test] + [TestCase("1")] + [TestCase("2")] + public async Task Send_WhenCalled_CheckReceptorQueryParam(string receptor) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/sendarray.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.Send( + new SendMultiMessageRequest( + new List + { + new(new MessageInfo(""), receptor) + { + MessageInfo = new MessageInfo("") + }, + new(new MessageInfo(""), receptor) + { + MessageInfo = new MessageInfo("") + } + })); + + Assert.That(passedQueryParams["receptor"], Is.EqualTo($"[\"{receptor}\",\"{receptor}\"]")); + } + + [Test] + [TestCase(MessageType.Flash)] + [TestCase(MessageType.AppMemory)] + public async Task Send_WhenCalled_CheckTypeQueryParam(MessageType messageType) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/sendarray.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.Send( + new SendMultiMessageRequest( + new List + { + new(new MessageInfo(""), "") + { + MessageInfo = new MessageInfo("") + { + Type = messageType + } + }, + new(new MessageInfo(""), "") + { + MessageInfo = new MessageInfo("") + { + Type = messageType + } + } + })); + + Assert.That(passedQueryParams["type"], Is.EqualTo($"[{(int)messageType},{(int)messageType}]")); + } + + [Test] + public async Task Send_WhenCalled_CheckDateQueryParam() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/sendarray.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + var dt = DateTime.Now; + + await _kavenegarMessageSender.Send( + new SendMultiMessageRequest( + new List + { + new(new MessageInfo(""), "") + { + MessageInfo = new MessageInfo("") + }, + new(new MessageInfo(""), "") + { + MessageInfo = new MessageInfo("") + } + }) + { + Date = dt + }); + + Assert.That(passedQueryParams["date"], Is.EqualTo(dt.ToUnixTimestamp())); + } + + [Test] + [TestCase("1")] + [TestCase("2")] + public async Task Send_WithLocalMessageId_QueryParamsIncludeLocalMessageId(string localMessageId) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/sendarray.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.Send( + new SendMultiMessageRequest( + new List + { + new(new MessageInfo(""), "") + { + MessageInfo = new MessageInfo(""), + LocalMessageId = localMessageId + }, + new(new MessageInfo(""), "") + { + MessageInfo = new MessageInfo(""), + LocalMessageId = localMessageId + } + })); + + Assert.That(passedQueryParams["localMessageIds"], Is.EqualTo($"{localMessageId},{localMessageId}")); + } +} \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/KavenegarMessageSender/MultiMessage/SendWithParamsTests.cs b/Test/Test.Kavenegar.Core/KavenegarMessageSender/MultiMessage/SendWithParamsTests.cs new file mode 100644 index 0000000..1ae4634 --- /dev/null +++ b/Test/Test.Kavenegar.Core/KavenegarMessageSender/MultiMessage/SendWithParamsTests.cs @@ -0,0 +1,372 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Kavenegar.Core.Dto.Message; +using Kavenegar.Core.Enums; +using Moq; +using NUnit.Framework; +using Shared.Infrastructure; +using MessageSender = Kavenegar.Core.KavenegarMessageSender; + +namespace Test.Kavenegar.Core.KavenegarMessageSender.MultiMessage; + +[TestFixture] +public class SendWithParamsTests +{ + [SetUp] + public void SetUp() + { + _mockHttpClientHelper = new Mock(); + _kavenegarMessageSender = new MessageSender(_mockHttpClientHelper.Object, ""); + } + + private MessageSender _kavenegarMessageSender = null!; + private Mock _mockHttpClientHelper = null!; + + [Test] + public async Task Send_WhenCalled_CallsPostAsync() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/sendarray.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.Send(new List()); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "sms/sendarray.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + [TestCase("test")] + [TestCase("تست")] + public async Task Send_WhenCalled_CheckMessageQueryParam( + string message) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/sendarray.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.Send( + new List + { + new(new MessageInfo(message), ""), + new(new MessageInfo(message), ""), + }); + + var expectedMessages = new List + { + WebUtility.HtmlEncode(message), + WebUtility.HtmlEncode(message) + }.Serialize(); + + Assert.That(passedQueryParams["message"], Is.EqualTo(expectedMessages)); + } + + [Test] + public async Task Send_WithNoSender_QueryParamsNotIncludeSender() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/sendarray.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.Send( + new List + { + new(new MessageInfo(""), "") + { + MessageInfo = new MessageInfo("") + } + }); + + Assert.That(passedQueryParams.ContainsKey("sender"), Is.False); + } + + [Test] + [TestCase("1")] + [TestCase("2")] + public async Task Send_WithSender_QueryParamsIncludeSender( + string sender) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/sendarray.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.Send( + new List + { + new(new MessageInfo(""), "") + { + MessageInfo = new MessageInfo("") + { + Sender = sender + } + }, + new(new MessageInfo(""), "") + { + MessageInfo = new MessageInfo("") + { + Sender = sender + } + } + }); + + Assert.That(passedQueryParams["sender"], Is.EqualTo($"[\"{sender}\",\"{sender}\"]")); + } + + [Test] + [TestCase("1")] + [TestCase("2")] + public async Task Send_WhenCalled_CheckReceptorQueryParam(string receptor) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/sendarray.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.Send( + new List + { + new(new MessageInfo(""), receptor) + { + MessageInfo = new MessageInfo("") + }, + new(new MessageInfo(""), receptor) + { + MessageInfo = new MessageInfo("") + } + }); + + Assert.That(passedQueryParams["receptor"], Is.EqualTo($"[\"{receptor}\",\"{receptor}\"]")); + } + + [Test] + [TestCase(MessageType.Flash)] + [TestCase(MessageType.AppMemory)] + public async Task Send_WhenCalled_CheckTypeQueryParam(MessageType messageType) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/sendarray.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.Send( + new List + { + new(new MessageInfo(""), "") + { + MessageInfo = new MessageInfo("") + { + Type = messageType + } + }, + new(new MessageInfo(""), "") + { + MessageInfo = new MessageInfo("") + { + Type = messageType + } + } + }); + + Assert.That(passedQueryParams["type"], Is.EqualTo($"[{(int)messageType},{(int)messageType}]")); + } + + [Test] + public async Task Send_WhenCalled_CheckDateQueryParam() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/sendarray.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + var dt = DateTime.Now; + + await _kavenegarMessageSender.Send( + new List + { + new(new MessageInfo(""), "") + { + MessageInfo = new MessageInfo("") + }, + new(new MessageInfo(""), "") + { + MessageInfo = new MessageInfo("") + } + }, + dateTime:dt); + + Assert.That(passedQueryParams["date"], Is.EqualTo(dt.ToUnixTimestamp())); + } + + [Test] + [TestCase("1")] + [TestCase("2")] + public async Task Send_WithLocalMessageId_QueryParamsIncludeLocalMessageId(string localMessageId) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/sendarray.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.Send( + new List + { + new(new MessageInfo(""), "") + { + MessageInfo = new MessageInfo(""), + LocalMessageId = localMessageId + }, + new(new MessageInfo(""), "") + { + MessageInfo = new MessageInfo(""), + LocalMessageId = localMessageId + } + }); + + Assert.That(passedQueryParams["localMessageIds"], Is.EqualTo($"{localMessageId},{localMessageId}")); + } +} \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToManyBaseMethodTests.cs b/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessage/SendToManyBaseMethodTests.cs similarity index 77% rename from Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToManyBaseMethodTests.cs rename to Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessage/SendToManyBaseMethodTests.cs index a0363fe..5802e28 100644 --- a/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToManyBaseMethodTests.cs +++ b/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessage/SendToManyBaseMethodTests.cs @@ -12,10 +12,10 @@ using Shared.Infrastructure; using MessageSender = Kavenegar.Core.KavenegarMessageSender; -namespace Test.Kavenegar.Core.KavenegarMessageSender; +namespace Test.Kavenegar.Core.KavenegarMessageSender.SingleMessage; [TestFixture] -public class SingleMessageSendToManyBaseMethodTests +public class SendToManyBaseMethodTests { [SetUp] public void SetUp() @@ -43,19 +43,14 @@ public async Task Send_WhenCalled_CallsPostAsync() }); await _kavenegarMessageSender.Send( - new SendSingleMessageRequest - { - MessageInfo = new MessageInfo - { - Message = "message" - }, - ReceptorLocalMessageIds = new Dictionary + new SendSingleMessageRequest( + new MessageInfo("message"), + new Dictionary { { - "receptor", "" + "receptor", null } - } - }); + })); _mockHttpClientHelper.Verify( i => i.PostAsync( @@ -91,19 +86,17 @@ public async Task Send_SenderIsEmpty_SenderNotInParams() }); await _kavenegarMessageSender.Send( - new SendSingleMessageRequest - { - MessageInfo = new MessageInfo + new SendSingleMessageRequest( + new MessageInfo("message") { Message = "message" }, - ReceptorLocalMessageIds = new Dictionary + new Dictionary { { - "receptor", "" + "receptor", null } - } - }); + })); Assert.That(passedQueryParams.ContainsKey("sender"), Is.False); } @@ -134,20 +127,17 @@ public async Task Send_SenderNotEmpty_SenderInParams() }); await _kavenegarMessageSender.Send( - new SendSingleMessageRequest - { - MessageInfo = new MessageInfo + new SendSingleMessageRequest( + new MessageInfo("message") { - Message = "message", Sender = "sender" }, - ReceptorLocalMessageIds = new Dictionary + new Dictionary { { - "receptor", "" + "receptor", null } - } - }); + })); Assert.That(passedQueryParams["sender"], Is.EqualTo("sender")); } @@ -178,19 +168,14 @@ public async Task Send_LocalMessageIdsAreNotQualified_LocalIdNotInParams() }); await _kavenegarMessageSender.Send( - new SendSingleMessageRequest - { - MessageInfo = new MessageInfo - { - Message = "message" - }, - ReceptorLocalMessageIds = new Dictionary + new SendSingleMessageRequest( + new MessageInfo("message"), + new Dictionary { { - "receptor", "" + "receptor", null } - } - }); + })); Assert.That(passedQueryParams.ContainsKey("localId"), Is.False); } @@ -221,19 +206,14 @@ public async Task Send_LocalMessageIdsAreQualified_LocalIdInParams() }); await _kavenegarMessageSender.Send( - new SendSingleMessageRequest - { - MessageInfo = new MessageInfo - { - Message = "message" - }, - ReceptorLocalMessageIds = new Dictionary + new SendSingleMessageRequest( + new MessageInfo("message"), + new Dictionary { { "receptor", "localMessageId" } - } - }); + })); Assert.That(passedQueryParams["localId"], Is.EqualTo("localMessageId")); } @@ -264,13 +244,9 @@ public async Task Send_WhenCalled_CheckStaticParams() }); await _kavenegarMessageSender.Send( - new SendSingleMessageRequest - { - MessageInfo = new MessageInfo - { - Message = "message" - }, - ReceptorLocalMessageIds = new Dictionary + new SendSingleMessageRequest( + new MessageInfo("message"), + new Dictionary { { "receptor1", "" @@ -278,8 +254,7 @@ await _kavenegarMessageSender.Send( { "receptor2", "" } - } - }); + })); Assert.That(passedQueryParams["receptor"], Is.EqualTo("receptor1,receptor2")); Assert.That(passedQueryParams["message"], Is.EqualTo("message")); @@ -311,19 +286,14 @@ public async Task Send_DefaultDate_DateParamIsZero() }); await _kavenegarMessageSender.Send( - new SendSingleMessageRequest - { - MessageInfo = new MessageInfo - { - Message = "message" - }, - ReceptorLocalMessageIds = new Dictionary + new SendSingleMessageRequest( + new MessageInfo("message"), + new Dictionary { { - "receptor", "" + "receptor", null } - } - }); + })); Assert.That(passedQueryParams["date"], Is.EqualTo(0)); } @@ -356,18 +326,15 @@ public async Task Send_SetDate_DateParamHasValue() var dt = DateTime.Now; await _kavenegarMessageSender.Send( - new SendSingleMessageRequest - { - MessageInfo = new MessageInfo - { - Message = "message" - }, - ReceptorLocalMessageIds = new Dictionary + new SendSingleMessageRequest( + new MessageInfo("message"), + new Dictionary { { - "receptor", "" + "receptor", null } - }, + }) + { Date = dt }); @@ -400,19 +367,14 @@ public async Task Send_TypeNotSet_TypeValueIsDefault() }); await _kavenegarMessageSender.Send( - new SendSingleMessageRequest - { - MessageInfo = new MessageInfo - { - Message = "message" - }, - ReceptorLocalMessageIds = new Dictionary + new SendSingleMessageRequest( + new MessageInfo("message"), + new Dictionary { { - "receptor", "" + "receptor", null } - } - }); + })); Assert.That(passedQueryParams["type"], Is.EqualTo((int)MessageType.Flash)); } @@ -447,20 +409,17 @@ public async Task Send_TypeSet_CheckTypeValue( }); await _kavenegarMessageSender.Send( - new SendSingleMessageRequest - { - MessageInfo = new MessageInfo + new SendSingleMessageRequest( + new MessageInfo("message") { - Message = "message", Type = messageType }, - ReceptorLocalMessageIds = new Dictionary + new Dictionary { { - "receptor", "" + "receptor", null } - } - }); + })); Assert.That(passedQueryParams["type"], Is.EqualTo((int)messageType)); } @@ -481,19 +440,14 @@ public async Task Send_PostRequestReturnsNoResult_ResultIsNull() }); var result = await _kavenegarMessageSender.Send( - new SendSingleMessageRequest - { - MessageInfo = new MessageInfo - { - Message = "message" - }, - ReceptorLocalMessageIds = new Dictionary + new SendSingleMessageRequest( + new MessageInfo("message"), + new Dictionary { { - "receptor", "" + "receptor", null } - } - }); + })); Assert.That(result, Is.Null); } @@ -514,20 +468,15 @@ public async Task Send_PostRequestReturnsResult_ResultSendResultDto() }); var result = await _kavenegarMessageSender.Send( - new SendSingleMessageRequest - { - MessageInfo = new MessageInfo - { - Message = "message" - }, - ReceptorLocalMessageIds = new Dictionary + new SendSingleMessageRequest( + new MessageInfo("message"), + new Dictionary { { - "receptor", "" + "receptor", null } - } - }); + })); - Assert.That(result, Is.TypeOf()); + Assert.That(result, Is.TypeOf>()); } } \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToManyTests.cs b/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessage/SendToManyTests.cs similarity index 96% rename from Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToManyTests.cs rename to Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessage/SendToManyTests.cs index 8ce11f4..eb93dc6 100644 --- a/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToManyTests.cs +++ b/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessage/SendToManyTests.cs @@ -11,10 +11,10 @@ using Shared.Infrastructure; using MessageSender = Kavenegar.Core.KavenegarMessageSender; -namespace Test.Kavenegar.Core.KavenegarMessageSender; +namespace Test.Kavenegar.Core.KavenegarMessageSender.SingleMessage; [TestFixture] -public class SingleMessageSendToManyTests +public class SendToManyTests { [SetUp] public void SetUp() @@ -43,7 +43,7 @@ public async Task Send_WhenCalled_CallsPostAsync() await _kavenegarMessageSender.Send( "message", - new Dictionary + new Dictionary { { "receptor", "" @@ -85,7 +85,7 @@ public async Task Send_SenderIsEmpty_SenderNotInParams() await _kavenegarMessageSender.Send( "message", - new Dictionary + new Dictionary { { "receptor", "" @@ -121,7 +121,7 @@ public async Task Send_SenderNotEmpty_SenderInParams() await _kavenegarMessageSender.Send( "message", - new Dictionary + new Dictionary { { "receptor", "" @@ -158,7 +158,7 @@ public async Task Send_LocalMessageIdsAreNotQualified_LocalIdNotInParams() }); await _kavenegarMessageSender.Send( "message", - new Dictionary + new Dictionary { { "receptor", "" @@ -194,7 +194,7 @@ public async Task Send_LocalMessageIdsAreQualified_LocalIdInParams() }); await _kavenegarMessageSender.Send( "message", - new Dictionary + new Dictionary { { "receptor", "localMessageId" @@ -230,7 +230,7 @@ public async Task Send_WhenCalled_CheckStaticParams() }); await _kavenegarMessageSender.Send( "message", - new Dictionary + new Dictionary { { "receptor1", "" @@ -270,7 +270,7 @@ public async Task Send_DefaultDate_DateParamIsZero() }); await _kavenegarMessageSender.Send( "message", - new Dictionary + new Dictionary { { "receptor", "" @@ -309,7 +309,7 @@ public async Task Send_SetDate_DateParamHasValue() await _kavenegarMessageSender.Send( "message", - new Dictionary + new Dictionary { { "receptor", "" @@ -346,7 +346,7 @@ public async Task Send_TypeNotSet_TypeValueIsDefault() }); await _kavenegarMessageSender.Send( "message", - new Dictionary + new Dictionary { { "receptor", "" @@ -386,7 +386,7 @@ public async Task Send_TypeSet_CheckTypeValue( }); await _kavenegarMessageSender.Send( "message", - new Dictionary + new Dictionary { { "receptor", "" diff --git a/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToOneTests.cs b/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessage/SendToOneTests.cs similarity index 99% rename from Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToOneTests.cs rename to Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessage/SendToOneTests.cs index 15beb54..6185664 100644 --- a/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessageSendToOneTests.cs +++ b/Test/Test.Kavenegar.Core/KavenegarMessageSender/SingleMessage/SendToOneTests.cs @@ -11,10 +11,10 @@ using Shared.Infrastructure; using MessageSender = Kavenegar.Core.KavenegarMessageSender; -namespace Test.Kavenegar.Core.KavenegarMessageSender; +namespace Test.Kavenegar.Core.KavenegarMessageSender.SingleMessage; [TestFixture] -public class SingleMessageSendToOneTests +public class SendToOneTests { [SetUp] public void SetUp() diff --git a/Test/Test.Kavenegar.Core/KavenegarMessageSender/VerifyLookup/VerifyLookupWithDto.cs b/Test/Test.Kavenegar.Core/KavenegarMessageSender/VerifyLookup/VerifyLookupWithDto.cs new file mode 100644 index 0000000..e43b291 --- /dev/null +++ b/Test/Test.Kavenegar.Core/KavenegarMessageSender/VerifyLookup/VerifyLookupWithDto.cs @@ -0,0 +1,550 @@ +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Kavenegar.Core.Dto.Message; +using Kavenegar.Core.Dto.Result; +using Kavenegar.Core.Enums; +using Moq; +using NUnit.Framework; +using Shared.Infrastructure; +using MessageSender = Kavenegar.Core.KavenegarMessageSender; + +namespace Test.Kavenegar.Core.KavenegarMessageSender.VerifyLookup; + +[TestFixture] +public class VerifyLookupWithDto +{ + [SetUp] + public void SetUp() + { + _mockHttpClientHelper = new Mock(); + _kavenegarMessageSender = new MessageSender(_mockHttpClientHelper.Object, ""); + } + + private MessageSender _kavenegarMessageSender = null!; + private Mock _mockHttpClientHelper = null!; + + [Test] + public async Task VerifyLookup_WhenCalled_CallsPostAsync() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + new VerifyLookupRequest( + "", + "", + "")); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + public async Task VerifyLookup_WhenCalled_CheckReceptorQueryParam() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + new VerifyLookupRequest( + "receptor", + "", + "")); + + Assert.That(passedQueryParams["receptor"], Is.EqualTo("receptor")); + } + + [Test] + public async Task VerifyLookup_WhenCalled_CheckTemplateQueryParam() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + new VerifyLookupRequest( + "", + "template", + "")); + + Assert.That(passedQueryParams["template"], Is.EqualTo("template")); + } + + [Test] + public async Task VerifyLookup_WhenCalled_CheckFirstTokenQueryParam() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + new VerifyLookupRequest( + "", + "", + "token")); + + Assert.That(passedQueryParams["token"], Is.EqualTo("token")); + } + + [Test] + public async Task VerifyLookup_WithNoSender_QueryParamsNotIncludeToken2() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + new VerifyLookupRequest( + "", + "", + "")); + + Assert.That(passedQueryParams.ContainsKey("token2"), Is.False); + } + + [Test] + public async Task VerifyLookup_WithSender_QueryParamsIncludeToken2() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + new VerifyLookupRequest( + "", + "", + "") + { + Token2 = "token2" + }); + + Assert.That(passedQueryParams["token2"], Is.EqualTo("token2")); + } + + [Test] + public async Task VerifyLookup_WithNoSender_QueryParamsNotIncludeToken3() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + new VerifyLookupRequest( + "", + "", + "")); + + Assert.That(passedQueryParams.ContainsKey("token3"), Is.False); + } + + [Test] + public async Task VerifyLookup_WithSender_QueryParamsIncludeToken3() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + new VerifyLookupRequest( + "", + "", + "") + { + Token3 = "token3" + }); + + Assert.That(passedQueryParams["token3"], Is.EqualTo("token3")); + } + + [Test] + public async Task VerifyLookup_WithNoSender_QueryParamsNotIncludeToken10() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + new VerifyLookupRequest( + "", + "", + "")); + + Assert.That(passedQueryParams.ContainsKey("token10"), Is.False); + } + + [Test] + public async Task VerifyLookup_WithSender_QueryParamsIncludeToken10() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + new VerifyLookupRequest( + "", + "", + "") + { + Token4 = "token10" + }); + + Assert.That(passedQueryParams["token10"], Is.EqualTo("token10")); + } + + [Test] + public async Task VerifyLookup_WithNoSender_QueryParamsNotIncludeToken20() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + new VerifyLookupRequest( + "", + "", + "")); + + Assert.That(passedQueryParams.ContainsKey("token20"), Is.False); + } + + [Test] + public async Task VerifyLookup_WithSender_QueryParamsIncludeToken20() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + new VerifyLookupRequest( + "", + "", + "") + { + Token5 = "token20" + }); + + Assert.That(passedQueryParams["token20"], Is.EqualTo("token20")); + } + + [Test] + public async Task VerifyLookup_WithNoSender_QueryParamsNotIncludeType() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + new VerifyLookupRequest( + "", + "", + "")); + + Assert.That(passedQueryParams.ContainsKey("type"), Is.False); + } + + [Test] + public async Task VerifyLookup_WithSender_QueryParamsIncludeType() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + new VerifyLookupRequest( + "", + "", + "") + { + VerifyLookupType = VerifyLookupType.Call + }); + + Assert.That(passedQueryParams["type"], Is.EqualTo((int)VerifyLookupType.Call)); + } + + [Test] + public async Task VerifyLookup_WhenCalled_ReturnsSendResult() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":[{}]}") + }); + + var result = await _kavenegarMessageSender.VerifyLookup( + new VerifyLookupRequest( + "", + "", + "")); + + Assert.That(result, Is.TypeOf()); + } +} \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/KavenegarMessageSender/VerifyLookup/VerifyLookupWithParam.cs b/Test/Test.Kavenegar.Core/KavenegarMessageSender/VerifyLookup/VerifyLookupWithParam.cs new file mode 100644 index 0000000..7f5a6da --- /dev/null +++ b/Test/Test.Kavenegar.Core/KavenegarMessageSender/VerifyLookup/VerifyLookupWithParam.cs @@ -0,0 +1,524 @@ +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Kavenegar.Core.Dto.Result; +using Kavenegar.Core.Enums; +using Moq; +using NUnit.Framework; +using Shared.Infrastructure; +using MessageSender = Kavenegar.Core.KavenegarMessageSender; + +namespace Test.Kavenegar.Core.KavenegarMessageSender.VerifyLookup; + +[TestFixture] +public class VerifyLookupWithParam +{ + [SetUp] + public void SetUp() + { + _mockHttpClientHelper = new Mock(); + _kavenegarMessageSender = new MessageSender(_mockHttpClientHelper.Object, ""); + } + + private MessageSender _kavenegarMessageSender = null!; + private Mock _mockHttpClientHelper = null!; + + [Test] + public async Task VerifyLookup_WhenCalled_CallsPostAsync() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + "", + "", + ""); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + public async Task VerifyLookup_WhenCalled_CheckReceptorQueryParam() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + "receptor", + "", + ""); + + Assert.That(passedQueryParams["receptor"], Is.EqualTo("receptor")); + } + + [Test] + public async Task VerifyLookup_WhenCalled_CheckTemplateQueryParam() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + "", + "template", + ""); + + Assert.That(passedQueryParams["template"], Is.EqualTo("template")); + } + + [Test] + public async Task VerifyLookup_WhenCalled_CheckFirstTokenQueryParam() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + "", + "", + "token"); + + Assert.That(passedQueryParams["token"], Is.EqualTo("token")); + } + + [Test] + public async Task VerifyLookup_WithNoSender_QueryParamsNotIncludeToken2() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + "", + "", + ""); + + Assert.That(passedQueryParams.ContainsKey("token2"), Is.False); + } + + [Test] + public async Task VerifyLookup_WithSender_QueryParamsIncludeToken2() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + "", + "", + "", + "token2"); + + Assert.That(passedQueryParams["token2"], Is.EqualTo("token2")); + } + + [Test] + public async Task VerifyLookup_WithNoSender_QueryParamsNotIncludeToken3() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + "", + "", + ""); + + Assert.That(passedQueryParams.ContainsKey("token3"), Is.False); + } + + [Test] + public async Task VerifyLookup_WithSender_QueryParamsIncludeToken3() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + "", + "", + "", + token3: "token3"); + + Assert.That(passedQueryParams["token3"], Is.EqualTo("token3")); + } + + [Test] + public async Task VerifyLookup_WithNoSender_QueryParamsNotIncludeToken10() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + "", + "", + ""); + + Assert.That(passedQueryParams.ContainsKey("token10"), Is.False); + } + + [Test] + public async Task VerifyLookup_WithSender_QueryParamsIncludeToken10() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + "", + "", + "", + token4: "token10"); + + Assert.That(passedQueryParams["token10"], Is.EqualTo("token10")); + } + + [Test] + public async Task VerifyLookup_WithNoSender_QueryParamsNotIncludeToken20() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + "", + "", + ""); + + Assert.That(passedQueryParams.ContainsKey("token20"), Is.False); + } + + [Test] + public async Task VerifyLookup_WithSender_QueryParamsIncludeToken20() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + "", + "", + "", + token5: "token20"); + + Assert.That(passedQueryParams["token20"], Is.EqualTo("token20")); + } + + [Test] + public async Task VerifyLookup_WithNoSender_QueryParamsNotIncludeType() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + "", + "", + ""); + + Assert.That(passedQueryParams.ContainsKey("type"), Is.False); + } + + [Test] + public async Task VerifyLookup_WithSender_QueryParamsIncludeType() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarMessageSender.VerifyLookup( + "", + "", + "", + type: VerifyLookupType.Call); + + Assert.That(passedQueryParams["type"], Is.EqualTo((int)VerifyLookupType.Call)); + } + + [Test] + public async Task VerifyLookup_WhenCalled_ReturnsSendResult() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "verify/lookup.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":[{}]}") + }); + + var result = await _kavenegarMessageSender.VerifyLookup( + "", + "", + ""); + + Assert.That(result, Is.TypeOf()); + } +} \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/Test.Kavenegar.Core.csproj b/Test/Test.Kavenegar.Core/Test.Kavenegar.Core.csproj index 58ab01c..e3d8042 100644 --- a/Test/Test.Kavenegar.Core/Test.Kavenegar.Core.csproj +++ b/Test/Test.Kavenegar.Core/Test.Kavenegar.Core.csproj @@ -8,15 +8,15 @@ - - - - - + + + + + - + From b0669e7225e102358644a6d36a153c8f6200fd00 Mon Sep 17 00:00:00 2001 From: alireza995 <88311706+alireza995@users.noreply.github.com> Date: Wed, 14 Dec 2022 01:29:05 +0330 Subject: [PATCH 10/14] test(Solution) : Test kavenegarprofile and shared project Test kavenegarprofile and shared project closes nothing --- Code/Kavenegar.Core/DependencyManager.cs | 23 +- Code/Kavenegar.Core/IKavenegarProfileApi.cs | 33 +- Code/Kavenegar.Core/Kavenegar.Core.csproj | 22 +- Code/Kavenegar.Core/KavenegarMessageSender.cs | 11 +- Code/Kavenegar.Core/KavenegarProfileApi.cs | 112 ++--- .../Shared.Infrastructure/DateHelper.cs | 6 - .../Shared.Infrastructure/HttpClientHelper.cs | 23 +- .../Shared.Infrastructure/JsonUtility.cs | 3 +- .../Shared.Infrastructure/QueryParamHelper.cs | 23 +- .../Shared.Infrastructure.csproj | 2 +- Kavenegar.sln | 7 + Kavenegar.sln.DotSettings | 4 + .../DependencyManagerTests.cs | 82 ++++ .../MultiMessage/SendWithDtoTests.cs | 9 +- .../MultiMessage/SendWithParamsTests.cs | 15 +- .../VerifyLookup/VerifyLookupWithDto.cs | 20 +- .../KavenegarProfileApi/AccountConfig.cs | 426 ++++++++++++++++++ .../KavenegarProfileApi/AccountInfo.cs | 70 +++ .../KavenegarProfileApi/Cancel.cs | 196 ++++++++ .../KavenegarProfileApi/CountInbox.cs | 367 +++++++++++++++ .../KavenegarProfileApi/CountOutbox.cs | 275 +++++++++++ .../KavenegarProfileApi/LatestOutbox.cs | 186 ++++++++ .../KavenegarProfileApi/Receive.cs | 163 +++++++ .../KavenegarProfileApi/Select.cs | 196 ++++++++ .../KavenegarProfileApi/SelectOutbox.cs | 278 ++++++++++++ .../KavenegarProfileApi/Status.cs | 196 ++++++++ .../StatusLocalMessageId.cs | 196 ++++++++ .../Test.Kavenegar.Core.csproj | 13 +- .../DateHelperTests.cs | 47 ++ .../HttpClientHelperTests.cs | 62 +++ .../JsonUtilityTests.cs | 31 ++ .../QueryParamHelperTests.cs | 24 + .../StringUtilityTests.cs | 108 +++++ .../Test.Shared.Infrastructure.csproj | 24 + 34 files changed, 3099 insertions(+), 154 deletions(-) create mode 100644 Test/Test.Kavenegar.Core/DependencyManagerTests.cs create mode 100644 Test/Test.Kavenegar.Core/KavenegarProfileApi/AccountConfig.cs create mode 100644 Test/Test.Kavenegar.Core/KavenegarProfileApi/AccountInfo.cs create mode 100644 Test/Test.Kavenegar.Core/KavenegarProfileApi/Cancel.cs create mode 100644 Test/Test.Kavenegar.Core/KavenegarProfileApi/CountInbox.cs create mode 100644 Test/Test.Kavenegar.Core/KavenegarProfileApi/CountOutbox.cs create mode 100644 Test/Test.Kavenegar.Core/KavenegarProfileApi/LatestOutbox.cs create mode 100644 Test/Test.Kavenegar.Core/KavenegarProfileApi/Receive.cs create mode 100644 Test/Test.Kavenegar.Core/KavenegarProfileApi/Select.cs create mode 100644 Test/Test.Kavenegar.Core/KavenegarProfileApi/SelectOutbox.cs create mode 100644 Test/Test.Kavenegar.Core/KavenegarProfileApi/Status.cs create mode 100644 Test/Test.Kavenegar.Core/KavenegarProfileApi/StatusLocalMessageId.cs create mode 100644 Test/Test.Shared.Infrastructure/DateHelperTests.cs create mode 100644 Test/Test.Shared.Infrastructure/HttpClientHelperTests.cs create mode 100644 Test/Test.Shared.Infrastructure/JsonUtilityTests.cs create mode 100644 Test/Test.Shared.Infrastructure/QueryParamHelperTests.cs create mode 100644 Test/Test.Shared.Infrastructure/StringUtilityTests.cs create mode 100644 Test/Test.Shared.Infrastructure/Test.Shared.Infrastructure.csproj diff --git a/Code/Kavenegar.Core/DependencyManager.cs b/Code/Kavenegar.Core/DependencyManager.cs index 8e87a0f..8a71252 100644 --- a/Code/Kavenegar.Core/DependencyManager.cs +++ b/Code/Kavenegar.Core/DependencyManager.cs @@ -9,14 +9,19 @@ public static IServiceCollection AddKavenegar( this IServiceCollection serviceCollection, string apiKey) { - return serviceCollection.AddScoped() - .AddScoped( - serviceProvider => new KavenegarProfileApi( - serviceProvider.GetRequiredService(), - apiKey)) - .AddScoped( - serviceProvider => new KavenegarMessageSender( - serviceProvider.GetRequiredService(), - apiKey)); + serviceCollection.AddScoped(); + serviceCollection.AddScoped(); + + serviceCollection.AddScoped( + serviceProvider => new KavenegarProfileApi( + serviceProvider.GetRequiredService(), + apiKey)); + + serviceCollection.AddScoped( + serviceProvider => new KavenegarMessageSender( + serviceProvider.GetRequiredService(), + apiKey)); + + return serviceCollection; } } \ No newline at end of file diff --git a/Code/Kavenegar.Core/IKavenegarProfileApi.cs b/Code/Kavenegar.Core/IKavenegarProfileApi.cs index bf54d6a..c2e78a1 100644 --- a/Code/Kavenegar.Core/IKavenegarProfileApi.cs +++ b/Code/Kavenegar.Core/IKavenegarProfileApi.cs @@ -1,4 +1,5 @@ using Kavenegar.Core.Dto.Result; +using Kavenegar.Core.Enums; namespace Kavenegar.Core; @@ -9,7 +10,7 @@ public interface IKavenegarProfileApi CancellationToken cancellationToken = default); Task?> Status( - List messageIds, + IEnumerable messageIds, CancellationToken cancellationToken = default); Task StatusLocalMessageId( @@ -17,7 +18,7 @@ public interface IKavenegarProfileApi CancellationToken cancellationToken = default); Task?> StatusLocalMessageId( - List messageIds, + IEnumerable messageIds, CancellationToken cancellationToken = default); Task Select( @@ -25,24 +26,24 @@ public interface IKavenegarProfileApi CancellationToken cancellationToken = default); Task?> Select( - List messageIds, + IEnumerable messageIds, CancellationToken cancellationToken = default); Task?> SelectOutbox( DateTime startDate, - DateTime? endDate, - string? sender, + DateTime? endDate = null, + string? sender = null, CancellationToken cancellationToken = default); Task?> LatestOutbox( - long? pageSize, - string? sender, + int? pageSize = null, + string? sender = null, CancellationToken cancellationToken = default); Task CountOutbox( DateTime startDate, - DateTime? endDate, - int? status, + DateTime? endDate = null, + MessageStatus? status = null, CancellationToken cancellationToken = default); Task Cancel( @@ -50,7 +51,7 @@ public interface IKavenegarProfileApi CancellationToken cancellationToken = default); Task?> Cancel( - List ids, + IEnumerable ids, CancellationToken cancellationToken = default); Task?> Receive( @@ -69,11 +70,11 @@ public interface IKavenegarProfileApi CancellationToken cancellationToken = default); Task AccountConfig( - string apiLogs, - string dailyReport, - string debugMode, - string defaultSender, - int? minCreditAlarm, - string resendFailed, + string? apiLogs = null, + string? dailyReport = null, + string? debugMode = null, + string? defaultSender = null, + int? minCreditAlarm = null, + string? resendFailed = null, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Code/Kavenegar.Core/Kavenegar.Core.csproj b/Code/Kavenegar.Core/Kavenegar.Core.csproj index 672080c..28afc84 100644 --- a/Code/Kavenegar.Core/Kavenegar.Core.csproj +++ b/Code/Kavenegar.Core/Kavenegar.Core.csproj @@ -1,17 +1,33 @@ - net6.0 + 1.1.0 enable enable + A cross-platform library for the kavenegar sms provider; written in C# + Kavenegar.Core + Kavenegar.Core + Kavenegar.Core + KavenegarDotNetCore + Kavenegar Core kavenegar.Core kavenegarCore Sms + https://github.com/kavenegar/Kavenegar.Core + Library + true + true + MohamadAminSayedBagheri HadiEskandari Ardavan HosseinRezaei Mberneti MohammadAmirriazi + git + https://github.com/kavenegar/Kavenegar.Core + Kavenegar + true + net6.0;net6.0-windows - + - + diff --git a/Code/Kavenegar.Core/KavenegarMessageSender.cs b/Code/Kavenegar.Core/KavenegarMessageSender.cs index f9252e4..94a540d 100644 --- a/Code/Kavenegar.Core/KavenegarMessageSender.cs +++ b/Code/Kavenegar.Core/KavenegarMessageSender.cs @@ -155,18 +155,15 @@ public KavenegarMessageSender( messages.SendMessageInfos .Select(sendMessageInfo => WebUtility.HtmlEncode(sendMessageInfo.MessageInfo.Message)) .ToList() - .Serialize(cancellationToken) + .Serialize() }, { "receptor", - messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.Receptor) - .ToList() - .Serialize(cancellationToken) + messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.Receptor).ToList().Serialize() }, { "type", - messages.SendMessageInfos.Select(sendMessageInfo => (int)sendMessageInfo.MessageInfo.Type) - .Serialize(cancellationToken) + messages.SendMessageInfos.Select(sendMessageInfo => (int)sendMessageInfo.MessageInfo.Type).Serialize() }, { "date", messages.Date == DateTime.MinValue ? 0 : messages.Date.ToUnixTimestamp() @@ -179,7 +176,7 @@ public KavenegarMessageSender( "sender", messages.SendMessageInfos.Select(sendMessageInfo => sendMessageInfo.MessageInfo.Sender) .ToList() - .Serialize(cancellationToken)); + .Serialize()); if (messages.SendMessageInfos.All( sendMessageInfo => !string.IsNullOrWhiteSpace(sendMessageInfo.LocalMessageId))) diff --git a/Code/Kavenegar.Core/KavenegarProfileApi.cs b/Code/Kavenegar.Core/KavenegarProfileApi.cs index d016e0e..cb6c0a9 100644 --- a/Code/Kavenegar.Core/KavenegarProfileApi.cs +++ b/Code/Kavenegar.Core/KavenegarProfileApi.cs @@ -1,4 +1,5 @@ using Kavenegar.Core.Dto.Result; +using Kavenegar.Core.Enums; using Shared.Infrastructure; namespace Kavenegar.Core; @@ -26,7 +27,7 @@ public KavenegarProfileApi( } public async Task?> Status( - List messageIds, + IEnumerable messageIds, CancellationToken cancellationToken = default) { var queryParams = new Dictionary @@ -56,7 +57,7 @@ public KavenegarProfileApi( } public async Task?> StatusLocalMessageId( - List messageIds, + IEnumerable messageIds, CancellationToken cancellationToken = default) { var queryParams = new Dictionary @@ -86,7 +87,7 @@ public KavenegarProfileApi( } public async Task?> Select( - List messageIds, + IEnumerable messageIds, CancellationToken cancellationToken = default) { var queryParams = new Dictionary @@ -105,18 +106,12 @@ public KavenegarProfileApi( public async Task?> SelectOutbox( DateTime startDate, - DateTime? endDate, - string? sender, + DateTime? endDate = null, + string? sender = null, CancellationToken cancellationToken = default) { - if (endDate <= startDate) throw new ArgumentException("تاریخ پایان باید از تاریخ شروع بزرگتر باشد."); - - if ((endDate - startDate)!.Value.TotalDays > 1) - throw new ArgumentException( - "حداکثر فاصله زمانی بین متغیر startDate تا متغیر endDate برابر با 1 روز می باشد."); - - if (startDate < DateTime.Now.AddDays(-60)) - throw new ArgumentException("تاریخ شروع startDate حداکثر باید تا 60 روز قبل باشد."); + var error = ValidateDatePeriod(startDate, endDate); + if (error.IsNotNullOrWhiteSpace()) throw new ArgumentException(error); var queryParams = new Dictionary { @@ -126,7 +121,7 @@ public KavenegarProfileApi( }; if (endDate.HasValue) queryParams.Add("enddate", endDate.Value.ToUnixTimestamp()); - if (string.IsNullOrWhiteSpace(sender)) queryParams.Add("sender", sender); + if (sender.IsNotNullOrWhiteSpace()) queryParams.Add("sender", sender); return await RequestSender>( "sms/selectoutbox.json", @@ -136,8 +131,8 @@ public KavenegarProfileApi( } public async Task?> LatestOutbox( - long? pageSize, - string? sender, + int? pageSize = null, + string? sender = null, CancellationToken cancellationToken = default) { if (pageSize is > 500) throw new ArgumentException("تعداد رکورد های خروجی این متد حداکثر 500 رکورد می‌باشد."); @@ -151,7 +146,7 @@ public KavenegarProfileApi( } }; - if (string.IsNullOrWhiteSpace(sender)) queryParams.Add("sender", sender); + if (sender.IsNotNullOrWhiteSpace()) queryParams.Add("sender", sender); return await RequestSender>( "sms/latestoutbox.json", @@ -162,18 +157,12 @@ public KavenegarProfileApi( public async Task CountOutbox( DateTime startDate, - DateTime? endDate, - int? status, + DateTime? endDate = null, + MessageStatus? status = null, CancellationToken cancellationToken = default) { - if (endDate <= startDate) throw new ArgumentException("تاریخ پایان باید از تاریخ شروع بزرگتر باشد."); - - if ((endDate - startDate)!.Value.TotalDays > 1) - throw new ArgumentException( - "حداکثر فاصله زمانی بین متغیر startdate تا متغیر endDate برابر با 1 روز می باشد."); - - if (startDate < DateTime.Now.AddDays(-60)) - throw new ArgumentException("تاریخ شروع startdate حداکثر باید تا 60 روز قبل باشد."); + var error = ValidateDatePeriod(startDate, endDate); + if (error.IsNotNullOrWhiteSpace()) throw new ArgumentException(error); var queryParams = new Dictionary { @@ -183,7 +172,7 @@ public KavenegarProfileApi( }; if (endDate.HasValue) queryParams.Add("enddate", endDate.Value.ToUnixTimestamp()); - if (status.HasValue) queryParams.Add("status", status); + if (status.HasValue) queryParams.Add("status", (int)status); return (await RequestSender>( "sms/countoutbox.json", @@ -205,7 +194,7 @@ public KavenegarProfileApi( } public async Task?> Cancel( - List ids, + IEnumerable ids, CancellationToken cancellationToken = default) { var queryParams = new Dictionary @@ -245,19 +234,13 @@ public KavenegarProfileApi( public async Task CountInbox( DateTime startDate, - DateTime? endDate, - string? lineNumber, - bool? isRead, + DateTime? endDate = null, + string? lineNumber = null, + bool? isRead = null, CancellationToken cancellationToken = default) { - if (endDate <= startDate) throw new ArgumentException("تاریخ پایان باید از تاریخ شروع بزرگتر باشد."); - - if ((endDate - startDate)!.Value.TotalDays > 1) - throw new ArgumentException( - "حداکثر فاصله زمانی بین متغیر startdate تا متغیر endDate برابر با 1 روز می باشد."); - - if (startDate < DateTime.Now.AddDays(-60)) - throw new ArgumentException("تاریخ شروع startdate حداکثر باید تا 60 روز قبل باشد."); + var error = ValidateDatePeriod(startDate, endDate); + if (error.IsNotNullOrWhiteSpace()) throw new ArgumentException(error); var queryParams = new Dictionary { @@ -267,7 +250,7 @@ public KavenegarProfileApi( }; if (endDate.HasValue) queryParams.Add("enddate", endDate.Value.ToUnixTimestamp()); - if (string.IsNullOrWhiteSpace(lineNumber)) queryParams.Add("linenumber", lineNumber); + if (lineNumber.IsNotNullOrWhiteSpace()) queryParams.Add("linenumber", lineNumber); if (isRead.HasValue) queryParams.Add("isread", isRead.Value ? 1 : 0); return (await RequestSender>( @@ -288,22 +271,30 @@ public KavenegarProfileApi( } public async Task AccountConfig( - string? apiLogs, - string? dailyReport, - string? debugMode, - string? defaultSender, - int? minCreditAlarm, - string? resendFailed, + string? apiLogs = null, + string? dailyReport = null, + string? debugMode = null, + string? defaultSender = null, + int? minCreditAlarm = null, + string? resendFailed = null, CancellationToken cancellationToken = default) { + if (apiLogs.IsNullOrWhiteSpace() && + dailyReport.IsNullOrWhiteSpace() && + debugMode.IsNullOrWhiteSpace() && + defaultSender.IsNullOrWhiteSpace() && + !minCreditAlarm.HasValue && + resendFailed.IsNullOrWhiteSpace()) + throw new ArgumentException("حداقل یکی از مقادیر باید وارد شده باشند."); + var queryParams = new Dictionary(); - if (string.IsNullOrWhiteSpace(apiLogs)) queryParams.Add("apilogs", apiLogs); - if (string.IsNullOrWhiteSpace(dailyReport)) queryParams.Add("dailyreport", dailyReport); - if (string.IsNullOrWhiteSpace(debugMode)) queryParams.Add("debugmode", debugMode); - if (string.IsNullOrWhiteSpace(defaultSender)) queryParams.Add("defaultsender", defaultSender); - queryParams.Add("mincreditalarm", minCreditAlarm); - if (string.IsNullOrWhiteSpace(resendFailed)) queryParams.Add("resendfailed", resendFailed); + if (apiLogs.IsNotNullOrWhiteSpace()) queryParams.Add("apilogs", apiLogs); + if (dailyReport.IsNotNullOrWhiteSpace()) queryParams.Add("dailyreport", dailyReport); + if (debugMode.IsNotNullOrWhiteSpace()) queryParams.Add("debugmode", debugMode); + if (defaultSender.IsNotNullOrWhiteSpace()) queryParams.Add("defaultsender", defaultSender); + if (minCreditAlarm.HasValue) queryParams.Add("mincreditalarm", minCreditAlarm); + if (resendFailed.IsNotNullOrWhiteSpace()) queryParams.Add("resendfailed", resendFailed); return await RequestSender( "account/config.json", @@ -311,4 +302,19 @@ public KavenegarProfileApi( queryParams, cancellationToken); } + + private string ValidateDatePeriod( + DateTime startDate, + DateTime? endDate = null) + { + if (startDate < DateTime.Now.AddDays(-60)) return "تاریخ شروع startDate حداکثر باید تا 60 روز قبل باشد."; + + if (endDate <= startDate) return "تاریخ پایان باید از تاریخ شروع بزرگتر باشد."; + + if (endDate.HasValue && + (endDate - startDate).Value.TotalDays > 1) + return "حداکثر فاصله زمانی بین متغیر startDate تا متغیر endDate برابر با 1 روز می باشد."; + + return string.Empty; + } } \ No newline at end of file diff --git a/Code/Shared/Shared.Infrastructure/DateHelper.cs b/Code/Shared/Shared.Infrastructure/DateHelper.cs index 686df89..e22e768 100644 --- a/Code/Shared/Shared.Infrastructure/DateHelper.cs +++ b/Code/Shared/Shared.Infrastructure/DateHelper.cs @@ -18,12 +18,6 @@ public static DateTime ToDateTime( return MinUnixDateTime.AddSeconds(unixTimeStamp); } - public static DateTime ToDateTime( - this double unixTimeStamp) - { - return MinUnixDateTime.AddSeconds(unixTimeStamp); - } - public static double ToUnixTimestamp( this DateTime dt) { diff --git a/Code/Shared/Shared.Infrastructure/HttpClientHelper.cs b/Code/Shared/Shared.Infrastructure/HttpClientHelper.cs index 156017a..8520003 100644 --- a/Code/Shared/Shared.Infrastructure/HttpClientHelper.cs +++ b/Code/Shared/Shared.Infrastructure/HttpClientHelper.cs @@ -2,9 +2,15 @@ public class HttpClientHelper : IHttpClientHelper { - private readonly HttpClient _httpClient = new(); + private readonly HttpClient _httpClient; - public string BaseAddress { get; set; } = null!; + public HttpClientHelper( + HttpClient httpClient) + { + _httpClient = httpClient; + } + + public string BaseAddress { get; set; } = ""; public async Task PostAsync( string requestUri, @@ -13,19 +19,12 @@ public async Task PostAsync( CancellationToken cancellationToken = default) { var address = queryParams == null ? - Path.Combine(BaseAddress, requestUri) : - QueryParamHelper.AddQueryParamToUri(Path.Combine(BaseAddress, requestUri), queryParams); + $"{BaseAddress}/{requestUri}" : + QueryParamHelper.AddQueryParamToUri($"{BaseAddress}/{requestUri}", queryParams); return await _httpClient.PostAsync( address, - body == null ? null : SerializeBody(body, cancellationToken), + body == null ? null : new StringContent(body.Serialize()), cancellationToken); } - - private StringContent SerializeBody( - object obj, - CancellationToken cancellationToken) - { - return new StringContent(obj.Serialize(cancellationToken)); - } } \ No newline at end of file diff --git a/Code/Shared/Shared.Infrastructure/JsonUtility.cs b/Code/Shared/Shared.Infrastructure/JsonUtility.cs index 80cddd0..c6706b1 100644 --- a/Code/Shared/Shared.Infrastructure/JsonUtility.cs +++ b/Code/Shared/Shared.Infrastructure/JsonUtility.cs @@ -5,8 +5,7 @@ namespace Shared.Infrastructure; public static class JsonUtility { public static string Serialize( - this T obj, - CancellationToken cancellationToken = default) + this T obj) { return JsonSerializer.Serialize(obj, obj!.GetType()); } diff --git a/Code/Shared/Shared.Infrastructure/QueryParamHelper.cs b/Code/Shared/Shared.Infrastructure/QueryParamHelper.cs index eed186a..1934bb3 100644 --- a/Code/Shared/Shared.Infrastructure/QueryParamHelper.cs +++ b/Code/Shared/Shared.Infrastructure/QueryParamHelper.cs @@ -1,5 +1,4 @@ -using System.ComponentModel.DataAnnotations.Schema; -using System.Web; +using System.Web; namespace Shared.Infrastructure; @@ -7,29 +6,13 @@ public static class QueryParamHelper { public static string AddQueryParamToUri( string requestUri, - Dictionary queryParams = null!) + Dictionary queryParams) { var uriBuilder = new UriBuilder(requestUri); var queryString = HttpUtility.ParseQueryString(uriBuilder.Query); foreach (var parameter in queryParams) queryString[parameter.Key] = parameter.Value?.ToString(); uriBuilder.Query = queryString.ToString(); - return uriBuilder.ToString(); - } - - public static Dictionary ParametrizeObject( - this T obj) - { - var properties = obj!.GetType() - .GetProperties() - .OrderBy( - propertyInfo => ((ColumnAttribute)propertyInfo.GetCustomAttributes(typeof(ColumnAttribute), false)[0]) - .Order); - - return properties.ToDictionary( - propertyInfo => - ((ColumnAttribute)propertyInfo.GetCustomAttributes(typeof(ColumnAttribute), false)[0]).Name ?? - propertyInfo.Name, - propertyInfo => propertyInfo.GetValue(obj)); + return uriBuilder.Uri.AbsoluteUri; } } \ No newline at end of file diff --git a/Code/Shared/Shared.Infrastructure/Shared.Infrastructure.csproj b/Code/Shared/Shared.Infrastructure/Shared.Infrastructure.csproj index eb2460e..8277f69 100644 --- a/Code/Shared/Shared.Infrastructure/Shared.Infrastructure.csproj +++ b/Code/Shared/Shared.Infrastructure/Shared.Infrastructure.csproj @@ -1,9 +1,9 @@ - net6.0 enable enable + net6.0 diff --git a/Kavenegar.sln b/Kavenegar.sln index 7f88a4a..b9f0d75 100644 --- a/Kavenegar.sln +++ b/Kavenegar.sln @@ -10,6 +10,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{17B39BF3-C EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test.Kavenegar.Core", "Test\Test.Kavenegar.Core\Test.Kavenegar.Core.csproj", "{6E36B3F6-2B1D-4506-BA92-007AC00EF317}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test.Shared.Infrastructure", "Test\Test.Shared.Infrastructure\Test.Shared.Infrastructure.csproj", "{F7A2FE83-BE4B-4A9D-BEF5-A14FC8E05AFD}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -28,10 +30,15 @@ Global {6E36B3F6-2B1D-4506-BA92-007AC00EF317}.Debug|Any CPU.Build.0 = Debug|Any CPU {6E36B3F6-2B1D-4506-BA92-007AC00EF317}.Release|Any CPU.ActiveCfg = Release|Any CPU {6E36B3F6-2B1D-4506-BA92-007AC00EF317}.Release|Any CPU.Build.0 = Release|Any CPU + {F7A2FE83-BE4B-4A9D-BEF5-A14FC8E05AFD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F7A2FE83-BE4B-4A9D-BEF5-A14FC8E05AFD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F7A2FE83-BE4B-4A9D-BEF5-A14FC8E05AFD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F7A2FE83-BE4B-4A9D-BEF5-A14FC8E05AFD}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {35D0DBF6-25F0-4DEB-9BC8-D3C3B65933EB} = {67BC444E-84C9-493C-B776-55FE5D54D560} {5A102430-241D-46A1-A615-0149411194D5} = {67BC444E-84C9-493C-B776-55FE5D54D560} {6E36B3F6-2B1D-4506-BA92-007AC00EF317} = {17B39BF3-CC26-40C5-AEB0-87CA2D71B93E} + {F7A2FE83-BE4B-4A9D-BEF5-A14FC8E05AFD} = {17B39BF3-CC26-40C5-AEB0-87CA2D71B93E} EndGlobalSection EndGlobal diff --git a/Kavenegar.sln.DotSettings b/Kavenegar.sln.DotSettings index 17fefcb..cc70dac 100644 --- a/Kavenegar.sln.DotSettings +++ b/Kavenegar.sln.DotSettings @@ -21,11 +21,13 @@ True True True + True True True True True True + True True True True @@ -33,4 +35,6 @@ True True True + True + True True \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/DependencyManagerTests.cs b/Test/Test.Kavenegar.Core/DependencyManagerTests.cs new file mode 100644 index 0000000..f816321 --- /dev/null +++ b/Test/Test.Kavenegar.Core/DependencyManagerTests.cs @@ -0,0 +1,82 @@ +using System.Linq; +using System.Net.Http; +using Kavenegar.Core; +using Microsoft.Extensions.DependencyInjection; +using NUnit.Framework; +using Shared.Infrastructure; + +namespace Test.Kavenegar.Core; + +[TestFixture] +public class DependencyManagerTests +{ + [SetUp] + public void SetUp() + { + _serviceCollection = new ServiceCollection().AddKavenegar("apiKey"); + } + + private IServiceCollection _serviceCollection = null!; + + [Test] + public void AddKavenegar_WhenCalled_IKavenegarProfileApiServiceAdded() + { + var serviceExistence = _serviceCollection.Any( + i => i.Lifetime == ServiceLifetime.Scoped && + i.ServiceType == typeof(IKavenegarProfileApi) && + i.ImplementationFactory!.Method.ReturnType == typeof(global::Kavenegar.Core.KavenegarProfileApi)); + + Assert.That(serviceExistence, Is.True); + } + + [Test] + public void AddKavenegar_WhenCalled_IKavenegarMessageSenderServiceAdded() + { + var serviceExistence = _serviceCollection.Any( + i => i.Lifetime == ServiceLifetime.Scoped && + i.ServiceType == typeof(IKavenegarMessageSender) && + i.ImplementationFactory!.Method.ReturnType == typeof(global::Kavenegar.Core.KavenegarMessageSender)); + + Assert.That(serviceExistence, Is.True); + } + + [Test] + public void AddKavenegar_WhenCalled_IHttpClientHelperServiceAdded() + { + var serviceExistence = _serviceCollection.Any( + i => i.Lifetime == ServiceLifetime.Scoped && + i.ServiceType == typeof(IHttpClientHelper) && + i.ImplementationType == typeof(HttpClientHelper)); + + Assert.That(serviceExistence, Is.True); + } + + [Test] + public void AddKavenegar_WhenCalled_HttpClientServiceAdded() + { + var serviceExistence = _serviceCollection.Any( + i => i.Lifetime == ServiceLifetime.Scoped && + i.ServiceType == typeof(HttpClient) && + i.ImplementationType == typeof(HttpClient)); + + Assert.That(serviceExistence, Is.True); + } + + [Test] + public void AddKavenegar_WhenCalled_CheckBuiltServices() + { + var provider = _serviceCollection.BuildServiceProvider(); + + Assert.That( + provider.GetService(), + Is.TypeOf()); + + Assert.That( + provider.GetService(), + Is.TypeOf()); + + Assert.That(provider.GetService(), Is.TypeOf()); + + Assert.That(provider.GetService(), Is.TypeOf()); + } +} \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/KavenegarMessageSender/MultiMessage/SendWithDtoTests.cs b/Test/Test.Kavenegar.Core/KavenegarMessageSender/MultiMessage/SendWithDtoTests.cs index 7cad31d..bc90b1e 100644 --- a/Test/Test.Kavenegar.Core/KavenegarMessageSender/MultiMessage/SendWithDtoTests.cs +++ b/Test/Test.Kavenegar.Core/KavenegarMessageSender/MultiMessage/SendWithDtoTests.cs @@ -188,7 +188,8 @@ await _kavenegarMessageSender.Send( [Test] [TestCase("1")] [TestCase("2")] - public async Task Send_WhenCalled_CheckReceptorQueryParam(string receptor) + public async Task Send_WhenCalled_CheckReceptorQueryParam( + string receptor) { Dictionary passedQueryParams = null!; @@ -233,7 +234,8 @@ await _kavenegarMessageSender.Send( [Test] [TestCase(MessageType.Flash)] [TestCase(MessageType.AppMemory)] - public async Task Send_WhenCalled_CheckTypeQueryParam(MessageType messageType) + public async Task Send_WhenCalled_CheckTypeQueryParam( + MessageType messageType) { Dictionary passedQueryParams = null!; @@ -332,7 +334,8 @@ await _kavenegarMessageSender.Send( [Test] [TestCase("1")] [TestCase("2")] - public async Task Send_WithLocalMessageId_QueryParamsIncludeLocalMessageId(string localMessageId) + public async Task Send_WithLocalMessageId_QueryParamsIncludeLocalMessageId( + string localMessageId) { Dictionary passedQueryParams = null!; diff --git a/Test/Test.Kavenegar.Core/KavenegarMessageSender/MultiMessage/SendWithParamsTests.cs b/Test/Test.Kavenegar.Core/KavenegarMessageSender/MultiMessage/SendWithParamsTests.cs index 1ae4634..2a40091 100644 --- a/Test/Test.Kavenegar.Core/KavenegarMessageSender/MultiMessage/SendWithParamsTests.cs +++ b/Test/Test.Kavenegar.Core/KavenegarMessageSender/MultiMessage/SendWithParamsTests.cs @@ -84,7 +84,7 @@ await _kavenegarMessageSender.Send( new List { new(new MessageInfo(message), ""), - new(new MessageInfo(message), ""), + new(new MessageInfo(message), "") }); var expectedMessages = new List @@ -188,7 +188,8 @@ await _kavenegarMessageSender.Send( [Test] [TestCase("1")] [TestCase("2")] - public async Task Send_WhenCalled_CheckReceptorQueryParam(string receptor) + public async Task Send_WhenCalled_CheckReceptorQueryParam( + string receptor) { Dictionary passedQueryParams = null!; @@ -232,7 +233,8 @@ await _kavenegarMessageSender.Send( [Test] [TestCase(MessageType.Flash)] [TestCase(MessageType.AppMemory)] - public async Task Send_WhenCalled_CheckTypeQueryParam(MessageType messageType) + public async Task Send_WhenCalled_CheckTypeQueryParam( + MessageType messageType) { Dictionary passedQueryParams = null!; @@ -306,7 +308,7 @@ public async Task Send_WhenCalled_CheckDateQueryParam() }); var dt = DateTime.Now; - + await _kavenegarMessageSender.Send( new List { @@ -319,7 +321,7 @@ await _kavenegarMessageSender.Send( MessageInfo = new MessageInfo("") } }, - dateTime:dt); + dateTime: dt); Assert.That(passedQueryParams["date"], Is.EqualTo(dt.ToUnixTimestamp())); } @@ -327,7 +329,8 @@ await _kavenegarMessageSender.Send( [Test] [TestCase("1")] [TestCase("2")] - public async Task Send_WithLocalMessageId_QueryParamsIncludeLocalMessageId(string localMessageId) + public async Task Send_WithLocalMessageId_QueryParamsIncludeLocalMessageId( + string localMessageId) { Dictionary passedQueryParams = null!; diff --git a/Test/Test.Kavenegar.Core/KavenegarMessageSender/VerifyLookup/VerifyLookupWithDto.cs b/Test/Test.Kavenegar.Core/KavenegarMessageSender/VerifyLookup/VerifyLookupWithDto.cs index e43b291..66827bb 100644 --- a/Test/Test.Kavenegar.Core/KavenegarMessageSender/VerifyLookup/VerifyLookupWithDto.cs +++ b/Test/Test.Kavenegar.Core/KavenegarMessageSender/VerifyLookup/VerifyLookupWithDto.cs @@ -160,7 +160,7 @@ await _kavenegarMessageSender.VerifyLookup( } [Test] - public async Task VerifyLookup_WithNoSender_QueryParamsNotIncludeToken2() + public async Task VerifyLookup_WithNoToken2_QueryParamsNotIncludeToken2() { Dictionary passedQueryParams = null!; @@ -195,7 +195,7 @@ await _kavenegarMessageSender.VerifyLookup( } [Test] - public async Task VerifyLookup_WithSender_QueryParamsIncludeToken2() + public async Task VerifyLookup_WithToken2_QueryParamsIncludeToken2() { Dictionary passedQueryParams = null!; @@ -233,7 +233,7 @@ await _kavenegarMessageSender.VerifyLookup( } [Test] - public async Task VerifyLookup_WithNoSender_QueryParamsNotIncludeToken3() + public async Task VerifyLookup_WithNoToken3_QueryParamsNotIncludeToken3() { Dictionary passedQueryParams = null!; @@ -268,7 +268,7 @@ await _kavenegarMessageSender.VerifyLookup( } [Test] - public async Task VerifyLookup_WithSender_QueryParamsIncludeToken3() + public async Task VerifyLookup_WithToken3_QueryParamsIncludeToken3() { Dictionary passedQueryParams = null!; @@ -306,7 +306,7 @@ await _kavenegarMessageSender.VerifyLookup( } [Test] - public async Task VerifyLookup_WithNoSender_QueryParamsNotIncludeToken10() + public async Task VerifyLookup_WithNoToken4_QueryParamsNotIncludeToken10() { Dictionary passedQueryParams = null!; @@ -341,7 +341,7 @@ await _kavenegarMessageSender.VerifyLookup( } [Test] - public async Task VerifyLookup_WithSender_QueryParamsIncludeToken10() + public async Task VerifyLookup_WithToken4_QueryParamsIncludeToken10() { Dictionary passedQueryParams = null!; @@ -379,7 +379,7 @@ await _kavenegarMessageSender.VerifyLookup( } [Test] - public async Task VerifyLookup_WithNoSender_QueryParamsNotIncludeToken20() + public async Task VerifyLookup_WithNoToken5_QueryParamsNotIncludeToken20() { Dictionary passedQueryParams = null!; @@ -414,7 +414,7 @@ await _kavenegarMessageSender.VerifyLookup( } [Test] - public async Task VerifyLookup_WithSender_QueryParamsIncludeToken20() + public async Task VerifyLookup_WithToken5_QueryParamsIncludeToken20() { Dictionary passedQueryParams = null!; @@ -452,7 +452,7 @@ await _kavenegarMessageSender.VerifyLookup( } [Test] - public async Task VerifyLookup_WithNoSender_QueryParamsNotIncludeType() + public async Task VerifyLookup_WithNoType_QueryParamsNotIncludeType() { Dictionary passedQueryParams = null!; @@ -487,7 +487,7 @@ await _kavenegarMessageSender.VerifyLookup( } [Test] - public async Task VerifyLookup_WithSender_QueryParamsIncludeType() + public async Task VerifyLookup_WithType_QueryParamsIncludeType() { Dictionary passedQueryParams = null!; diff --git a/Test/Test.Kavenegar.Core/KavenegarProfileApi/AccountConfig.cs b/Test/Test.Kavenegar.Core/KavenegarProfileApi/AccountConfig.cs new file mode 100644 index 0000000..7caae3b --- /dev/null +++ b/Test/Test.Kavenegar.Core/KavenegarProfileApi/AccountConfig.cs @@ -0,0 +1,426 @@ +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Kavenegar.Core.Dto.Result; +using Moq; +using NUnit.Framework; +using Shared.Infrastructure; +using Profile = Kavenegar.Core.KavenegarProfileApi; + +namespace Test.Kavenegar.Core.KavenegarProfileApi; + +public class AccountConfig +{ + private Profile _kavenegarProfileApi = null!; + private Mock _mockHttpClientHelper = null!; + + [SetUp] + public void SetUp() + { + _mockHttpClientHelper = new Mock(); + _kavenegarProfileApi = new Profile(_mockHttpClientHelper.Object, ""); + } + + [Test] + public async Task AccountConfig_WithAtLeastOneArgumentPassed_ReturnsAccountConfigDto() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "account/config.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":{}}") + }); + + var result = await _kavenegarProfileApi.AccountConfig(dailyReport: "a"); + + Assert.That(result, Is.TypeOf()); + } + + [Test] + public void AccountConfig_NoSettingArgumentIsSet_ThrowsArgumentException() + { + Assert.That(async () => await _kavenegarProfileApi.AccountConfig(), Throws.ArgumentException); + } + + [Test] + public async Task AccountConfig_WithNoApiLogs_QueryParamsNotIncludeApiLogs() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "account/config.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.AccountConfig(dailyReport: "a"); + + Assert.That(passedQueryParams.ContainsKey("apilogs"), Is.False); + } + + [Test] + public async Task AccountConfig_WithApiLogs_QueryParamsIncludeApiLogs() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "account/config.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.AccountConfig("apilogs"); + + Assert.That(passedQueryParams["apilogs"], Is.EqualTo("apilogs")); + } + + [Test] + public async Task AccountConfig_WithNoDailyReport_QueryParamsNotIncludeDailyReport() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "account/config.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.AccountConfig("a"); + + Assert.That(passedQueryParams.ContainsKey("dailyreport"), Is.False); + } + + [Test] + public async Task AccountConfig_WithDailyReport_QueryParamsIncludeDailyReport() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "account/config.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.AccountConfig(dailyReport: "dailyreport"); + + Assert.That(passedQueryParams["dailyreport"], Is.EqualTo("dailyreport")); + } + + [Test] + public async Task AccountConfig_WithNoDebugMode_QueryParamsNotIncludeDebugMode() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "account/config.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.AccountConfig("a"); + + Assert.That(passedQueryParams.ContainsKey("debugmode"), Is.False); + } + + [Test] + public async Task AccountConfig_WithDebugMode_QueryParamsIncludeDebugMode() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "account/config.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.AccountConfig(debugMode: "debugmode"); + + Assert.That(passedQueryParams["debugmode"], Is.EqualTo("debugmode")); + } + + [Test] + public async Task AccountConfig_WithNoDefaultSender_QueryParamsNotIncludeDefaultSender() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "account/config.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.AccountConfig("a"); + + Assert.That(passedQueryParams.ContainsKey("defaultsender"), Is.False); + } + + [Test] + public async Task AccountConfig_WithDefaultSender_QueryParamsIncludeDefaultSender() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "account/config.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.AccountConfig(defaultSender: "defaultsender"); + + Assert.That(passedQueryParams["defaultsender"], Is.EqualTo("defaultsender")); + } + + [Test] + public async Task AccountConfig_WithNoMinCreditAlarm_QueryParamsNotIncludeMinCreditAlarm() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "account/config.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.AccountConfig("a"); + + Assert.That(passedQueryParams.ContainsKey("mincreditalarm"), Is.False); + } + + [Test] + [TestCase(1)] + [TestCase(10)] + [TestCase(100)] + public async Task AccountConfig_WithMinCreditAlarm_QueryParamsIncludeMinCreditAlarm( + int mincreditalarm) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "account/config.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.AccountConfig(minCreditAlarm: mincreditalarm); + + Assert.That(passedQueryParams["mincreditalarm"], Is.EqualTo(mincreditalarm)); + } + + [Test] + public async Task AccountConfig_WithNoResendFailed_QueryParamsNotIncludeResendFailed() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "account/config.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.AccountConfig("a"); + + Assert.That(passedQueryParams.ContainsKey("resendfailed"), Is.False); + } + + [Test] + public async Task AccountConfig_WithResendFailed_QueryParamsIncludeResendFailed() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "account/config.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.AccountConfig(resendFailed: "resendfailed"); + + Assert.That(passedQueryParams["resendfailed"], Is.EqualTo("resendfailed")); + } +} \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/KavenegarProfileApi/AccountInfo.cs b/Test/Test.Kavenegar.Core/KavenegarProfileApi/AccountInfo.cs new file mode 100644 index 0000000..b69c347 --- /dev/null +++ b/Test/Test.Kavenegar.Core/KavenegarProfileApi/AccountInfo.cs @@ -0,0 +1,70 @@ +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Kavenegar.Core.Dto.Result; +using Moq; +using NUnit.Framework; +using Shared.Infrastructure; +using Profile = Kavenegar.Core.KavenegarProfileApi; + +namespace Test.Kavenegar.Core.KavenegarProfileApi; + +[TestFixture] +public class AccountInfo +{ + [SetUp] + public void SetUp() + { + _mockHttpClientHelper = new Mock(); + _kavenegarProfileApi = new Profile(_mockHttpClientHelper.Object, ""); + } + + private Profile _kavenegarProfileApi = null!; + private Mock _mockHttpClientHelper = null!; + + [Test] + public async Task AccountInfo_WhenCalled_CallsPostAsync() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "account/info.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.AccountInfo(); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "account/info.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + public async Task AccountInfo_WhenCalled_ReturnsAccountInfoDto() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "account/info.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":{}}") + }); + + var result = await _kavenegarProfileApi.AccountInfo(); + + Assert.That(result, Is.TypeOf()); + } +} \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/KavenegarProfileApi/Cancel.cs b/Test/Test.Kavenegar.Core/KavenegarProfileApi/Cancel.cs new file mode 100644 index 0000000..e280da7 --- /dev/null +++ b/Test/Test.Kavenegar.Core/KavenegarProfileApi/Cancel.cs @@ -0,0 +1,196 @@ +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Kavenegar.Core.Dto.Result; +using Moq; +using NUnit.Framework; +using Shared.Infrastructure; +using Profile = Kavenegar.Core.KavenegarProfileApi; + +namespace Test.Kavenegar.Core.KavenegarProfileApi; + +[TestFixture] +public class Cancel +{ + [SetUp] + public void SetUp() + { + _mockHttpClientHelper = new Mock(); + _kavenegarProfileApi = new Profile(_mockHttpClientHelper.Object, ""); + } + + private Profile _kavenegarProfileApi = null!; + private Mock _mockHttpClientHelper = null!; + + [Test] + public async Task Cancel_SingleCalled_CallsPostAsync() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/cancel.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.Cancel("messageid"); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "sms/cancel.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + [TestCase("1")] + [TestCase("2")] + public async Task Cancel_SingleCalled_CheckMessageIdsQueryParam( + string messageId) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/cancel.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.Cancel(messageId); + + Assert.That(passedQueryParams["messageid"], Is.EqualTo(messageId)); + } + + [Test] + public async Task Cancel_SingleCalled_ReturnsStatusMessageDto() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/cancel.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":[{}]}") + }); + + var result = await _kavenegarProfileApi.Cancel(""); + + Assert.That(result, Is.TypeOf()); + } + + [Test] + public async Task Cancel_MultiCalled_CallsPostAsync() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/cancel.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.Cancel( + new List + { + "" + }); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "sms/cancel.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + [TestCase("1")] + [TestCase("2")] + public async Task Cancel_MultiCalled_CheckMessageIdsQueryParam( + string messageId) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/cancel.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.Cancel( + new List + { + messageId, + messageId + }); + + Assert.That(passedQueryParams["messageid"], Is.EqualTo($"{messageId},{messageId}")); + } + + [Test] + public async Task Cancel_MultiCalled_ReturnsStatusMessageDto() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/cancel.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":[{}]}") + }); + + var result = await _kavenegarProfileApi.Cancel( + new List + { + "" + }); + + Assert.That(result, Is.TypeOf>()); + } +} \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/KavenegarProfileApi/CountInbox.cs b/Test/Test.Kavenegar.Core/KavenegarProfileApi/CountInbox.cs new file mode 100644 index 0000000..e0ef2d7 --- /dev/null +++ b/Test/Test.Kavenegar.Core/KavenegarProfileApi/CountInbox.cs @@ -0,0 +1,367 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Kavenegar.Core.Dto.Result; +using Moq; +using NUnit.Framework; +using Shared.Infrastructure; +using Profile = Kavenegar.Core.KavenegarProfileApi; + +namespace Test.Kavenegar.Core.KavenegarProfileApi; + +public class CountInbox +{ + private Profile _kavenegarProfileApi = null!; + private Mock _mockHttpClientHelper = null!; + + [SetUp] + public void SetUp() + { + _mockHttpClientHelper = new Mock(); + _kavenegarProfileApi = new Profile(_mockHttpClientHelper.Object, ""); + } + + [Test] + public async Task CountInbox_WhenCalled_CallsPostAsync() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/countinbox.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.CountInbox(DateTime.Now); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "sms/countinbox.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + [TestCase(61)] + [TestCase(71)] + [TestCase(81)] + public void CountInbox_StartDate61DaysAgo_ThrowsArgumentException( + int daysAgo) + { + Assert.That( + async () => await _kavenegarProfileApi.CountInbox(DateTime.Now.AddDays(-1 * daysAgo)), + Throws.ArgumentException); + } + + [Test] + [TestCase(1)] + [TestCase(10)] + [TestCase(100)] + public void CountInbox_StartDateGreaterThanOrEqualEndDate_ThrowsArgumentException( + int secondsBeforeStartDate) + { + Assert.That( + async () => await _kavenegarProfileApi.CountInbox( + DateTime.Now, + DateTime.Now.AddSeconds(-1 * secondsBeforeStartDate)), + Throws.ArgumentException); + } + + [Test] + [TestCase(2)] + [TestCase(10)] + [TestCase(100)] + public void CountInbox_StartDateEndDateDifferenceMoreThan1Day_ThrowsArgumentException( + int daysBeforeStartDate) + { + Assert.That( + async () => await _kavenegarProfileApi.CountInbox(DateTime.Now, DateTime.Now.AddDays(daysBeforeStartDate)), + Throws.ArgumentException); + } + + [Test] + public async Task CountInbox_WhenCalled_CheckStartDateQueryParam() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/countinbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + var expectedStartDateTime = DateTime.Now; + + await _kavenegarProfileApi.CountInbox(expectedStartDateTime); + + Assert.That(passedQueryParams["startdate"], Is.EqualTo(expectedStartDateTime.ToUnixTimestamp())); + } + + [Test] + public async Task CountInbox_WithNoEndDate_QueryParamsNotIncludeEndDate() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/countinbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + var expectedStartDateTime = DateTime.Now; + + await _kavenegarProfileApi.CountInbox(expectedStartDateTime); + + Assert.That(passedQueryParams.ContainsKey("enddate"), Is.False); + } + + [Test] + public async Task CountInbox_WithEndDate_QueryParamsIncludeEndDate() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/countinbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + var expectedStartDateTime = DateTime.Now; + var expectedEndDateDateTime = expectedStartDateTime.AddHours(1); + + await _kavenegarProfileApi.CountInbox(expectedStartDateTime, expectedEndDateDateTime); + + Assert.That(passedQueryParams["enddate"], Is.EqualTo(expectedEndDateDateTime.ToUnixTimestamp())); + } + + [Test] + public async Task CountInbox_WithNoLineNumber_QueryParamsNotIncludeLineNumber() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/countinbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + var expectedStartDateTime = DateTime.Now; + + await _kavenegarProfileApi.CountInbox(expectedStartDateTime); + + Assert.That(passedQueryParams.ContainsKey("linenumber"), Is.False); + } + + [Test] + public async Task CountInbox_WithLineNumber_QueryParamsIncludeLineNumber() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/countinbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.CountInbox(DateTime.Now, lineNumber: "linenumber"); + + Assert.That(passedQueryParams["linenumber"], Is.EqualTo("linenumber")); + } + + [Test] + public async Task CountInbox_WithNoIsRead_QueryParamsNotIncludeIsRead() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/countinbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + var expectedStartDateTime = DateTime.Now; + + await _kavenegarProfileApi.CountInbox(expectedStartDateTime); + + Assert.That(passedQueryParams.ContainsKey("isread"), Is.False); + } + + [Test] + public async Task CountInbox_WithIsReadSetTrue_QueryParamsIsReadEqual1() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/countinbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.CountInbox(DateTime.Now, isRead: true); + + Assert.That(passedQueryParams["isread"], Is.EqualTo(1)); + } + + [Test] + public async Task CountInbox_WithIsReadSetFalse_QueryParamsIsReadEqual0() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/countinbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.CountInbox(DateTime.Now, isRead: false); + + Assert.That(passedQueryParams["isread"], Is.EqualTo(0)); + } + + [Test] + public async Task CountInbox_WhenCalled_ReturnsSendResultDtoList() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/countinbox.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":[{}]}") + }); + + var result = await _kavenegarProfileApi.CountInbox(DateTime.Now); + + Assert.That(result, Is.TypeOf()); + } +} \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/KavenegarProfileApi/CountOutbox.cs b/Test/Test.Kavenegar.Core/KavenegarProfileApi/CountOutbox.cs new file mode 100644 index 0000000..149fec3 --- /dev/null +++ b/Test/Test.Kavenegar.Core/KavenegarProfileApi/CountOutbox.cs @@ -0,0 +1,275 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Kavenegar.Core.Dto.Result; +using Kavenegar.Core.Enums; +using Moq; +using NUnit.Framework; +using Shared.Infrastructure; +using Profile = Kavenegar.Core.KavenegarProfileApi; + +namespace Test.Kavenegar.Core.KavenegarProfileApi; + +public class CountOutbox +{ + private Profile _kavenegarProfileApi = null!; + private Mock _mockHttpClientHelper = null!; + + [SetUp] + public void SetUp() + { + _mockHttpClientHelper = new Mock(); + _kavenegarProfileApi = new Profile(_mockHttpClientHelper.Object, ""); + } + + [Test] + public async Task CountOutbox_WhenCalled_CallsPostAsync() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/countoutbox.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.CountOutbox(DateTime.Now); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "sms/countoutbox.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + [TestCase(61)] + [TestCase(71)] + [TestCase(81)] + public void CountOutbox_StartDate61DaysAgo_ThrowsArgumentException( + int daysAgo) + { + Assert.That( + async () => await _kavenegarProfileApi.CountOutbox(DateTime.Now.AddDays(-1 * daysAgo)), + Throws.ArgumentException); + } + + [Test] + [TestCase(1)] + [TestCase(10)] + [TestCase(100)] + public void CountOutbox_StartDateGreaterThanOrEqualEndDate_ThrowsArgumentException( + int secondsBeforeStartDate) + { + Assert.That( + async () => await _kavenegarProfileApi.CountOutbox( + DateTime.Now, + DateTime.Now.AddSeconds(-1 * secondsBeforeStartDate)), + Throws.ArgumentException); + } + + [Test] + [TestCase(2)] + [TestCase(10)] + [TestCase(100)] + public void CountOutbox_StartDateEndDateDifferenceMoreThan1Day_ThrowsArgumentException( + int daysBeforeStartDate) + { + Assert.That( + async () => await _kavenegarProfileApi.CountOutbox(DateTime.Now, DateTime.Now.AddDays(daysBeforeStartDate)), + Throws.ArgumentException); + } + + [Test] + public async Task CountOutbox_WhenCalled_CheckStartDateQueryParam() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/countoutbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + var expectedStartDateTime = DateTime.Now; + + await _kavenegarProfileApi.CountOutbox(expectedStartDateTime); + + Assert.That(passedQueryParams["startdate"], Is.EqualTo(expectedStartDateTime.ToUnixTimestamp())); + } + + [Test] + public async Task CountOutbox_WithNoEndDate_QueryParamsNotIncludeEndDate() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/countoutbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + var expectedStartDateTime = DateTime.Now; + + await _kavenegarProfileApi.CountOutbox(expectedStartDateTime); + + Assert.That(passedQueryParams.ContainsKey("enddate"), Is.False); + } + + [Test] + public async Task CountOutbox_WithEndDate_QueryParamsIncludeEndDate() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/countoutbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + var expectedStartDateTime = DateTime.Now; + var expectedEndDateDateTime = expectedStartDateTime.AddHours(1); + + await _kavenegarProfileApi.CountOutbox(expectedStartDateTime, expectedEndDateDateTime); + + Assert.That(passedQueryParams["enddate"], Is.EqualTo(expectedEndDateDateTime.ToUnixTimestamp())); + } + + [Test] + public async Task CountOutbox_WithNoStatus_QueryParamsNotIncludeStatus() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/countoutbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + var expectedStartDateTime = DateTime.Now; + + await _kavenegarProfileApi.CountOutbox(expectedStartDateTime); + + Assert.That(passedQueryParams.ContainsKey("status"), Is.False); + } + + [Test] + public async Task CountOutbox_WithStatus_QueryParamsIncludeStatus() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/countoutbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + var expectedStartDateTime = DateTime.Now; + + await _kavenegarProfileApi.CountOutbox(expectedStartDateTime, status: MessageStatus.Canceled); + + Assert.That(passedQueryParams["status"], Is.EqualTo((int)MessageStatus.Canceled)); + } + + [Test] + public async Task CountOutbox_WhenCalled_ReturnsSendResultDtoList() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/countoutbox.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":[{}]}") + }); + + var result = await _kavenegarProfileApi.CountOutbox(DateTime.Now); + + Assert.That(result, Is.TypeOf()); + } +} \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/KavenegarProfileApi/LatestOutbox.cs b/Test/Test.Kavenegar.Core/KavenegarProfileApi/LatestOutbox.cs new file mode 100644 index 0000000..8f04e35 --- /dev/null +++ b/Test/Test.Kavenegar.Core/KavenegarProfileApi/LatestOutbox.cs @@ -0,0 +1,186 @@ +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Kavenegar.Core.Dto.Result; +using Moq; +using NUnit.Framework; +using Shared.Infrastructure; +using Profile = Kavenegar.Core.KavenegarProfileApi; + +namespace Test.Kavenegar.Core.KavenegarProfileApi; + +public class LatestOutbox +{ + private Profile _kavenegarProfileApi = null!; + private Mock _mockHttpClientHelper = null!; + + [SetUp] + public void SetUp() + { + _mockHttpClientHelper = new Mock(); + _kavenegarProfileApi = new Profile(_mockHttpClientHelper.Object, ""); + } + + [Test] + [TestCase(501)] + [TestCase(601)] + [TestCase(701)] + public void LatestOutbox_PageSizeLargerThan500_ThrowsArgumentException( + int pageSize) + { + Assert.That(async () => await _kavenegarProfileApi.LatestOutbox(501), Throws.ArgumentException); + } + + [Test] + public async Task LatestOutbox_NullPageSize_PageSizeIs500() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/latestoutbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.LatestOutbox(); + + Assert.That(passedQueryParams["pagesize"], Is.EqualTo(500)); + } + + [Test] + [TestCase(1)] + [TestCase(2)] + [TestCase(100)] + public async Task LatestOutbox_SetPageSize_CheckPageSizeQueryParam( + int pageSize) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/latestoutbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.LatestOutbox(pageSize); + + Assert.That(passedQueryParams["pagesize"], Is.EqualTo(pageSize)); + } + + [Test] + public async Task LatestOutbox_WithNoSender_QueryParamsNotIncludeSender() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/latestoutbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.LatestOutbox(); + + Assert.That(passedQueryParams.ContainsKey("sender"), Is.False); + } + + [Test] + [TestCase("a")] + [TestCase("b")] + [TestCase("c")] + public async Task LatestOutbox_WithSender_QueryParamsIncludeSender( + string sender) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/latestoutbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.LatestOutbox(sender: sender); + + Assert.That(passedQueryParams["sender"], Is.EqualTo(sender)); + } + + [Test] + public async Task LatestOutbox_WhenCalled_ReturnsSendResultDtoList() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/latestoutbox.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":[{}]}") + }); + + var result = await _kavenegarProfileApi.LatestOutbox(); + + Assert.That(result, Is.TypeOf>()); + } +} \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/KavenegarProfileApi/Receive.cs b/Test/Test.Kavenegar.Core/KavenegarProfileApi/Receive.cs new file mode 100644 index 0000000..543aab6 --- /dev/null +++ b/Test/Test.Kavenegar.Core/KavenegarProfileApi/Receive.cs @@ -0,0 +1,163 @@ +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Kavenegar.Core.Dto.Result; +using Moq; +using NUnit.Framework; +using Shared.Infrastructure; +using Profile = Kavenegar.Core.KavenegarProfileApi; + +namespace Test.Kavenegar.Core.KavenegarProfileApi; + +[TestFixture] +public class Receive +{ + [SetUp] + public void SetUp() + { + _mockHttpClientHelper = new Mock(); + _kavenegarProfileApi = new Profile(_mockHttpClientHelper.Object, ""); + } + + private Profile _kavenegarProfileApi = null!; + private Mock _mockHttpClientHelper = null!; + + [Test] + public async Task Receive_WhenCalled_CallsPostAsync() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/receive.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.Receive("line", false); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "sms/receive.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + public async Task Receive_WhenCalled_CheckLineNumberValueInQueryParam() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/receive.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.Receive("linenumber", false); + + Assert.That(passedQueryParams["linenumber"], Is.EqualTo("linenumber")); + } + + [Test] + public async Task Receive_IsReadSetFalse_CheckIsReadValueIs0() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/receive.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.Receive("", false); + + Assert.That(passedQueryParams["isread"], Is.EqualTo(0)); + } + + [Test] + public async Task Receive_IsReadSetTrue_CheckIsReadValueIs1() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/receive.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.Receive("", true); + + Assert.That(passedQueryParams["isread"], Is.EqualTo(1)); + } + + [Test] + public async Task Receive_WhenCalled_ReturnsReceivedMessageDtoList() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/receive.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":[{}]}") + }); + + var result = await _kavenegarProfileApi.Receive("", true); + + Assert.That(result, Is.TypeOf>()); + } +} \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/KavenegarProfileApi/Select.cs b/Test/Test.Kavenegar.Core/KavenegarProfileApi/Select.cs new file mode 100644 index 0000000..8f55eb4 --- /dev/null +++ b/Test/Test.Kavenegar.Core/KavenegarProfileApi/Select.cs @@ -0,0 +1,196 @@ +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Kavenegar.Core.Dto.Result; +using Moq; +using NUnit.Framework; +using Shared.Infrastructure; +using Profile = Kavenegar.Core.KavenegarProfileApi; + +namespace Test.Kavenegar.Core.KavenegarProfileApi; + +[TestFixture] +public class Select +{ + [SetUp] + public void SetUp() + { + _mockHttpClientHelper = new Mock(); + _kavenegarProfileApi = new Profile(_mockHttpClientHelper.Object, ""); + } + + private Profile _kavenegarProfileApi = null!; + private Mock _mockHttpClientHelper = null!; + + [Test] + public async Task Select_SingleCalled_CallsPostAsync() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/select.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.Select("messageid"); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "sms/select.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + [TestCase("1")] + [TestCase("2")] + public async Task Select_SingleCalled_CheckMessageIdsQueryParam( + string messageId) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/select.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.Select(messageId); + + Assert.That(passedQueryParams["messageid"], Is.EqualTo(messageId)); + } + + [Test] + public async Task Select_SingleCalled_ReturnsSendResultDto() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/select.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":[{}]}") + }); + + var result = await _kavenegarProfileApi.Select(""); + + Assert.That(result, Is.TypeOf()); + } + + [Test] + public async Task Select_MultiCalled_CallsPostAsync() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/select.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.Select( + new List + { + "" + }); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "sms/select.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + [TestCase("1")] + [TestCase("2")] + public async Task Select_MultiCalled_CheckMessageIdsQueryParam( + string messageId) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/select.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.Select( + new List + { + messageId, + messageId + }); + + Assert.That(passedQueryParams["messageid"], Is.EqualTo($"{messageId},{messageId}")); + } + + [Test] + public async Task Select_MultiCalled_ReturnsSendResultDto() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/select.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":[{}]}") + }); + + var result = await _kavenegarProfileApi.Select( + new List + { + "" + }); + + Assert.That(result, Is.TypeOf>()); + } +} \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/KavenegarProfileApi/SelectOutbox.cs b/Test/Test.Kavenegar.Core/KavenegarProfileApi/SelectOutbox.cs new file mode 100644 index 0000000..c9b1289 --- /dev/null +++ b/Test/Test.Kavenegar.Core/KavenegarProfileApi/SelectOutbox.cs @@ -0,0 +1,278 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Kavenegar.Core.Dto.Result; +using Moq; +using NUnit.Framework; +using Shared.Infrastructure; +using Profile = Kavenegar.Core.KavenegarProfileApi; + +namespace Test.Kavenegar.Core.KavenegarProfileApi; + +public class SelectOutbox +{ + private Profile _kavenegarProfileApi = null!; + private Mock _mockHttpClientHelper = null!; + + [SetUp] + public void SetUp() + { + _mockHttpClientHelper = new Mock(); + _kavenegarProfileApi = new Profile(_mockHttpClientHelper.Object, ""); + } + + [Test] + public async Task SelectOutbox_WhenCalled_ThrowsArgumentException() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/selectoutbox.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.SelectOutbox(DateTime.Now); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "sms/selectoutbox.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + [TestCase(61)] + [TestCase(71)] + [TestCase(81)] + public void SelectOutbox_StartDate61DaysAgo_ThrowsArgumentException( + int daysAgo) + { + Assert.That( + async () => await _kavenegarProfileApi.SelectOutbox(DateTime.Now.AddDays(-1 * daysAgo)), + Throws.ArgumentException); + } + + [Test] + [TestCase(1)] + [TestCase(10)] + [TestCase(100)] + public void SelectOutbox_StartDateGreaterThanOrEqualEndDate_ThrowsArgumentException( + int secondsBeforeStartDate) + { + Assert.That( + async () => await _kavenegarProfileApi.SelectOutbox( + DateTime.Now, + DateTime.Now.AddSeconds(-1 * secondsBeforeStartDate)), + Throws.ArgumentException); + } + + [Test] + [TestCase(2)] + [TestCase(10)] + [TestCase(100)] + public void SelectOutbox_StartDateEndDateDifferenceMoreThan1Day_ThrowsArgumentException( + int daysBeforeStartDate) + { + Assert.That( + async () => await _kavenegarProfileApi.SelectOutbox( + DateTime.Now, + DateTime.Now.AddDays(daysBeforeStartDate)), + Throws.ArgumentException); + } + + [Test] + public async Task SelectOutbox_WhenCalled_CheckStartDateQueryParam() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/selectoutbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + var expectedStartDateTime = DateTime.Now; + + await _kavenegarProfileApi.SelectOutbox(expectedStartDateTime); + + Assert.That(passedQueryParams["startdate"], Is.EqualTo(expectedStartDateTime.ToUnixTimestamp())); + } + + [Test] + public async Task SelectOutbox_WithNoEndDate_QueryParamsNotIncludeEndDate() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/selectoutbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + var expectedStartDateTime = DateTime.Now; + + await _kavenegarProfileApi.SelectOutbox(expectedStartDateTime); + + Assert.That(passedQueryParams.ContainsKey("enddate"), Is.False); + } + + [Test] + public async Task SelectOutbox_WithEndDate_QueryParamsIncludeEndDate() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/selectoutbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + var expectedStartDateTime = DateTime.Now; + var expectedEndDateDateTime = expectedStartDateTime.AddHours(1); + + await _kavenegarProfileApi.SelectOutbox(expectedStartDateTime, expectedEndDateDateTime); + + Assert.That(passedQueryParams["enddate"], Is.EqualTo(expectedEndDateDateTime.ToUnixTimestamp())); + } + + [Test] + public async Task SelectOutbox_WithNoSender_QueryParamsNotIncludeSender() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/selectoutbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + var expectedStartDateTime = DateTime.Now; + + await _kavenegarProfileApi.SelectOutbox(expectedStartDateTime); + + Assert.That(passedQueryParams.ContainsKey("sender"), Is.False); + } + + [Test] + public async Task SelectOutbox_WithSender_QueryParamsIncludeSender() + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/selectoutbox.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + var expectedStartDateTime = DateTime.Now; + + await _kavenegarProfileApi.SelectOutbox(expectedStartDateTime, sender: "sender"); + + Assert.That(passedQueryParams["sender"], Is.EqualTo("sender")); + } + + [Test] + public async Task SelectOutbox_WhenCalled_ReturnsSendResultDtoList() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/selectoutbox.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":[{}]}") + }); + + var expectedStartDateTime = DateTime.Now; + + var result = await _kavenegarProfileApi.SelectOutbox(expectedStartDateTime, sender: "sender"); + + Assert.That(result, Is.TypeOf>()); + } +} \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/KavenegarProfileApi/Status.cs b/Test/Test.Kavenegar.Core/KavenegarProfileApi/Status.cs new file mode 100644 index 0000000..4339c2e --- /dev/null +++ b/Test/Test.Kavenegar.Core/KavenegarProfileApi/Status.cs @@ -0,0 +1,196 @@ +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Kavenegar.Core.Dto.Result; +using Moq; +using NUnit.Framework; +using Shared.Infrastructure; +using Profile = Kavenegar.Core.KavenegarProfileApi; + +namespace Test.Kavenegar.Core.KavenegarProfileApi; + +[TestFixture] +public class Status +{ + [SetUp] + public void SetUp() + { + _mockHttpClientHelper = new Mock(); + _kavenegarProfileApi = new Profile(_mockHttpClientHelper.Object, ""); + } + + private Profile _kavenegarProfileApi = null!; + private Mock _mockHttpClientHelper = null!; + + [Test] + public async Task Status_SingleCalled_CallsPostAsync() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/status.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.Status("messageid"); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "sms/status.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + [TestCase("1")] + [TestCase("2")] + public async Task Status_SingleCalled_CheckMessageIdsQueryParam( + string messageId) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/status.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.Status(messageId); + + Assert.That(passedQueryParams["messageid"], Is.EqualTo(messageId)); + } + + [Test] + public async Task Status_SingleCalled_ReturnsStatusMessageDto() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/status.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":[{}]}") + }); + + var result = await _kavenegarProfileApi.Status(""); + + Assert.That(result, Is.TypeOf()); + } + + [Test] + public async Task Status_MultiCalled_CallsPostAsync() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/status.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.Status( + new List + { + "" + }); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "sms/status.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + [TestCase("1")] + [TestCase("2")] + public async Task Status_MultiCalled_CheckMessageIdsQueryParam( + string messageId) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/status.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.Status( + new List + { + messageId, + messageId + }); + + Assert.That(passedQueryParams["messageid"], Is.EqualTo($"{messageId},{messageId}")); + } + + [Test] + public async Task Status_MultiCalled_ReturnsStatusMessageDto() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/status.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":[{}]}") + }); + + var result = await _kavenegarProfileApi.Status( + new List + { + "" + }); + + Assert.That(result, Is.TypeOf>()); + } +} \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/KavenegarProfileApi/StatusLocalMessageId.cs b/Test/Test.Kavenegar.Core/KavenegarProfileApi/StatusLocalMessageId.cs new file mode 100644 index 0000000..5940091 --- /dev/null +++ b/Test/Test.Kavenegar.Core/KavenegarProfileApi/StatusLocalMessageId.cs @@ -0,0 +1,196 @@ +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Kavenegar.Core.Dto.Result; +using Moq; +using NUnit.Framework; +using Shared.Infrastructure; +using Profile = Kavenegar.Core.KavenegarProfileApi; + +namespace Test.Kavenegar.Core.KavenegarProfileApi; + +[TestFixture] +public class StatusLocalMessageId +{ + [SetUp] + public void SetUp() + { + _mockHttpClientHelper = new Mock(); + _kavenegarProfileApi = new Profile(_mockHttpClientHelper.Object, ""); + } + + private Profile _kavenegarProfileApi = null!; + private Mock _mockHttpClientHelper = null!; + + [Test] + public async Task StatusLocalMessageId_SingleCalled_CallsPostAsync() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/statuslocalmessageid.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.StatusLocalMessageId("messageid"); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "sms/statuslocalmessageid.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + [TestCase("1")] + [TestCase("2")] + public async Task StatusLocalMessageId_SingleCalled_CheckMessageIdsQueryParam( + string messageId) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/statuslocalmessageid.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.StatusLocalMessageId(messageId); + + Assert.That(passedQueryParams["messageid"], Is.EqualTo(messageId)); + } + + [Test] + public async Task StatusLocalMessageId_SingleCalled_ReturnsStatusMessageDto() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/statuslocalmessageid.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":[{}]}") + }); + + var result = await _kavenegarProfileApi.StatusLocalMessageId(""); + + Assert.That(result, Is.TypeOf()); + } + + [Test] + public async Task StatusLocalMessageId_MultiCalled_CallsPostAsync() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/statuslocalmessageid.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.StatusLocalMessageId( + new List + { + "" + }); + + _mockHttpClientHelper.Verify( + i => i.PostAsync( + "sms/statuslocalmessageid.json", + null, + It.IsAny>(), + It.IsAny())); + } + + [Test] + [TestCase("1")] + [TestCase("2")] + public async Task StatusLocalMessageId_MultiCalled_CheckMessageIdsQueryParam( + string messageId) + { + Dictionary passedQueryParams = null!; + + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/statuslocalmessageid.json", + null, + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>( + ( + _, + _, + queryParams, + _) => + { + passedQueryParams = queryParams; + }) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{}") + }); + + await _kavenegarProfileApi.StatusLocalMessageId( + new List + { + messageId, + messageId + }); + + Assert.That(passedQueryParams["messageid"], Is.EqualTo($"{messageId},{messageId}")); + } + + [Test] + public async Task StatusLocalMessageId_MultiCalled_ReturnsStatusMessageDto() + { + _mockHttpClientHelper.Setup( + i => i.PostAsync( + "sms/statuslocalmessageid.json", + null, + It.IsAny>(), + It.IsAny())) + .ReturnsAsync( + new HttpResponseMessage + { + Content = new StringContent("{\"entries\":[{}]}") + }); + + var result = await _kavenegarProfileApi.StatusLocalMessageId( + new List + { + "" + }); + + Assert.That(result, Is.TypeOf>()); + } +} \ No newline at end of file diff --git a/Test/Test.Kavenegar.Core/Test.Kavenegar.Core.csproj b/Test/Test.Kavenegar.Core/Test.Kavenegar.Core.csproj index e3d8042..2e2ef6c 100644 --- a/Test/Test.Kavenegar.Core/Test.Kavenegar.Core.csproj +++ b/Test/Test.Kavenegar.Core/Test.Kavenegar.Core.csproj @@ -8,15 +8,16 @@ - - - - - + + + + + + - + diff --git a/Test/Test.Shared.Infrastructure/DateHelperTests.cs b/Test/Test.Shared.Infrastructure/DateHelperTests.cs new file mode 100644 index 0000000..7aa71d3 --- /dev/null +++ b/Test/Test.Shared.Infrastructure/DateHelperTests.cs @@ -0,0 +1,47 @@ +using System; +using NUnit.Framework; +using Shared.Infrastructure; + +namespace Test.Shared.Infrastructure; + +public class DateHelperTests +{ + [Test] + public void ToDateTime_WhenCalled_EqualsToConvertedDateTime() + { + const long unixTimeStamp = 1577836800L; + + var result = unixTimeStamp.ToDateTime(); + + var expectedDateTime = new DateTime( + 2020, + 1, + 1); + + Assert.That(result, Is.EqualTo(expectedDateTime)); + } + + [Test] + public void ToUnixTimestamp_DateBeforeMinDateTime_ThrowsArgumentException() + { + var dt = new DateTime( + 1969, + 12, + 1); + + Assert.That(() => dt.ToUnixTimestamp(), Throws.ArgumentException); + } + + [Test] + public void ToUnixTimestamp_DateAfterMinDateTime_ReturnsUnixTimestamp() + { + var dt = new DateTime( + 2020, + 1, + 1); + + var unixTimestamp = dt.ToUnixTimestamp(); + + Assert.That(unixTimestamp, Is.EqualTo(1577836800)); + } +} \ No newline at end of file diff --git a/Test/Test.Shared.Infrastructure/HttpClientHelperTests.cs b/Test/Test.Shared.Infrastructure/HttpClientHelperTests.cs new file mode 100644 index 0000000..462ceea --- /dev/null +++ b/Test/Test.Shared.Infrastructure/HttpClientHelperTests.cs @@ -0,0 +1,62 @@ +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Moq; +using Moq.Protected; +using NUnit.Framework; +using Shared.Infrastructure; + +namespace Test.Shared.Infrastructure; + +[TestFixture] +public class HttpClientHelperTests +{ + [SetUp] + public void SetUp() + { + _httpClientMock = new Mock(); + var httpClient = new HttpClient(_httpClientMock.Object); + _httpClientHelper = new HttpClientHelper(httpClient) + { + BaseAddress = "https://aaa.com" + }; + } + + private HttpClientHelper _httpClientHelper = null!; + private Mock _httpClientMock = null!; + + [Test] + public async Task PostAsync_WhenCalled_ReturnsHttpResponseMessage() + { + _httpClientMock.Protected() + .Setup>( + "SendAsync", + ItExpr.Is(req => req.Method == HttpMethod.Post), + ItExpr.IsAny()) + .ReturnsAsync(new HttpResponseMessage()); + + var result = await _httpClientHelper.PostAsync("c"); + + Assert.That(result, Is.TypeOf()); + } + + [Test] + public async Task PostAsync_WhenCalled_ReturnsCallsPostAsync() + { + _httpClientMock.Protected() + .Setup>( + "SendAsync", + ItExpr.Is(req => req.Method == HttpMethod.Post), + ItExpr.IsAny()) + .ReturnsAsync(new HttpResponseMessage()); + + await _httpClientHelper.PostAsync("c"); + + _httpClientMock.Protected() + .Verify( + "SendAsync", + Times.Exactly(1), + ItExpr.Is(req => req.Method == HttpMethod.Post), + ItExpr.IsAny()); + } +} \ No newline at end of file diff --git a/Test/Test.Shared.Infrastructure/JsonUtilityTests.cs b/Test/Test.Shared.Infrastructure/JsonUtilityTests.cs new file mode 100644 index 0000000..87a3e39 --- /dev/null +++ b/Test/Test.Shared.Infrastructure/JsonUtilityTests.cs @@ -0,0 +1,31 @@ +using System.Net.Http; +using System.Threading.Tasks; +using NUnit.Framework; +using Shared.Infrastructure; + +namespace Test.Shared.Infrastructure; + +[TestFixture] +public class JsonUtilityTests +{ + [Test] + public void Serialize_WhenCalled_ReturnsObjectJson() + { + var result = new object().Serialize(); + + Assert.That(result, Is.EqualTo("{}")); + } + + [Test] + public async Task Deserialize_WhenCalled_ReturnsDeserializedObject() + { + var httpResponseMessage = new HttpResponseMessage + { + Content = new StringContent("[{}]") + }; + + var result = await httpResponseMessage.Deserialize(); + + Assert.That(result, Is.TypeOf()); + } +} \ No newline at end of file diff --git a/Test/Test.Shared.Infrastructure/QueryParamHelperTests.cs b/Test/Test.Shared.Infrastructure/QueryParamHelperTests.cs new file mode 100644 index 0000000..20f5d95 --- /dev/null +++ b/Test/Test.Shared.Infrastructure/QueryParamHelperTests.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; +using NUnit.Framework; +using Shared.Infrastructure; + +namespace Test.Shared.Infrastructure; + +[TestFixture] +public class QueryParamHelperTests +{ + [Test] + public void AddQueryParamToUri_WhnCalled_ReturnsFullUri() + { + var result = QueryParamHelper.AddQueryParamToUri( + "http://a.b", + new Dictionary + { + { + "param", "value" + } + }); + + Assert.That(result, Is.EqualTo("http://a.b/?param=value")); + } +} \ No newline at end of file diff --git a/Test/Test.Shared.Infrastructure/StringUtilityTests.cs b/Test/Test.Shared.Infrastructure/StringUtilityTests.cs new file mode 100644 index 0000000..d25d3ff --- /dev/null +++ b/Test/Test.Shared.Infrastructure/StringUtilityTests.cs @@ -0,0 +1,108 @@ +using NUnit.Framework; +using Shared.Infrastructure; + +namespace Test.Shared.Infrastructure; + +[TestFixture] +public class StringUtilityTests +{ + [Test] + public void IsNullOrWhiteSpace_EmptyString_ReturnsTrue() + { + var result = string.Empty.IsNullOrWhiteSpace(); + + Assert.That(result, Is.True); + } + + [Test] + public void IsNullOrWhiteSpace_StringWithZeroLength_ReturnsTrue() + { + var result = "".IsNullOrWhiteSpace(); + + Assert.That(result, Is.True); + } + + [Test] + public void IsNullOrWhiteSpace_NullString_ReturnsTrue() + { + string? s = null; + + var result = s.IsNullOrWhiteSpace(); + + Assert.That(result, Is.True); + } + + [Test] + [TestCase(" ")] + [TestCase(" ")] + [TestCase(" ")] + public void IsNullOrWhiteSpace_WhiteSpaceString_ReturnsTrue( + string s) + { + var result = s.IsNullOrWhiteSpace(); + + Assert.That(result, Is.True); + } + + [Test] + [TestCase("a")] + [TestCase("ab")] + [TestCase("abc")] + public void IsNullOrWhiteSpace_StringWithCharacter_ReturnsFalse( + string s) + { + var result = s.IsNullOrWhiteSpace(); + + Assert.That(result, Is.False); + } + + [Test] + public void IsNotNullOrWhiteSpace_EmptyString_ReturnsTrue() + { + var result = string.Empty.IsNotNullOrWhiteSpace(); + + Assert.That(result, Is.False); + } + + [Test] + public void IsNotNullOrWhiteSpace_StringWithZeroLength_ReturnsTrue() + { + var result = "".IsNotNullOrWhiteSpace(); + + Assert.That(result, Is.False); + } + + [Test] + public void IsNotNullOrWhiteSpace_NullString_ReturnsTrue() + { + string? s = null; + + var result = s.IsNotNullOrWhiteSpace(); + + Assert.That(result, Is.False); + } + + [Test] + [TestCase(" ")] + [TestCase(" ")] + [TestCase(" ")] + public void IsNotNullOrWhiteSpace_WhiteSpaceString_ReturnsTrue( + string s) + { + var result = s.IsNotNullOrWhiteSpace(); + + Assert.That(result, Is.False); + } + + [Test] + [TestCase("a")] + [TestCase("ab")] + [TestCase("abc")] + public void IsNotNullOrWhiteSpace_StringWithCharacter_ReturnsFalse( + string s) + { + var result = s.IsNotNullOrWhiteSpace(); + + Assert.That(result, Is.True); + } +} \ No newline at end of file diff --git a/Test/Test.Shared.Infrastructure/Test.Shared.Infrastructure.csproj b/Test/Test.Shared.Infrastructure/Test.Shared.Infrastructure.csproj new file mode 100644 index 0000000..308d2ca --- /dev/null +++ b/Test/Test.Shared.Infrastructure/Test.Shared.Infrastructure.csproj @@ -0,0 +1,24 @@ + + + + net6.0 + enable + + false + + Test.Shared.Infrastructure + + + + + + + + + + + + + + + From 2c972d82fa9f72a668e78f23964d427d445408a2 Mon Sep 17 00:00:00 2001 From: alireza995 <88311706+alireza995@users.noreply.github.com> Date: Wed, 14 Dec 2022 23:15:39 +0330 Subject: [PATCH 11/14] test(IntegrationTest) : create test project create test project closes nothing --- Kavenegar.sln | 7 +++ .../Controllers/WeatherForecastController.cs | 44 +++++++++++++++++++ Test/IntegrationTest/IntegrationTest.csproj | 13 ++++++ Test/IntegrationTest/Program.cs | 25 +++++++++++ Test/IntegrationTest/WeatherForecast.cs | 12 +++++ .../appsettings.Development.json | 8 ++++ Test/IntegrationTest/appsettings.json | 9 ++++ logo.svg | 15 +++++++ 8 files changed, 133 insertions(+) create mode 100644 Test/IntegrationTest/Controllers/WeatherForecastController.cs create mode 100644 Test/IntegrationTest/IntegrationTest.csproj create mode 100644 Test/IntegrationTest/Program.cs create mode 100644 Test/IntegrationTest/WeatherForecast.cs create mode 100644 Test/IntegrationTest/appsettings.Development.json create mode 100644 Test/IntegrationTest/appsettings.json create mode 100644 logo.svg diff --git a/Kavenegar.sln b/Kavenegar.sln index b9f0d75..42817c7 100644 --- a/Kavenegar.sln +++ b/Kavenegar.sln @@ -12,6 +12,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test.Kavenegar.Core", "Test EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test.Shared.Infrastructure", "Test\Test.Shared.Infrastructure\Test.Shared.Infrastructure.csproj", "{F7A2FE83-BE4B-4A9D-BEF5-A14FC8E05AFD}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IntegrationTest", "Test\IntegrationTest\IntegrationTest.csproj", "{33DA3E9D-619D-4074-A98E-DE1632074ABC}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -34,11 +36,16 @@ Global {F7A2FE83-BE4B-4A9D-BEF5-A14FC8E05AFD}.Debug|Any CPU.Build.0 = Debug|Any CPU {F7A2FE83-BE4B-4A9D-BEF5-A14FC8E05AFD}.Release|Any CPU.ActiveCfg = Release|Any CPU {F7A2FE83-BE4B-4A9D-BEF5-A14FC8E05AFD}.Release|Any CPU.Build.0 = Release|Any CPU + {33DA3E9D-619D-4074-A98E-DE1632074ABC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {33DA3E9D-619D-4074-A98E-DE1632074ABC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {33DA3E9D-619D-4074-A98E-DE1632074ABC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {33DA3E9D-619D-4074-A98E-DE1632074ABC}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {35D0DBF6-25F0-4DEB-9BC8-D3C3B65933EB} = {67BC444E-84C9-493C-B776-55FE5D54D560} {5A102430-241D-46A1-A615-0149411194D5} = {67BC444E-84C9-493C-B776-55FE5D54D560} {6E36B3F6-2B1D-4506-BA92-007AC00EF317} = {17B39BF3-CC26-40C5-AEB0-87CA2D71B93E} {F7A2FE83-BE4B-4A9D-BEF5-A14FC8E05AFD} = {17B39BF3-CC26-40C5-AEB0-87CA2D71B93E} + {33DA3E9D-619D-4074-A98E-DE1632074ABC} = {17B39BF3-CC26-40C5-AEB0-87CA2D71B93E} EndGlobalSection EndGlobal diff --git a/Test/IntegrationTest/Controllers/WeatherForecastController.cs b/Test/IntegrationTest/Controllers/WeatherForecastController.cs new file mode 100644 index 0000000..e018f38 --- /dev/null +++ b/Test/IntegrationTest/Controllers/WeatherForecastController.cs @@ -0,0 +1,44 @@ +using Microsoft.AspNetCore.Mvc; + +namespace IntegrationTest.Controllers; + +[ApiController] +[Route("[controller]")] +public class WeatherForecastController : ControllerBase +{ + private static readonly string[] Summaries = new[] + { + "Freezing", + "Bracing", + "Chilly", + "Cool", + "Mild", + "Warm", + "Balmy", + "Hot", + "Sweltering", + "Scorching" + }; + + private readonly ILogger _logger; + + public WeatherForecastController( + ILogger logger) + { + _logger = logger; + } + + [HttpGet(Name = "GetWeatherForecast")] + public IEnumerable Get() + { + return Enumerable.Range(1, 5) + .Select( + index => new WeatherForecast + { + Date = DateTime.Now.AddDays(index), + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] + }) + .ToArray(); + } +} \ No newline at end of file diff --git a/Test/IntegrationTest/IntegrationTest.csproj b/Test/IntegrationTest/IntegrationTest.csproj new file mode 100644 index 0000000..6108b7b --- /dev/null +++ b/Test/IntegrationTest/IntegrationTest.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + enable + + + + + + + diff --git a/Test/IntegrationTest/Program.cs b/Test/IntegrationTest/Program.cs new file mode 100644 index 0000000..8264bac --- /dev/null +++ b/Test/IntegrationTest/Program.cs @@ -0,0 +1,25 @@ +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. + +builder.Services.AddControllers(); +// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseHttpsRedirection(); + +app.UseAuthorization(); + +app.MapControllers(); + +app.Run(); \ No newline at end of file diff --git a/Test/IntegrationTest/WeatherForecast.cs b/Test/IntegrationTest/WeatherForecast.cs new file mode 100644 index 0000000..46980c3 --- /dev/null +++ b/Test/IntegrationTest/WeatherForecast.cs @@ -0,0 +1,12 @@ +namespace IntegrationTest; + +public class WeatherForecast +{ + public DateTime Date { get; set; } + + public int TemperatureC { get; set; } + + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + + public string? Summary { get; set; } +} \ No newline at end of file diff --git a/Test/IntegrationTest/appsettings.Development.json b/Test/IntegrationTest/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/Test/IntegrationTest/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Test/IntegrationTest/appsettings.json b/Test/IntegrationTest/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/Test/IntegrationTest/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/logo.svg b/logo.svg new file mode 100644 index 0000000..aa475e6 --- /dev/null +++ b/logo.svg @@ -0,0 +1,15 @@ + + + + + + + From b2f22c45a8325a3655244e6f0ee918a69e1f840c Mon Sep 17 00:00:00 2001 From: alireza995 <88311706+alireza995@users.noreply.github.com> Date: Thu, 15 Dec 2022 01:00:20 +0330 Subject: [PATCH 12/14] test(Solution) : test all basic methods of all actions test all basic methods of all actions closes nothing --- .../Dto/Message/SendMessageInfo.cs | 2 +- .../Kavenegar.Core/Dto/Result/ResultStatus.cs | 7 +- .../Kavenegar.Core/IKavenegarMessageSender.cs | 24 ++++ Code/Kavenegar.Core/KavenegarMessageSender.cs | 25 ++++ .../Shared.Infrastructure/JsonUtility.cs | 7 +- Kavenegar.sln.DotSettings | 2 + .../Controllers/KavenegarProfileController.cs | 128 ++++++++++++++++++ .../Controllers/MessageSenderController.cs | 39 ++++++ .../Controllers/WeatherForecastController.cs | 44 ------ Test/IntegrationTest/IntegrationTest.csproj | 4 + Test/IntegrationTest/Program.cs | 6 +- Test/IntegrationTest/WeatherForecast.cs | 12 -- Test/IntegrationTest/appsettings.json | 3 +- 13 files changed, 240 insertions(+), 63 deletions(-) create mode 100644 Test/IntegrationTest/Controllers/KavenegarProfileController.cs create mode 100644 Test/IntegrationTest/Controllers/MessageSenderController.cs delete mode 100644 Test/IntegrationTest/Controllers/WeatherForecastController.cs delete mode 100644 Test/IntegrationTest/WeatherForecast.cs diff --git a/Code/Kavenegar.Core/Dto/Message/SendMessageInfo.cs b/Code/Kavenegar.Core/Dto/Message/SendMessageInfo.cs index bfb9505..ada046f 100644 --- a/Code/Kavenegar.Core/Dto/Message/SendMessageInfo.cs +++ b/Code/Kavenegar.Core/Dto/Message/SendMessageInfo.cs @@ -12,5 +12,5 @@ public SendMessageInfo( public MessageInfo MessageInfo { get; set; } public string Receptor { get; set; } - public string LocalMessageId { get; set; } = null!; + public string? LocalMessageId { get; set; } = null!; } \ No newline at end of file diff --git a/Code/Kavenegar.Core/Dto/Result/ResultStatus.cs b/Code/Kavenegar.Core/Dto/Result/ResultStatus.cs index 32762a2..c615c1d 100644 --- a/Code/Kavenegar.Core/Dto/Result/ResultStatus.cs +++ b/Code/Kavenegar.Core/Dto/Result/ResultStatus.cs @@ -1,7 +1,12 @@ -namespace Kavenegar.Core.Dto.Result; +using System.Text.Json.Serialization; + +namespace Kavenegar.Core.Dto.Result; internal class ResultStatus { + [JsonPropertyName("status")] public int Status { get; set; } + + [JsonPropertyName("message")] public string Message { get; set; } = null!; } \ No newline at end of file diff --git a/Code/Kavenegar.Core/IKavenegarMessageSender.cs b/Code/Kavenegar.Core/IKavenegarMessageSender.cs index 076c359..a172587 100644 --- a/Code/Kavenegar.Core/IKavenegarMessageSender.cs +++ b/Code/Kavenegar.Core/IKavenegarMessageSender.cs @@ -48,6 +48,26 @@ public interface IKavenegarMessageSender MessageType messageType = MessageType.AppMemory, CancellationToken cancellationToken = default); + /// + /// Send message text for each receptor with the localMessageId + /// + /// Message text. + /// Key for receptor and value is for local message id. + /// Number to send message if you set it empty the default number will be used. + /// The date time you wand the message to be sent. If it is null message will be send asap. + /// If true receptor number will be hidden. + /// Type of message. + /// Token to cancel request. + /// + Task?> Send( + string message, + IEnumerable receptors, + string sender = "", + DateTime? dateTime = null, + bool hide = false, + MessageType messageType = MessageType.AppMemory, + CancellationToken cancellationToken = default); + public Task?> Send( SendSingleMessageRequest message, CancellationToken cancellationToken = default); @@ -72,4 +92,8 @@ public interface IKavenegarMessageSender string? token5 = null, VerifyLookupType? type = null, CancellationToken cancellationToken = default); + + Task VerifyLookup( + VerifyLookupRequest verifyLookupRequest, + CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Code/Kavenegar.Core/KavenegarMessageSender.cs b/Code/Kavenegar.Core/KavenegarMessageSender.cs index 94a540d..d7ca8ae 100644 --- a/Code/Kavenegar.Core/KavenegarMessageSender.cs +++ b/Code/Kavenegar.Core/KavenegarMessageSender.cs @@ -97,6 +97,31 @@ public KavenegarMessageSender( return await Send(sendSingleMessageRequest, cancellationToken); } + public async Task?> Send( + string message, + IEnumerable receptors, + string sender = "", + DateTime? dateTime = null, + bool hide = false, + MessageType messageType = MessageType.AppMemory, + CancellationToken cancellationToken = default) + { + var sendSingleMessageRequest = new SendSingleMessageRequest( + new MessageInfo(message) + { + Sender = sender, + Type = messageType + }, + receptors.ToDictionary(i => i, _ => "")!) + { + Hide = hide + }; + + if (dateTime.HasValue) sendSingleMessageRequest.Date = dateTime; + + return await Send(sendSingleMessageRequest, cancellationToken); + } + public async Task?> Send( SendSingleMessageRequest message, CancellationToken cancellationToken = default) diff --git a/Code/Shared/Shared.Infrastructure/JsonUtility.cs b/Code/Shared/Shared.Infrastructure/JsonUtility.cs index c6706b1..c64f94d 100644 --- a/Code/Shared/Shared.Infrastructure/JsonUtility.cs +++ b/Code/Shared/Shared.Infrastructure/JsonUtility.cs @@ -15,6 +15,11 @@ public static string Serialize( CancellationToken cancellationToken = default) { var content = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken); - return JsonSerializer.Deserialize(content); + return JsonSerializer.Deserialize( + content, + new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true + }); } } \ No newline at end of file diff --git a/Kavenegar.sln.DotSettings b/Kavenegar.sln.DotSettings index cc70dac..ecac642 100644 --- a/Kavenegar.sln.DotSettings +++ b/Kavenegar.sln.DotSettings @@ -7,6 +7,7 @@ True True True + True True True True @@ -14,6 +15,7 @@ True True True + True True True True diff --git a/Test/IntegrationTest/Controllers/KavenegarProfileController.cs b/Test/IntegrationTest/Controllers/KavenegarProfileController.cs new file mode 100644 index 0000000..8dd5d2c --- /dev/null +++ b/Test/IntegrationTest/Controllers/KavenegarProfileController.cs @@ -0,0 +1,128 @@ +using Kavenegar.Core; +using Kavenegar.Core.Enums; +using Microsoft.AspNetCore.Mvc; + +namespace IntegrationTest.Controllers; + +[ApiController] +[Route("[controller]/[action]")] +public class KavenegarProfileController : ControllerBase +{ + private readonly IKavenegarProfileApi _kavenegarProfileApi; + + public KavenegarProfileController( + IKavenegarProfileApi kavenegarProfileApi) + { + _kavenegarProfileApi = kavenegarProfileApi; + } + + [HttpPost] + public async Task Cancel( + IEnumerable ids) + { + return Ok(await _kavenegarProfileApi.Cancel(ids)); + } + + [HttpGet] + public async Task Receive( + string line, + bool isRead) + { + return Ok(await _kavenegarProfileApi.Receive(line, isRead)); + } + + [HttpGet] + public async Task Select( + IEnumerable messageIds) + { + return Ok(await _kavenegarProfileApi.Select(messageIds)); + } + + [HttpGet] + public async Task Status( + IEnumerable messageIds) + { + return Ok(await _kavenegarProfileApi.Status(messageIds)); + } + + [HttpPost] + public async Task AccountConfig( + string? apiLogs = null, + string? dailyReport = null, + string? debugMode = null, + string? defaultSender = null, + int? minCreditAlarm = null, + string? resendFailed = null) + { + return Ok( + await _kavenegarProfileApi.AccountConfig( + apiLogs, + dailyReport, + debugMode, + defaultSender, + minCreditAlarm, + resendFailed)); + } + + [HttpGet] + public async Task AccountInfo() + { + return Ok(await _kavenegarProfileApi.AccountInfo()); + } + + [HttpGet] + public async Task CountInbox( + DateTime startDate, + DateTime? endDate, + string? lineNumber, + bool? isRead) + { + return Ok( + await _kavenegarProfileApi.CountInbox( + startDate, + endDate, + lineNumber, + isRead)); + } + + [HttpGet] + public async Task CountOutbox( + DateTime startDate, + DateTime? endDate = null, + MessageStatus? status = null) + { + return Ok( + await _kavenegarProfileApi.CountOutbox( + startDate, + endDate, + status)); + } + + [HttpGet] + public async Task LatestOutbox( + int? pageSize = null, + string? sender = null) + { + return Ok(await _kavenegarProfileApi.LatestOutbox(pageSize, sender)); + } + + [HttpGet] + public async Task SelectOutbox( + DateTime startDate, + DateTime? endDate = null, + string? sender = null) + { + return Ok( + await _kavenegarProfileApi.SelectOutbox( + startDate, + endDate, + sender)); + } + + [HttpGet] + public async Task StatusLocalMessageId( + IEnumerable messageIds) + { + return Ok(await _kavenegarProfileApi.StatusLocalMessageId(messageIds)); + } +} \ No newline at end of file diff --git a/Test/IntegrationTest/Controllers/MessageSenderController.cs b/Test/IntegrationTest/Controllers/MessageSenderController.cs new file mode 100644 index 0000000..b8be154 --- /dev/null +++ b/Test/IntegrationTest/Controllers/MessageSenderController.cs @@ -0,0 +1,39 @@ +using Kavenegar.Core; +using Kavenegar.Core.Dto.Message; +using Microsoft.AspNetCore.Mvc; + +namespace IntegrationTest.Controllers; + +[ApiController] +[Route("[controller]/[action]")] +public class MessageSenderController : ControllerBase +{ + private readonly IKavenegarMessageSender _kavenegarMessageSender; + + public MessageSenderController( + IKavenegarMessageSender kavenegarMessageSender) + { + _kavenegarMessageSender = kavenegarMessageSender; + } + + [HttpPost] + public async Task SendSingleMessage( + SendSingleMessageRequest singleMessageRequest) + { + return Ok(await _kavenegarMessageSender.Send(singleMessageRequest)); + } + + [HttpPost] + public async Task SendMultiMessage( + SendMultiMessageRequest sendMultiMessageRequest) + { + return Ok(await _kavenegarMessageSender.Send(sendMultiMessageRequest)); + } + + [HttpPost] + public async Task VerifyLookUp( + VerifyLookupRequest verifyLookupRequest) + { + return Ok(await _kavenegarMessageSender.VerifyLookup(verifyLookupRequest)); + } +} \ No newline at end of file diff --git a/Test/IntegrationTest/Controllers/WeatherForecastController.cs b/Test/IntegrationTest/Controllers/WeatherForecastController.cs deleted file mode 100644 index e018f38..0000000 --- a/Test/IntegrationTest/Controllers/WeatherForecastController.cs +++ /dev/null @@ -1,44 +0,0 @@ -using Microsoft.AspNetCore.Mvc; - -namespace IntegrationTest.Controllers; - -[ApiController] -[Route("[controller]")] -public class WeatherForecastController : ControllerBase -{ - private static readonly string[] Summaries = new[] - { - "Freezing", - "Bracing", - "Chilly", - "Cool", - "Mild", - "Warm", - "Balmy", - "Hot", - "Sweltering", - "Scorching" - }; - - private readonly ILogger _logger; - - public WeatherForecastController( - ILogger logger) - { - _logger = logger; - } - - [HttpGet(Name = "GetWeatherForecast")] - public IEnumerable Get() - { - return Enumerable.Range(1, 5) - .Select( - index => new WeatherForecast - { - Date = DateTime.Now.AddDays(index), - TemperatureC = Random.Shared.Next(-20, 55), - Summary = Summaries[Random.Shared.Next(Summaries.Length)] - }) - .ToArray(); - } -} \ No newline at end of file diff --git a/Test/IntegrationTest/IntegrationTest.csproj b/Test/IntegrationTest/IntegrationTest.csproj index 6108b7b..29600b6 100644 --- a/Test/IntegrationTest/IntegrationTest.csproj +++ b/Test/IntegrationTest/IntegrationTest.csproj @@ -10,4 +10,8 @@ + + + + diff --git a/Test/IntegrationTest/Program.cs b/Test/IntegrationTest/Program.cs index 8264bac..aa6c0fb 100644 --- a/Test/IntegrationTest/Program.cs +++ b/Test/IntegrationTest/Program.cs @@ -1,11 +1,11 @@ -var builder = WebApplication.CreateBuilder(args); +using Kavenegar.Core; -// Add services to the container. +var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); -// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); +builder.Services.AddKavenegar(builder.Configuration["ApiKey"]); var app = builder.Build(); diff --git a/Test/IntegrationTest/WeatherForecast.cs b/Test/IntegrationTest/WeatherForecast.cs deleted file mode 100644 index 46980c3..0000000 --- a/Test/IntegrationTest/WeatherForecast.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace IntegrationTest; - -public class WeatherForecast -{ - public DateTime Date { get; set; } - - public int TemperatureC { get; set; } - - public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); - - public string? Summary { get; set; } -} \ No newline at end of file diff --git a/Test/IntegrationTest/appsettings.json b/Test/IntegrationTest/appsettings.json index 10f68b8..2833cf7 100644 --- a/Test/IntegrationTest/appsettings.json +++ b/Test/IntegrationTest/appsettings.json @@ -5,5 +5,6 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "ApiKey": "" } From 12fdf571a2e4c07ea259a0d969478ff75b6f36a5 Mon Sep 17 00:00:00 2001 From: alireza995 <88311706+alireza995@users.noreply.github.com> Date: Thu, 15 Dec 2022 01:14:37 +0330 Subject: [PATCH 13/14] refactor(Kavenegar) : Add easy constructor Add easy constructor for projects with no DI closes nothing --- Code/Kavenegar.Core/KavenegarMessageSender.cs | 5 +++++ Code/Kavenegar.Core/KavenegarProfileApi.cs | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/Code/Kavenegar.Core/KavenegarMessageSender.cs b/Code/Kavenegar.Core/KavenegarMessageSender.cs index d7ca8ae..837238c 100644 --- a/Code/Kavenegar.Core/KavenegarMessageSender.cs +++ b/Code/Kavenegar.Core/KavenegarMessageSender.cs @@ -16,6 +16,11 @@ public KavenegarMessageSender( { } + public KavenegarMessageSender( + string apiKey) : base(new HttpClientHelper(new HttpClient()), apiKey) + { + } + /// /// Send one message for only the receptor /// diff --git a/Code/Kavenegar.Core/KavenegarProfileApi.cs b/Code/Kavenegar.Core/KavenegarProfileApi.cs index cb6c0a9..e32224a 100644 --- a/Code/Kavenegar.Core/KavenegarProfileApi.cs +++ b/Code/Kavenegar.Core/KavenegarProfileApi.cs @@ -13,6 +13,11 @@ public KavenegarProfileApi( string apiKey) : base(httpClientHelper, apiKey) { } + + public KavenegarProfileApi( + string apiKey) : base(new HttpClientHelper(new HttpClient()), apiKey) + { + } public async Task Status( string messageId, From 25ab9e9faaa7be74b47cc7afabfdd816af62c2a9 Mon Sep 17 00:00:00 2001 From: alireza995 <88311706+alireza995@users.noreply.github.com> Date: Thu, 15 Dec 2022 22:01:32 +0330 Subject: [PATCH 14/14] refactor(IntegrationTest) : refactor controllers refactor controllers and handle null ResultStatus.cs closes nothing --- .../Dto/Result/CountInboxDto.cs | 5 +++ .../Kavenegar.Core/Dto/Result/ResultStatus.cs | 2 +- Code/Kavenegar.Core/KavenegarProfileApi.cs | 2 +- .../Controllers/BaseAPiController.cs | 15 +++++++++ .../Controllers/KavenegarProfileController.cs | 32 +++++++++---------- .../Controllers/MessageSenderController.cs | 10 +++--- 6 files changed, 41 insertions(+), 25 deletions(-) create mode 100644 Test/IntegrationTest/Controllers/BaseAPiController.cs diff --git a/Code/Kavenegar.Core/Dto/Result/CountInboxDto.cs b/Code/Kavenegar.Core/Dto/Result/CountInboxDto.cs index 766a3c3..d825ca8 100644 --- a/Code/Kavenegar.Core/Dto/Result/CountInboxDto.cs +++ b/Code/Kavenegar.Core/Dto/Result/CountInboxDto.cs @@ -1,8 +1,13 @@ +using Shared.Infrastructure; + namespace Kavenegar.Core.Dto.Result; public class CountInboxDto { public long StartDate { get; set; } + public DateTime StartDateGregorian => StartDate.ToDateTime(); public long EndDate { get; set; } + public DateTime EndDateGregorian => EndDate.ToDateTime(); + public long SumCount { get; set; } } \ No newline at end of file diff --git a/Code/Kavenegar.Core/Dto/Result/ResultStatus.cs b/Code/Kavenegar.Core/Dto/Result/ResultStatus.cs index c615c1d..8d44644 100644 --- a/Code/Kavenegar.Core/Dto/Result/ResultStatus.cs +++ b/Code/Kavenegar.Core/Dto/Result/ResultStatus.cs @@ -6,7 +6,7 @@ internal class ResultStatus { [JsonPropertyName("status")] public int Status { get; set; } - + [JsonPropertyName("message")] public string Message { get; set; } = null!; } \ No newline at end of file diff --git a/Code/Kavenegar.Core/KavenegarProfileApi.cs b/Code/Kavenegar.Core/KavenegarProfileApi.cs index e32224a..31375df 100644 --- a/Code/Kavenegar.Core/KavenegarProfileApi.cs +++ b/Code/Kavenegar.Core/KavenegarProfileApi.cs @@ -13,7 +13,7 @@ public KavenegarProfileApi( string apiKey) : base(httpClientHelper, apiKey) { } - + public KavenegarProfileApi( string apiKey) : base(new HttpClientHelper(new HttpClient()), apiKey) { diff --git a/Test/IntegrationTest/Controllers/BaseAPiController.cs b/Test/IntegrationTest/Controllers/BaseAPiController.cs new file mode 100644 index 0000000..965e054 --- /dev/null +++ b/Test/IntegrationTest/Controllers/BaseAPiController.cs @@ -0,0 +1,15 @@ +using Microsoft.AspNetCore.Mvc; + +namespace IntegrationTest.Controllers; + +[ApiController] +[Route("[controller]/[action]")] +public class BaseAPiController : ControllerBase +{ + protected IActionResult HandleValue( + T? value) + { + if (value == null) return NoContent(); + return Ok(value); + } +} \ No newline at end of file diff --git a/Test/IntegrationTest/Controllers/KavenegarProfileController.cs b/Test/IntegrationTest/Controllers/KavenegarProfileController.cs index 8dd5d2c..d455ae3 100644 --- a/Test/IntegrationTest/Controllers/KavenegarProfileController.cs +++ b/Test/IntegrationTest/Controllers/KavenegarProfileController.cs @@ -4,9 +4,7 @@ namespace IntegrationTest.Controllers; -[ApiController] -[Route("[controller]/[action]")] -public class KavenegarProfileController : ControllerBase +public class KavenegarProfileController : BaseAPiController { private readonly IKavenegarProfileApi _kavenegarProfileApi; @@ -20,7 +18,7 @@ public KavenegarProfileController( public async Task Cancel( IEnumerable ids) { - return Ok(await _kavenegarProfileApi.Cancel(ids)); + return HandleValue(await _kavenegarProfileApi.Cancel(ids)); } [HttpGet] @@ -28,21 +26,21 @@ public async Task Receive( string line, bool isRead) { - return Ok(await _kavenegarProfileApi.Receive(line, isRead)); + return HandleValue(await _kavenegarProfileApi.Receive(line, isRead)); } [HttpGet] public async Task Select( - IEnumerable messageIds) + [FromQuery] IEnumerable messageIds) { - return Ok(await _kavenegarProfileApi.Select(messageIds)); + return HandleValue(await _kavenegarProfileApi.Select(messageIds)); } [HttpGet] public async Task Status( - IEnumerable messageIds) + [FromQuery] IEnumerable messageIds) { - return Ok(await _kavenegarProfileApi.Status(messageIds)); + return HandleValue(await _kavenegarProfileApi.Status(messageIds)); } [HttpPost] @@ -54,7 +52,7 @@ public async Task AccountConfig( int? minCreditAlarm = null, string? resendFailed = null) { - return Ok( + return HandleValue( await _kavenegarProfileApi.AccountConfig( apiLogs, dailyReport, @@ -67,7 +65,7 @@ await _kavenegarProfileApi.AccountConfig( [HttpGet] public async Task AccountInfo() { - return Ok(await _kavenegarProfileApi.AccountInfo()); + return HandleValue(await _kavenegarProfileApi.AccountInfo()); } [HttpGet] @@ -77,7 +75,7 @@ public async Task CountInbox( string? lineNumber, bool? isRead) { - return Ok( + return HandleValue( await _kavenegarProfileApi.CountInbox( startDate, endDate, @@ -91,7 +89,7 @@ public async Task CountOutbox( DateTime? endDate = null, MessageStatus? status = null) { - return Ok( + return HandleValue( await _kavenegarProfileApi.CountOutbox( startDate, endDate, @@ -103,7 +101,7 @@ public async Task LatestOutbox( int? pageSize = null, string? sender = null) { - return Ok(await _kavenegarProfileApi.LatestOutbox(pageSize, sender)); + return HandleValue(await _kavenegarProfileApi.LatestOutbox(pageSize, sender)); } [HttpGet] @@ -112,7 +110,7 @@ public async Task SelectOutbox( DateTime? endDate = null, string? sender = null) { - return Ok( + return HandleValue( await _kavenegarProfileApi.SelectOutbox( startDate, endDate, @@ -121,8 +119,8 @@ await _kavenegarProfileApi.SelectOutbox( [HttpGet] public async Task StatusLocalMessageId( - IEnumerable messageIds) + [FromQuery] IEnumerable messageIds) { - return Ok(await _kavenegarProfileApi.StatusLocalMessageId(messageIds)); + return HandleValue(await _kavenegarProfileApi.StatusLocalMessageId(messageIds)); } } \ No newline at end of file diff --git a/Test/IntegrationTest/Controllers/MessageSenderController.cs b/Test/IntegrationTest/Controllers/MessageSenderController.cs index b8be154..95aab56 100644 --- a/Test/IntegrationTest/Controllers/MessageSenderController.cs +++ b/Test/IntegrationTest/Controllers/MessageSenderController.cs @@ -4,9 +4,7 @@ namespace IntegrationTest.Controllers; -[ApiController] -[Route("[controller]/[action]")] -public class MessageSenderController : ControllerBase +public class MessageSenderController : BaseAPiController { private readonly IKavenegarMessageSender _kavenegarMessageSender; @@ -20,20 +18,20 @@ public MessageSenderController( public async Task SendSingleMessage( SendSingleMessageRequest singleMessageRequest) { - return Ok(await _kavenegarMessageSender.Send(singleMessageRequest)); + return HandleValue(await _kavenegarMessageSender.Send(singleMessageRequest)); } [HttpPost] public async Task SendMultiMessage( SendMultiMessageRequest sendMultiMessageRequest) { - return Ok(await _kavenegarMessageSender.Send(sendMultiMessageRequest)); + return HandleValue(await _kavenegarMessageSender.Send(sendMultiMessageRequest)); } [HttpPost] public async Task VerifyLookUp( VerifyLookupRequest verifyLookupRequest) { - return Ok(await _kavenegarMessageSender.VerifyLookup(verifyLookupRequest)); + return HandleValue(await _kavenegarMessageSender.VerifyLookup(verifyLookupRequest)); } } \ No newline at end of file