Skip to content

Commit

Permalink
177/cli add ons (#418)
Browse files Browse the repository at this point in the history
* cli login

* cli search

* f

* r

---------

Co-authored-by: jer\tsahi_a <[email protected]>
  • Loading branch information
atias007 and customs-il authored Sep 1, 2024
1 parent 4e5090e commit 9e733d7
Show file tree
Hide file tree
Showing 11 changed files with 125 additions and 73 deletions.
16 changes: 8 additions & 8 deletions src/Planar.CLI/Actions/BaseCliAction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -438,21 +438,21 @@ protected static void AssertUpdated(string? id, string entity)
}
}

protected static string? PromptSelection(IEnumerable<string>? items, string title, bool addCancelOption = true)
protected static string? PromptSelection(IEnumerable<string>? items, string title)
{
return CliPromptUtil.PromptSelection(items, title, addCancelOption);
return CliPromptUtil.PromptSelection(items, title);
}

protected static CliSelectItem<T>? PromptSelection<T>(IEnumerable<CliSelectItem<T>>? items, string title, bool addCancelOption = true)
protected static CliSelectItem<T>? PromptSelection<T>(IEnumerable<CliSelectItem<T>>? items, string title)
{
return CliPromptUtil.PromptSelection<T>(items, title, addCancelOption);
return CliPromptUtil.PromptSelection(items, title);
}

protected static TEnum PromptSelection<TEnum>(string title, bool addCancelOption = true)
protected static TEnum PromptSelection<TEnum>(string title)
where TEnum : struct, Enum
{
var items = Enum.GetNames<TEnum>().Select(e => e.ToLower());
var result = CliPromptUtil.PromptSelection(items, title, addCancelOption);
var result = CliPromptUtil.PromptSelection(items, title);
return Enum.Parse<TEnum>(result!, true);
}

Expand All @@ -465,7 +465,7 @@ protected static bool ConfirmAction(string title)
protected static int GetCounterHours()
{
var items = new[] { "1 hour", "2 hours", "8 hours", "1 day", "2 days", "3 days", "7 days" };
var select = PromptSelection(items, "select time period", true);
var select = PromptSelection(items, "select time period");
if (string.IsNullOrEmpty(select)) { return 0; }
var parts = select.Split(' ');
if (parts.Length != 2) { return 0; }
Expand All @@ -489,7 +489,7 @@ protected static void FillDatesScope(ICliDateScope request)
private static (DateTime?, DateTime?) GetDateScope()
{
var items = new[] { "today", "yesterday", "this week", "last week", "this month", "last month", "this year", "last year", "since forever", "custom..." };
var select = PromptSelection(items, "select date period", true);
var select = PromptSelection(items, "select date period");

if (string.Equals(select, "custom...", StringComparison.OrdinalIgnoreCase))
{
Expand Down
1 change: 0 additions & 1 deletion src/Planar.CLI/Actions/MonitorCliActions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,6 @@ private static string GetEventForTest()
private static string? GetEventArguments(string eventName)
{
var result = MonitorEventsExtensions.IsMonitorEventHasArguments(eventName) ?
//AnsiConsole.Prompt(new TextPrompt<string>("[turquoise2] > event argument:[/]").AllowEmpty()) :
PickEventArgument(eventName) :
null;

Expand Down
28 changes: 23 additions & 5 deletions src/Planar.CLI/Actions/ServiceCliActions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Planar.CLI.General;
using Planar.CLI.Proxy;
using RestSharp;
using Spectre.Console;
using System;
using System.Collections.Generic;
using System.IO;
Expand Down Expand Up @@ -85,8 +86,17 @@ public static async Task<CliActionResponse> GetVersion(CancellationToken cancell
[Action("health-check")]
public static async Task<CliActionResponse> HealthCheck(CancellationToken cancellationToken = default)
{
const string seperator = "-------------------";
var restRequest = new RestRequest("service/health-check", Method.Get);
var result = await RestProxy.Invoke<string>(restRequest, cancellationToken);
if (result.IsSuccessful)
{
AnsiConsole.MarkupLine($"{seperator}\r\n[green]planar is healthy[/]\r\n{seperator}");
}
else
{
AnsiConsole.MarkupLine($"{seperator}\r\n[red]planar is unhealthy[/]\r\n{seperator}");
}
return new CliActionResponse(result, result.Data);
}

Expand Down Expand Up @@ -119,6 +129,7 @@ public static async Task<CliActionResponse> GetAllCalendars(CancellationToken ca
public static async Task<CliActionResponse> Login(CliLoginRequest request, CancellationToken cancellationToken = default)
{
var notnullRequest = FillLoginRequest(request);
if (request.Port == 0) { request.Port = ConnectUtil.GetDefaultPort(); }
var response = await InnerLogin(notnullRequest, cancellationToken);
if (response.Response.IsSuccessful)
{
Expand Down Expand Up @@ -157,7 +168,7 @@ public static async Task<CliActionResponse> LoginColor(CliLoginColorRequest requ
{
var colorType = typeof(CliColors);
var options = CliActionMetadata.GetEnumOptions(colorType);
var colorText = PromptSelection(options, "color", true);
var colorText = PromptSelection(options, "color");
var parse = CliArgumentsUtil.ParseEnum(colorType, colorText);
if (parse != null)
{
Expand Down Expand Up @@ -207,7 +218,7 @@ public static async Task<CliActionResponse> GetWorkingHours(CliGetWorkingHoursRe

if (result.Data.Count() > 1)
{
var calendar = PromptSelection(result.Data.Select(r => r.CalendarName), "calendar", addCancelOption: true);
var calendar = PromptSelection(result.Data.Select(r => r.CalendarName), "calendar");
data = result.Data.FirstOrDefault(r => r.CalendarName == calendar);
}
else
Expand Down Expand Up @@ -311,15 +322,22 @@ Then set the key in environment variable (i.e. setx {Consts.CryptographyKeyVaria

public static async Task InitializeLogin()
{
var request = ConnectUtil.GetLastLoginRequestWithCredentials();
var request = ConnectUtil.GetLastLoginRequestWithRemember();
if (request == null)
{
SetDefaultAnonymousLogin();
Console.Title = $"{CliConsts.Title} ({CliConsts.Anonymous})";
}
else
{
await InnerLogin(request);
var response = await InnerLogin(request);
if (!response.Response.IsSuccessful && response.Response.StatusCode != HttpStatusCode.Conflict)
{
RestProxy.Host = request.Host;
RestProxy.Port = request.Port;
RestProxy.SecureProtocol = request.SecureProtocol;
RestProxy.Flush();
}
}
}

Expand Down Expand Up @@ -368,7 +386,7 @@ private static CliLoginRequest FillLoginRequest(CliLoginRequest? request)

if (request.Port == 0)
{
request.Port = int.Parse(CollectCliValue("port", true, 1, 5, regexTepmplate, "invalid port", ConnectUtil.DefaultPort.ToString()) ?? ConnectUtil.DefaultPort.ToString());
request.Port = int.Parse(CollectCliValue("port", true, 1, 5, regexTepmplate, "invalid port", ConnectUtil.GetDefaultPort().ToString()) ?? ConnectUtil.GetDefaultPort().ToString());
}

if (string.IsNullOrEmpty(request.Username))
Expand Down
56 changes: 26 additions & 30 deletions src/Planar.CLI/CliGeneral/CliPromptUtil.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Planar.API.Common.Entities;
using Planar.CLI.Actions;
using Planar.CLI.General;
using Planar.CLI.Proxy;
using RestSharp;
Expand All @@ -16,36 +15,33 @@ namespace Planar.CLI.CliGeneral
{
internal static class CliPromptUtil
{
internal static string? PromptSelection(IEnumerable<string>? items, string title, bool addCancelOption = true)
internal static string? PromptSelection(IEnumerable<string>? items, string title)
{
if (items == null) { return null; }

var finalItems = items.Select(i => new CliSelectItem<string> { DisplayName = i, Value = i });
return PromptSelection(finalItems, title, addCancelOption)?.Value;
return PromptSelection(finalItems, title)?.Value;
}

internal static CliSelectItem<T>? PromptSelection<T>(IEnumerable<CliSelectItem<T>>? items, string title, bool addCancelOption = true)
internal static CliSelectItem<T>? PromptSelection<T>(IEnumerable<CliSelectItem<T>>? items, string title)
{
if (items == null) { return null; }
IEnumerable<CliSelectItem<T>> finalItems;
if (addCancelOption)
{
var temp = items.ToList();
temp.Add(CliSelectItem<T>.CancelItem);
finalItems = temp;
}
else
{
finalItems = items;
}
var finalItems = items.ToList();
var addSearch = finalItems.Count > 5;
finalItems.Add(CliSelectItem<T>.CancelItem);

using var _ = new TokenBlockerScope();
var selectedItem = AnsiConsole.Prompt(
new SelectionPrompt<CliSelectItem<T>>()
var prompt = new SelectionPrompt<CliSelectItem<T>>()
.Title($"[underline][gray]select [/][white]{title?.EscapeMarkup()}[/][gray] from the following list (press [/][blue]enter[/][gray] to select):[/][/]")
.PageSize(20)
.MoreChoicesText($"[grey](Move [/][blue]up[/][grey] and [/][blue]down[/] [grey]to reveal more [/][white]{title?.EscapeMarkup()}s[/])")
.AddChoices(finalItems));
.AddChoices(finalItems);
if (addSearch)
{
prompt.EnableSearch();
prompt.SearchHighlightStyle = new Style(foreground: Color.White, background: Color.DeepSkyBlue4_2);
}
var selectedItem = AnsiConsole.Prompt(prompt);

CheckForCancelOption(selectedItem);

Expand All @@ -68,7 +64,7 @@ internal static async Task<CliPromptWrapper<string>> NewHooks(CancellationToken
}

var items = data.Select(g => g ?? string.Empty);
var select = PromptSelection(items, "new hook", addCancelOption: true);
var select = PromptSelection(items, "new hook");
return new CliPromptWrapper<string>(select);
}

Expand All @@ -91,7 +87,7 @@ internal static async Task<CliPromptWrapper<string>> ExternalHooks(CancellationT
.Where(h => string.Equals(h.HookType, "external", StringComparison.OrdinalIgnoreCase))
.Select(g => g.Name ?? string.Empty);

var select = PromptSelection(items, "hook", addCancelOption: true);
var select = PromptSelection(items, "hook");
return new CliPromptWrapper<string>(select);
}

Expand All @@ -113,7 +109,7 @@ internal static async Task<CliPromptWrapper<string>> Groups(CancellationToken ca
}

var items = data.Select(g => g.Name ?? string.Empty);
var select = PromptSelection(items, "group", true);
var select = PromptSelection(items, "group");
return new CliPromptWrapper<string>(select);
}

Expand All @@ -133,7 +129,7 @@ internal static async Task<CliPromptWrapper<string>> GroupsForUser(string userna
throw new CliWarningException("no available groups to perform the opertaion");
}

var select = PromptSelection(items, "group", true);
var select = PromptSelection(items, "group");
return new CliPromptWrapper<string>(select);
}

Expand Down Expand Up @@ -173,7 +169,7 @@ internal static async Task<CliPromptWrapper<string>> GroupsWithoutUser(string us
throw new CliWarningException("no available groups to perform the opertaion");
}

var select = PromptSelection(items, "group", true);
var select = PromptSelection(items, "group");
return new CliPromptWrapper<string>(select);
}

Expand All @@ -194,7 +190,7 @@ internal static async Task<CliPromptWrapper<string>> Users(CancellationToken can
}

var items = data.Select(g => g.Username ?? string.Empty);
var select = PromptSelection(items, "user", true);
var select = PromptSelection(items, "user");
return new CliPromptWrapper<string>(select);
}

Expand All @@ -215,7 +211,7 @@ internal static async Task<CliPromptWrapper<string>> UsersInGroup(string groupNa
throw new CliWarningException("no available users to perform the opertaion");
}

var select = PromptSelection(items, "user", true);
var select = PromptSelection(items, "user");
return new CliPromptWrapper<string>(select);
}

Expand Down Expand Up @@ -255,7 +251,7 @@ internal static async Task<CliPromptWrapper<string>> UsersNotInGroup(string grou
throw new CliWarningException("no available users to perform the opertaion");
}

var select = PromptSelection(items, "user", true);
var select = PromptSelection(items, "user");
return new CliPromptWrapper<string>(select);
}

Expand All @@ -274,7 +270,7 @@ internal static async Task<CliPromptWrapper<string>> Reports(CancellationToken c
throw new CliWarningException("no available reports to perform the opertaion");
}

var select = PromptSelection(data, "report", true);
var select = PromptSelection(data, "report");
return new CliPromptWrapper<string>(select);
}

Expand All @@ -295,7 +291,7 @@ internal static async Task<CliPromptWrapper<MonitorItem>> Monitors(CancellationT
}

var prompt = data.Select(data => $"{data.Id} - {data.Title}");
var select = PromptSelection(prompt, "monitor", true);
var select = PromptSelection(prompt, "monitor");
var id = select?.Split('-').FirstOrDefault()?.Trim();
_ = int.TryParse(id, out var monitorId);
var item = data.First(data => data.Id == monitorId);
Expand All @@ -317,7 +313,7 @@ internal static async Task<CliPromptWrapper<string>> ReportPeriods(CancellationT
throw new CliWarningException("no available periods to perform the opertaion");
}

var select = PromptSelection(data, "period", true);
var select = PromptSelection(data, "period");
return new CliPromptWrapper<string>(select);
}

Expand All @@ -336,7 +332,7 @@ internal static async Task<CliPromptWrapper<Roles>> Roles(CancellationToken canc
}

var items = result.Data.Select(g => g ?? string.Empty);
var select = PromptSelection(items, "role", true);
var select = PromptSelection(items, "role");

if (!Enum.TryParse<Roles>(select, ignoreCase: true, out var enumSelect))
{
Expand Down
3 changes: 2 additions & 1 deletion src/Planar.CLI/CliGeneral/CliTableExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,8 @@ public static CliTable GetTable(PagingResponse<JobBasicDetails>? response)
var table = new CliTable(paging: response, entityName: "job");
table.Table.AddColumns("Job Id", "Job Key", "Job Type", "Description");
if (response == null || response.Data == null) { return table; }
response.Data.ForEach(r => table.Table.AddRow(CliTableFormat.FormatJobId(r.Id, r.Active), CliTableFormat.FormatJobKey(r.Group, r.Name), r.JobType.EscapeMarkup(), LimitValue(r.Description)));
var hasInactive = response.Data.Exists(d => d.Active != JobActiveMembers.Active);
response.Data.ForEach(r => table.Table.AddRow(hasInactive ? CliTableFormat.FormatJobId(r.Id, r.Active) : r.Id, CliTableFormat.FormatJobKey(r.Group, r.Name), r.JobType.EscapeMarkup(), LimitValue(r.Description)));
return table;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Planar.CLI/CliGeneral/CliTableFormat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ public static string GetStatusMarkup(int status, bool hasWarning)
var result = GetStatusMarkup(status);
if (hasWarning)
{
result = $"{result}[{CliFormat.WarningColor}]{bullet}[/]";
result = $"{result} [{CliFormat.WarningColor}]{bullet}[/]";
}

return result;
Expand Down
24 changes: 18 additions & 6 deletions src/Planar.CLI/DataProtect/ConnectUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,28 +14,40 @@ namespace Planar.CLI.DataProtect
public static class ConnectUtil
{
public const string DefaultHost = "localhost";
public const int DefaultPort = 2306;
public const int DefaultSecurePort = 2610;
private const int DefaultPort = 2306;
private const int DefaultSecurePort = 2610;

static ConnectUtil()
{
InitializeMetadataFolder();
Load();
}

public static int GetDefaultPort()
{
if (Current.SecureProtocol)
{
return DefaultSecurePort;
}
else
{
return DefaultPort;
}
}

public static CliLoginRequest Current { get; private set; } = new CliLoginRequest();

private static UserMetadata Data { get; set; } = new();

private static string MetadataFilename { get; set; } = string.Empty;

public static CliLoginRequest? GetLastLoginRequestWithCredentials()
public static CliLoginRequest? GetLastLoginRequestWithRemember()
{
try
{
LogoutOldItems();
var last = Data.Logins
.Where(l => l.HasCredentials)
.Where(l => l.Remember)
.OrderByDescending(l => l.ConnectDate)
.FirstOrDefault();

Expand Down Expand Up @@ -151,7 +163,7 @@ public static void SaveLoginRequest(CliLoginRequest request, string? token)
private static void LogoutOldItems()
{
var old = Data.Logins.Where(l => l.Deprecated).ToList();
old.ForEach(o => Logout(o));
old.ForEach(Logout);
Save();
}

Expand Down Expand Up @@ -217,7 +229,7 @@ private static void Load()
var protector = GetProtector();
text = protector.Unprotect(text);
Data = JsonConvert.DeserializeObject<UserMetadata>(text) ?? new UserMetadata();
if (Data.Logins == null) { Data.Logins = new List<LoginData>(); }
if (Data.Logins == null) { Data.Logins = []; }
LogoutOldItems();
}
catch (Exception ex)
Expand Down
2 changes: 1 addition & 1 deletion src/Planar.CLI/Proxy/RestProxy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ internal static class RestProxy
{
public static bool SecureProtocol { get; set; }
public static string Host { get; set; } = ConnectUtil.DefaultHost;
public static int Port { get; set; } = ConnectUtil.DefaultPort;
public static int Port { get; set; } = ConnectUtil.GetDefaultPort();

private static RestClient? _client;
private static readonly object _lock = new();
Expand Down
Loading

0 comments on commit 9e733d7

Please sign in to comment.