summaryrefslogtreecommitdiffstats
path: root/src/main.lib/Services/InputService.cs
blob: 829cf5ed03b5ee9e6e70df3b9c3793779be83666 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PKISharp.WACS.Services
{
    public class InputService : IInputService
    {
        private readonly IArgumentsService _arguments;
        private readonly ILogService _log;
        private readonly ISettingsService _settings;
        private const string _cancelCommand = "C";
        private bool _dirty;

        public InputService(IArgumentsService arguments, ISettingsService settings, ILogService log)
        {
            _log = log;
            _arguments = arguments;
            _settings = settings;
        }

        private void Validate(string what)
        {
            if (_arguments.MainArguments.Renew && !_arguments.MainArguments.Test)
            {
                throw new Exception($"User input '{what}' should not be needed in --renew mode.");
            }
        }

        public void CreateSpace()
        {
            if (_log.Dirty || _dirty)
            {
                _log.Dirty = false;
                _dirty = false;
                Console.WriteLine();
            }
        }

        public Task<bool> Continue(string message = "Press <Space> to continue...")
        {
            Validate(message);
            CreateSpace();
            Console.Write($" {message} ");
            while (true)
            {
                var response = Console.ReadKey(true);
                switch (response.Key)
                {
                    case ConsoleKey.Spacebar:
                        Console.SetCursorPosition(0, Console.CursorTop);
                        Console.Write(new string(' ', Console.WindowWidth));
                        Console.SetCursorPosition(0, Console.CursorTop);
                        return Task.FromResult(true);
                }
            }
        }

        public Task<bool> Wait(string message = "Press <Enter> to continue...")
        {
            Validate(message);
            CreateSpace();
            Console.Write($" {message} ");
            while (true)
            {
                var response = Console.ReadKey(true);
                switch (response.Key)
                {
                    case ConsoleKey.Enter:
                        Console.WriteLine();
                        Console.WriteLine();
                        return Task.FromResult(true);
                    case ConsoleKey.Escape:
                        Console.WriteLine();
                        Console.WriteLine();
                        return Task.FromResult(false);
                }
            }
        }

        public async Task<string> RequestString(string[] what)
        {
            if (what != null)
            {
                CreateSpace();
                Console.ForegroundColor = ConsoleColor.Green;
                for (var i = 0; i < what.Length - 1; i++)
                {
                    Console.WriteLine($" {what[i]}");
                }
                Console.ResetColor();
                return await RequestString(what[^1]);
            }
            return "";
        }

        public void Show(string? label, string? value, int level = 0)
        {
            var hasLabel = !string.IsNullOrEmpty(label);
            if (hasLabel)
            {
                Console.ForegroundColor = ConsoleColor.White;
                if (level > 0)
                {
                    Console.Write($"  - {label}");
                }
                else
                {
                    Console.Write($" {label}");
                }
                Console.ResetColor();
            }

            if (!string.IsNullOrWhiteSpace(value))
            {
                if (hasLabel)
                {
                    Console.Write(":");
                }
                WriteMultiline(hasLabel ? 20 : 0, value);
            }
            else
            {
                if (!Console.IsOutputRedirected)
                {
                    Console.SetCursorPosition(15, Console.CursorTop);
                }
                Console.WriteLine($"-----------------------------------------------------------------");
            }

            _dirty = true;
        }

        private void WriteMultiline(int startPos, string value)
        {
            var step = 79 - startPos;
            var pos = 0;
            var words = value.Split(' ');
            while (pos < words.Length)
            {
                var line = "";
                if (words[pos].Length + 1 >= step)
                {
                    line = words[pos++];
                }
                else
                {
                    while (pos < words.Length && line.Length + words[pos].Length + 1 < step)
                    {
                        line += " " + words[pos++];
                    }
                }
                if (!Console.IsOutputRedirected)
                {
                    Console.SetCursorPosition(startPos, Console.CursorTop);
                }
                Console.WriteLine($" {line}");
            }
        }

        public Task<string> RequestString(string what)
        {
            Validate(what);
            CreateSpace();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write($" {what}: ");
            Console.ResetColor();

            // Copied from http://stackoverflow.com/a/16638000
            var bufferSize = 16384;
            var inputStream = Console.OpenStandardInput(bufferSize);
            Console.SetIn(new StreamReader(inputStream, Console.InputEncoding, false, bufferSize));

            int top = default;
            int left = default;
            if (!Console.IsOutputRedirected)
            {
                top = Console.CursorTop;
                left = Console.CursorLeft;
            }

            var answer = Console.ReadLine();
            if (string.IsNullOrWhiteSpace(answer))
            {
                if (!Console.IsOutputRedirected)
                {
                    Console.SetCursorPosition(left, top);
                }
                Console.WriteLine("<Enter>");
                Console.WriteLine();
                return Task.FromResult(string.Empty);
            }
            else
            {
                Console.WriteLine();
                return Task.FromResult(answer.Trim());
            }
        }

        public Task<bool> PromptYesNo(string message, bool defaultChoice)
        {
            Validate(message);
            CreateSpace();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write($" {message} ");
            Console.ForegroundColor = ConsoleColor.Yellow;
            if (defaultChoice)
            {
                Console.Write($"(y*/n) ");
            }
            else
            {
                Console.Write($"(y/n*) ");
            }
            Console.ResetColor();
            while (true)
            {
                var response = Console.ReadKey(true);
                switch (response.Key)
                {
                    case ConsoleKey.Y:
                        Console.WriteLine(" - yes");
                        Console.WriteLine();
                        return Task.FromResult(true);
                    case ConsoleKey.N:
                        Console.WriteLine(" - no");
                        Console.WriteLine();
                        return Task.FromResult(false);
                    case ConsoleKey.Enter:
                        Console.WriteLine($" - <Enter>");
                        Console.WriteLine();
                        return Task.FromResult(defaultChoice);
                }
            }
        }

        // Replaces the characters of the typed in password with asterisks
        // More info: http://rajeshbailwal.blogspot.com/2012/03/password-in-c-console-application.html
        public async Task<string?> ReadPassword(string what)
        {
            Validate(what);
            CreateSpace();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write($" {what}: ");
            Console.ResetColor();
            var password = new StringBuilder();
            try
            {
                var info = Console.ReadKey(true);
                while (info.Key != ConsoleKey.Enter)
                {
                    if (info.Key != ConsoleKey.Backspace)
                    {
                        Console.Write("*");
                        password.Append(info.KeyChar);
                    }
                    else if (info.Key == ConsoleKey.Backspace)
                    {
                        if (password.Length > 0)
                        {
                            // remove one character from the list of password characters
                            password.Remove(password.Length - 1, 1);
                            // get the location of the cursor
                            var pos = Console.CursorLeft;
                            // move the cursor to the left by one character
                            Console.SetCursorPosition(pos - 1, Console.CursorTop);
                            // replace it with space
                            Console.Write(" ");
                            // move the cursor to the left by one character again
                            Console.SetCursorPosition(pos - 1, Console.CursorTop);
                        }
                    }
                    info = Console.ReadKey(true);
                }
                // add a new line because user pressed enter at the end of their password
                Console.WriteLine();
                // add another new line to keep a clean break with following log messages
                Console.WriteLine();
            }
            catch (Exception ex)
            {
                _log.Error("Error reading Password: {@ex}", ex);
            }

            // Return null instead of emtpy string to save storage
            var ret = password.ToString();
            if (string.IsNullOrEmpty(ret))
            {
                return null;
            }
            else
            {
                return ret;
            }
        }

        /// <summary>
        /// Version of the picker where null may be returned
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="what"></param>
        /// <param name="options"></param>
        /// <param name="creator"></param>
        /// <param name="nullLabel"></param>
        /// <returns></returns>
        public async Task<TResult?> ChooseOptional<TSource, TResult>(
            string what, IEnumerable<TSource> options,
            Func<TSource, Choice<TResult?>> creator,
            string nullLabel) where TResult : class
        {
            var baseChoices = options.Select(creator).ToList();
            if (!baseChoices.Any(x => !x.Disabled))
            {
                _log.Warning("No options available");
                return default;
            }
            var defaults = baseChoices.Where(x => x.Default);
            var cancel = Choice.Create(default(TResult), nullLabel, _cancelCommand);
            if (defaults.Count() == 0)
            {
                cancel.Command = "<Enter>";
                cancel.Default = true;
            }
            baseChoices.Add(cancel);
            return await ChooseFromMenu(what, baseChoices);
        }

        /// <summary>
        /// Print a (paged) list of targets for the user to choose from
        /// </summary>
        /// <param name="targets"></param>
        public async Task<T> ChooseRequired<S, T>(
            string what, 
            IEnumerable<S> options, 
            Func<S, Choice<T>> creator) 
        {
            var baseChoices = options.Select(creator).ToList();
            if (!baseChoices.Any(x => !x.Disabled))
            {
                throw new Exception("No options available for required choice");
            }
            return await ChooseFromMenu(what, baseChoices);
        }

        /// <summary>
        /// Print a (paged) list of choices for the user to choose from
        /// </summary>
        /// <param name="choices"></param>
        public async Task<T> ChooseFromMenu<T>(string what, List<Choice<T>> choices, Func<string, Choice<T>>? unexpected = null)
        {
            if (!choices.Any())
            {
                throw new Exception("No options available");
            }
            var defaults = choices.Where(x => x.Default);
            if (defaults.Count() > 1)
            {
                throw new Exception("Multiple defaults provided");
            }
            else if (defaults.Count() == 1 && defaults.First().Disabled)
            {
                throw new Exception("Default option is disabled");
            }

            await WritePagedList(choices);

            Choice<T>? selected = null;
            do
            {
                var choice = await RequestString(what);
                if (string.IsNullOrWhiteSpace(choice))
                {
                    selected = choices.
                        Where(c => c.Default).
                        FirstOrDefault();
                }
                else
                {
                    selected = choices.
                        Where(t => string.Equals(t.Command, choice, StringComparison.InvariantCultureIgnoreCase)).
                        FirstOrDefault();

                    if (selected == null)
                    {
                        selected = choices.
                            Where(t => string.Equals(t.Description, choice, StringComparison.InvariantCultureIgnoreCase)).
                            FirstOrDefault();
                    }

                    if (selected != null && selected.Disabled)
                    {
                        var disabledReason = selected.DisabledReason ?? "Run as Administator to enable all features.";
                        _log.Warning($"The option you have chosen is currently disabled. {disabledReason}");
                        selected = null;
                    }

                    if (selected == null && unexpected != null)
                    {
                        selected = unexpected(choice);
                    }
                }
            } while (selected == null);
            return selected.Item;
        }

        /// <summary>
        /// Print a (paged) list of targets for the user to choose from
        /// </summary>
        /// <param name="listItems"></param>
        public async Task WritePagedList(IEnumerable<Choice> listItems)
        {
            var currentIndex = 0;
            var currentPage = 0;
            CreateSpace();
            if (listItems.Count() == 0)
            {
                Console.WriteLine($" [empty] ");
                Console.WriteLine();
                return;
            }

            while (currentIndex <= listItems.Count() - 1)
            {
                // Paging
                if (currentIndex > 0)
                {
                    if (await Continue())
                    {
                        currentPage += 1;
                    }
                    else
                    {
                        return;
                    }
                }
                var page = listItems.
                    Skip(currentPage * _settings.UI.PageSize).
                    Take(_settings.UI.PageSize);
                foreach (var target in page)
                {
                    if (target.Command == null)
                    {
                        target.Command = (currentIndex + 1).ToString();
                    }

                    if (!string.IsNullOrEmpty(target.Command))
                    {
                        Console.ForegroundColor = target.Default ? 
                            ConsoleColor.Green : 
                            target.Disabled ?
                                ConsoleColor.DarkGray : 
                                ConsoleColor.White;
                        Console.Write($" {target.Command}: ");
                        Console.ResetColor();
                    }
                    else
                    {
                        Console.Write($" * ");
                    }

                    if (target.Disabled)
                    {
                        Console.ForegroundColor = ConsoleColor.DarkGray;
                    } 
                    else if (target.Color.HasValue)
                    {
                        Console.ForegroundColor = target.Color.Value;
                    }
                    Console.WriteLine(target.Description);
                    Console.ResetColor();
                    currentIndex++;
                }
            }
            Console.WriteLine();
        }

        public string FormatDate(DateTime date) => date.ToString(_settings.UI.DateFormat);
    }

}