Web API for the bulk printing desktop application.

Client.cs 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. using ExtensionMethods;
  2. using MAX.Models;
  3. using Microsoft.Extensions.Logging;
  4. using System;
  5. using System.Net.Sockets;
  6. using System.Security.Cryptography;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using System.Xml;
  11. namespace MAX
  12. {
  13. public class Client : IDisposable
  14. {
  15. private ILogger _logger;
  16. private string _host;
  17. private int _port;
  18. private int _vendorId;
  19. private string _serialNumber;
  20. private int _userId;
  21. private string _username;
  22. private string _password;
  23. private TcpClient _connection = null;
  24. private NetworkStream _connectionStream = null;
  25. private TripleDES _des = null;
  26. private bool _disposed = false;
  27. public Client(ILogger logger, string host, int port, int vendorId, string serialNumber, int userId, string username, string password)
  28. {
  29. _logger = logger;
  30. _host = host;
  31. _port = port;
  32. _vendorId = vendorId;
  33. _serialNumber = serialNumber;
  34. _userId = userId;
  35. _username = username;
  36. _password = password;
  37. ConnectTimeout = 10000;
  38. ReceiveTimeout = 10000;
  39. SendTimeout = 10000;
  40. }
  41. public Client(ILogger logger, string host, int port, LoginCredentials credentials)
  42. : this(logger, host, port, credentials.Vendor.Id, credentials.Vendor.SerialNumber,
  43. credentials.User.Id, credentials.User.Username, credentials.Password)
  44. {
  45. }
  46. public void Close()
  47. {
  48. Dispose(true);
  49. }
  50. public async Task<User> ConnectAsync()
  51. {
  52. if (_connection != null)
  53. throw new Exception("Already connected");
  54. _connection = new TcpClient(AddressFamily.InterNetwork);
  55. _connection.ReceiveTimeout = ReceiveTimeout;
  56. _connection.SendTimeout = SendTimeout;
  57. // Connect to the server
  58. try
  59. {
  60. using (var cancellationSource = new CancellationTokenSource(ConnectTimeout))
  61. {
  62. await _connection.ConnectAsync(_host, _port).WithCancellation(cancellationSource.Token).ConfigureAwait(false);
  63. }
  64. }
  65. catch (OperationCanceledException)
  66. {
  67. throw new Exception("Connect timeout");
  68. }
  69. _connectionStream = _connection.GetStream();
  70. // Device authentication
  71. await WriteMessageAsync(new MessageBuilder()
  72. .Append("Hi ")
  73. .Append(_serialNumber)
  74. .Append("|V")
  75. .Append(_vendorId)
  76. .Append("|123451234512345||||||")).ConfigureAwait(false);
  77. var response = await ReadMessageAsync().ConfigureAwait(false);
  78. if (!response.StartsWith("Hi "))
  79. {
  80. _logger.LogError("Device authentication failed: {0}", response);
  81. return null;
  82. }
  83. // Request server RSA key
  84. await WriteMessageAsync(new MessageBuilder().Append("PK")).ConfigureAwait(false);
  85. response = await ReadMessageAsync().ConfigureAwait(false);
  86. // Key exchange
  87. _des = TripleDES.Create();
  88. _des.IV = new byte[8];
  89. await WriteMessageAsync(new MessageBuilder()
  90. .Append("3D ")
  91. .Append(EncryptRSA(response, BitConverter.ToString(_des.Key).Replace("-", "")))).ConfigureAwait(false);
  92. response = await ReadMessageAsync().ConfigureAwait(false);
  93. if (!response.StartsWith("OK"))
  94. {
  95. throw new Exception(String.Format("Key exchange failed: {0}", response));
  96. }
  97. // User authentication
  98. await WriteMessageAsync(new MessageBuilder()
  99. .Append("User ")
  100. .Append(Encrypt(new StringBuilder()
  101. .Append(_userId)
  102. .Append("|")
  103. .Append(_username)
  104. .Append("|")
  105. .Append(_password).ToString()))).ConfigureAwait(false);
  106. response = Decrypt(await ReadMessageAsync().ConfigureAwait(false));
  107. if (response.StartsWith("OK"))
  108. {
  109. var parts = response.Split('|');
  110. var user = new User()
  111. {
  112. Id = _userId,
  113. Username = _username,
  114. FirstName = parts[4],
  115. Surname = parts[3],
  116. Enabled = bool.Parse(parts[6]),
  117. Level = (User.UserLevel)int.Parse(parts[1]),
  118. System = int.Parse(parts[2]),
  119. LastLogin = DateTime.Parse(parts[5])
  120. };
  121. if (user.Level == User.UserLevel.CustomUser)
  122. {
  123. user.CanPrintOffline = bool.Parse(parts[7]);
  124. user.OfflinePrintValue = decimal.Parse(parts[8]);
  125. user.CanPrintOnline = bool.Parse(parts[9]);
  126. user.OnlinePrintValue = decimal.Parse(parts[10]);
  127. user.CanReprintOffline = bool.Parse(parts[11]);
  128. user.OfflineReprintValue = decimal.Parse(parts[12]);
  129. user.CanReprintOnline = bool.Parse(parts[13]);
  130. user.OnlineReprintValue = decimal.Parse(parts[14]);
  131. }
  132. return user;
  133. }
  134. else if (response.StartsWith("ER"))
  135. {
  136. _logger.LogInformation("User authentication failed: {0}", response);
  137. return null;
  138. }
  139. else
  140. {
  141. throw new Exception(String.Format("Invalid user information response: {0}", response));
  142. }
  143. }
  144. public int ConnectTimeout { get; set; }
  145. protected virtual void Dispose(bool disposing)
  146. {
  147. if (_disposed)
  148. return;
  149. _disposed = true;
  150. // No unmanaged resources are disposed so we don't need the full finalisation pattern.
  151. if (disposing)
  152. {
  153. if (_des != null)
  154. {
  155. _des.Dispose();
  156. _des = null;
  157. }
  158. if (_connectionStream != null)
  159. {
  160. _connectionStream.Dispose();
  161. _connectionStream = null;
  162. }
  163. if (_connection != null)
  164. {
  165. _connection.Dispose();
  166. _connection = null;
  167. }
  168. }
  169. }
  170. public void Dispose()
  171. {
  172. Dispose(true);
  173. }
  174. private string Decrypt(string cipherText)
  175. {
  176. return Utils.TripleDESDecrypt(cipherText, _des);
  177. }
  178. private string Encrypt(string plainText)
  179. {
  180. return Utils.TripleDESEncrypt(plainText, _des);
  181. }
  182. private string EncryptRSA(string publicKey, string plainText)
  183. {
  184. RSAParameters parameters = new RSAParameters();
  185. var xml = new XmlDocument();
  186. xml.LoadXml(publicKey);
  187. if (! xml.DocumentElement.Name.Equals("RSAKeyValue"))
  188. throw new Exception("Invalid RSA key");
  189. foreach (XmlNode node in xml.DocumentElement.ChildNodes)
  190. {
  191. switch (node.Name)
  192. {
  193. case "Modulus": parameters.Modulus = Convert.FromBase64String(node.InnerText); break;
  194. case "Exponent": parameters.Exponent = Convert.FromBase64String(node.InnerText); break;
  195. case "P": parameters.P = Convert.FromBase64String(node.InnerText); break;
  196. case "Q": parameters.Q = Convert.FromBase64String(node.InnerText); break;
  197. case "DP": parameters.DP = Convert.FromBase64String(node.InnerText); break;
  198. case "DQ": parameters.DQ = Convert.FromBase64String(node.InnerText); break;
  199. case "InverseQ": parameters.InverseQ = Convert.FromBase64String(node.InnerText); break;
  200. case "D": parameters.D = Convert.FromBase64String(node.InnerText); break;
  201. }
  202. }
  203. using (var rsa = RSA.Create())
  204. {
  205. rsa.ImportParameters(parameters);
  206. var blockSize = rsa.KeySize / 8 - 42;
  207. var offset = 0;
  208. var input = Encoding.UTF32.GetBytes(plainText);
  209. StringBuilder output = new StringBuilder();
  210. while (offset < input.Length)
  211. {
  212. var length = input.Length - offset;
  213. if (length > blockSize)
  214. length = blockSize;
  215. var block = new byte[length];
  216. Array.Copy(input, offset, block, 0, length);
  217. var cipherText = rsa.Encrypt(block, RSAEncryptionPadding.OaepSHA1);
  218. Array.Reverse(cipherText);
  219. output.Append(Convert.ToBase64String(cipherText));
  220. offset += length;
  221. }
  222. return output.ToString();
  223. }
  224. }
  225. public async Task<Account> GetAccountAsync()
  226. {
  227. await WriteMessageAsync(new MessageBuilder().Append("Acc")).ConfigureAwait(false);
  228. var response = Decrypt(await ReadMessageAsync().ConfigureAwait(false));
  229. if (response.StartsWith("OK"))
  230. {
  231. var parts = response.Split('|');
  232. return new Account()
  233. {
  234. Id = int.Parse(parts[1]),
  235. Name = parts[2],
  236. Balance = decimal.Parse(parts[3]),
  237. Status = (Account.AccountStatus)int.Parse(parts[4]),
  238. Reference = parts[5],
  239. Warehouse = new Warehouse()
  240. {
  241. Id = int.Parse(parts[6]),
  242. Name = parts[7]
  243. }
  244. };
  245. }
  246. else
  247. {
  248. throw new Exception(String.Format("Invalid account information response: {0}", response));
  249. }
  250. }
  251. public async Task<ProductCatalogue> GetProductCatalogueAsync(Account account)
  252. {
  253. var encryptedWarehouseName = Encrypt(account.Warehouse.Name);
  254. await WriteMessageAsync(new MessageBuilder()
  255. .Append("Pdt ")
  256. .Append(encryptedWarehouseName)).ConfigureAwait(false);
  257. var response = Decrypt(await ReadMessageAsync().ConfigureAwait(false));
  258. if (response.StartsWith("OK"))
  259. {
  260. var parts = response.Split('|');
  261. var count = int.Parse(parts[1]);
  262. var catalogue = new ProductCatalogue();
  263. var listCommand = new MessageBuilder().Append("List ")
  264. .Append(encryptedWarehouseName).GetBytes();
  265. for (var i = 0; i < count; i++)
  266. {
  267. await _connectionStream.WriteAsync(listCommand, 0, listCommand.Length).ConfigureAwait(false);
  268. response = Decrypt(await ReadMessageAsync().ConfigureAwait(false));
  269. if (response.StartsWith("OK"))
  270. {
  271. parts = response.Split('|');
  272. int networkId = int.Parse(parts[4]);
  273. Network network;
  274. if (! catalogue.NetworkMap.TryGetValue(networkId, out network))
  275. {
  276. network = catalogue.AddNetwork(networkId, parts[5]);
  277. }
  278. catalogue.AddProduct(
  279. network: network,
  280. id: int.Parse(parts[1]),
  281. faceValue: decimal.Parse(parts[2]),
  282. description: parts[3],
  283. voucherType: (Batch.Vouchertype)int.Parse(parts[6]),
  284. discountPercentage: decimal.Parse(parts[7])
  285. );
  286. }
  287. else
  288. {
  289. throw new Exception(String.Format("Invalid product item response: {0}", response));
  290. }
  291. }
  292. return catalogue;
  293. }
  294. else
  295. {
  296. throw new Exception(String.Format("Invalid product catalogue response: {0}", response));
  297. }
  298. }
  299. public async Task<OrderResponse> PlaceOrderAsync(int accountId, Product product, int quantity,
  300. string customerReference, byte[] key)
  301. {
  302. if (key.Length != 24)
  303. {
  304. throw new ArgumentException("24 byte key expected", nameof(key));
  305. }
  306. await WriteMessageAsync(new MessageBuilder()
  307. .Append("Order ")
  308. .Append(Encrypt(new StringBuilder()
  309. .Append(product.Id)
  310. .Append("|")
  311. .Append(quantity)
  312. .Append("|")
  313. .Append(customerReference)
  314. .Append("|2|") // EncType: 0:None, 1:DES, 2:Triple DES
  315. .Append(BitConverter.ToString(key, 0, 8).Replace("-", ""))
  316. .Append("|")
  317. .Append(BitConverter.ToString(key, 8, 8).Replace("-", ""))
  318. .Append("|")
  319. .Append(BitConverter.ToString(key, 16, 8).Replace("-", ""))
  320. .ToString()))).ConfigureAwait(false);
  321. var response = Decrypt(await ReadMessageAsync().ConfigureAwait(false));
  322. if (response.StartsWith("OK"))
  323. {
  324. var parts = response.Split('|');
  325. return new OrderResponse()
  326. {
  327. Batch = new Batch()
  328. {
  329. Id = int.Parse(parts[1]),
  330. OrderReference = parts[2],
  331. RequestedQuantity = int.Parse(parts[3]),
  332. DeliveredQuantity = int.Parse(parts[4]),
  333. Cost = decimal.Parse(parts[5]),
  334. AccountId = accountId,
  335. VendorId = _vendorId,
  336. ProductId = product.Id,
  337. ProductDescription = product.Description,
  338. VoucherType = product.VoucherType,
  339. FaceValue = product.FaceValue,
  340. DiscountPercentage = product.DiscountPercentage,
  341. NetworkId = product.Network.Id,
  342. NetworkName = product.Network.Name,
  343. OrderDate = DateTime.Now,
  344. OrderedById = _userId,
  345. ReadyForDownload = false
  346. },
  347. RemainingBalance = decimal.Parse(parts[6])
  348. };
  349. }
  350. else
  351. {
  352. throw new Exception(string.Format("Invalid order response: {0}", response));
  353. }
  354. }
  355. private async Task<byte[]> ReadBytesAsync(int count)
  356. {
  357. int totalBytesRead = 0;
  358. byte[] buffer = new byte[count];
  359. while (totalBytesRead < count)
  360. {
  361. int bytesRead = await _connectionStream.ReadAsync(buffer, totalBytesRead, count - totalBytesRead).ConfigureAwait(false);
  362. if (bytesRead == 0)
  363. throw new Exception("Connection closed unexpectedly");
  364. totalBytesRead += bytesRead;
  365. }
  366. return buffer;
  367. }
  368. private async Task<string> ReadMessageAsync()
  369. {
  370. byte[] buffer = await ReadBytesAsync(2).ConfigureAwait(false);
  371. int size = buffer[0] * 256 + buffer[1];
  372. if (size <= 0)
  373. {
  374. throw new Exception("Invalid message size");
  375. }
  376. return Encoding.ASCII.GetString(await ReadBytesAsync(size).ConfigureAwait(false));
  377. }
  378. public int ReceiveTimeout { get; set; }
  379. public int SendTimeout { get; set; }
  380. private async Task WriteMessageAsync(MessageBuilder message)
  381. {
  382. byte[] data = message.GetBytes();
  383. await _connectionStream.WriteAsync(data, 0, data.Length).ConfigureAwait(false);
  384. }
  385. }
  386. }