ソースを参照

Add re-export functionality.

Andrew Klopper 8 年 前
コミット
fd70936c40
共有3 個のファイルを変更した94 個の追加36 個の削除を含む
  1. 25 1
      BulkPrintingAPI/Controllers/BatchesController.cs
  2. 58 35
      MAXClient/Client.cs
  3. 11 0
      MAXClient/Utils.cs

+ 25 - 1
BulkPrintingAPI/Controllers/BatchesController.cs

@@ -6,7 +6,6 @@ using Microsoft.EntityFrameworkCore;
6 6
 using Microsoft.Extensions.Caching.Memory;
7 7
 using Microsoft.Extensions.Logging;
8 8
 using System;
9
-using System.Collections.Generic;
10 9
 using System.ComponentModel.DataAnnotations;
11 10
 using System.Linq;
12 11
 using System.Threading.Tasks;
@@ -168,5 +167,30 @@ namespace BulkPrintingAPI.Controllers
168 167
 
169 168
             return Ok(orderResponse);
170 169
         }
170
+
171
+        [HttpPost("{id}/a8a7b01e-9da9-4353-ad5c-f47d83d83065")]
172
+        public async Task<IActionResult> ReExportBatchAsync([FromRoute] int id)
173
+        {
174
+            var credentials = await Utils.GetLoginCredentialsFromRequestAsync(HttpContext, _context);
175
+
176
+            var batch = await BatchesForVendor(credentials.Vendor.Id)
177
+                .SingleOrDefaultAsync(m => m.Id == id);
178
+            if (batch == null)
179
+            {
180
+                return NotFound();
181
+            }
182
+            else
183
+            {
184
+                await _context.Database.ExecuteSqlCommandAsync("DELETE FROM [Vouchers] WHERE [BatchId]={0}",
185
+                    System.Threading.CancellationToken.None, id);
186
+
187
+                batch.ReadyForDownload = false;
188
+                await _context.SaveChangesAsync();
189
+
190
+                await MAX.Utils.ReExportBatchAsync(_clientFactory, _logger, credentials, id,
191
+                    Utils.AesDecryptBytes(credentials.Vendor.EncryptedVoucherKey, _dataEncryptionOptions.DefaultKey));
192
+            }
193
+            return Ok();
194
+        }
171 195
     }
172 196
 }

+ 58 - 35
MAXClient/Client.cs

@@ -261,6 +261,32 @@ namespace MAX
261 261
             }
262 262
         }
263 263
 
264
+
265
+        private string ExpectResponse(string response, string prefix)
266
+        {
267
+            if (response.StartsWith("ER"))
268
+            {
269
+                var parts = response.Split('|');
270
+                int errorCode;
271
+                if ((parts.Length < 2) || !int.TryParse(parts[1], out errorCode))
272
+                {
273
+                    errorCode = -1;
274
+                }
275
+                var message = parts.Length >= 3 ? parts[2] : String.Format("Malformed server error: {0}", response);
276
+                _logger.LogError("MAX Error for {0}: {1} (code {2})",
277
+                    LoginCredentials.Format(_userId, _username, _vendorId, _serialNumber), message, errorCode);
278
+                throw new MAXException(errorCode, message);
279
+            }
280
+            else if (!response.StartsWith(prefix))
281
+            {
282
+                _logger.LogError("Invalid MAX response for {0}: {1}",
283
+                    LoginCredentials.Format(_userId, _username, _vendorId, _serialNumber),
284
+                    response);
285
+                throw new Exception(String.Format("Invalid server response: {0}", response));
286
+            }
287
+            return response;
288
+        }
289
+
264 290
         public async Task<Account> GetAccountAsync()
265 291
         {
266 292
             await WriteMessageAsync(new MessageBuilder().Append("Acc")).ConfigureAwait(false);
@@ -322,19 +348,6 @@ namespace MAX
322 348
             return catalogue;
323 349
         }
324 350
 
325
-        private void ThrowParseError(string value, string valueName, string valueType, string fullResponse)
326
-        {
327
-            _logger.LogError(
328
-                "Failed to parse value: valueType={0} valueName={1} value={2} fullResponse={3} {4}",
329
-                valueType,
330
-                valueName,
331
-                value,
332
-                fullResponse,
333
-                LoginCredentials.Format(_userId, _username, _vendorId, _serialNumber)
334
-            );
335
-            throw new Exception(String.Format("Invalid value for {0}", valueName));
336
-        }
337
-
338 351
         private bool ParseBool(string value, string valueName, string fullResponse)
339 352
         {
340 353
             bool ret;
@@ -489,31 +502,41 @@ namespace MAX
489 502
 
490 503
         public int ReceiveTimeout { get; set; }
491 504
 
492
-        public int SendTimeout { get; set; }
493
-
494
-        private string ExpectResponse(string response, string prefix)
505
+        public async Task ReExportBatchAsync(int batchId, byte[] key)
495 506
         {
496
-            if (response.StartsWith("ER"))
497
-            {
498
-                var parts = response.Split('|');
499
-                int errorCode;
500
-                if ((parts.Length < 2) || ! int.TryParse(parts[1], out errorCode))
501
-                {
502
-                    errorCode = -1;
503
-                }
504
-                var message = parts.Length >= 3 ? parts[2] : String.Format("Malformed server error: {0}", response);
505
-                _logger.LogError("MAX Error for {0}: {1} (code {2})",
506
-                    LoginCredentials.Format(_userId, _username, _vendorId, _serialNumber), message, errorCode);
507
-                throw new MAXException(errorCode, message);
508
-            }
509
-            else if (! response.StartsWith(prefix))
507
+            if (key.Length != 24)
510 508
             {
511
-                _logger.LogError("Invalid MAX response for {0}: {1}",
512
-                    LoginCredentials.Format(_userId, _username, _vendorId, _serialNumber),
513
-                    response);
514
-                throw new Exception(String.Format("Invalid server response: {0}", response));
509
+                throw new ArgumentException("24 byte key expected", nameof(key));
515 510
             }
516
-            return response;
511
+
512
+            await WriteMessageAsync(new MessageBuilder()
513
+                .Append("ReExport ")
514
+                .Append(Encrypt(new StringBuilder()
515
+                    .Append(batchId)
516
+                    .Append("|2|") // EncType: 0:None, 1:DES, 2:Triple DES
517
+                    .Append(BitConverter.ToString(key, 0, 8).Replace("-", ""))
518
+                    .Append("|")
519
+                    .Append(BitConverter.ToString(key, 8, 8).Replace("-", ""))
520
+                    .Append("|")
521
+                    .Append(BitConverter.ToString(key, 16, 8).Replace("-", ""))
522
+                    .ToString()))).ConfigureAwait(false);
523
+
524
+            ExpectResponse(Decrypt(await ReadMessageAsync().ConfigureAwait(false)), "OK");
525
+        }
526
+
527
+        public int SendTimeout { get; set; }
528
+
529
+        private void ThrowParseError(string value, string valueName, string valueType, string fullResponse)
530
+        {
531
+            _logger.LogError(
532
+                "Failed to parse value: valueType={0} valueName={1} value={2} fullResponse={3} {4}",
533
+                valueType,
534
+                valueName,
535
+                value,
536
+                fullResponse,
537
+                LoginCredentials.Format(_userId, _username, _vendorId, _serialNumber)
538
+            );
539
+            throw new Exception(String.Format("Invalid value for {0}", valueName));
517 540
         }
518 541
 
519 542
         private async Task WriteMessageAsync(MessageBuilder message)

+ 11 - 0
MAXClient/Utils.cs

@@ -92,5 +92,16 @@ namespace MAX
92 92
                     product, quantity, customerReference, internalReference, orderGuid, key).ConfigureAwait(false);
93 93
             }
94 94
         }
95
+
96
+        public static async Task ReExportBatchAsync(
97
+            ClientFactory clientFactory, ILogger logger, LoginCredentials credentials,
98
+            int batchId, byte[] key)
99
+        {
100
+            using (var client = clientFactory.GetClient(logger, credentials))
101
+            {
102
+                await client.ConnectAsync().ConfigureAwait(false);
103
+                await client.ReExportBatchAsync(batchId, key).ConfigureAwait(false);
104
+            }
105
+        }
95 106
     }
96 107
 }