Skip to content

Commit

Permalink
Added Progressbar
Browse files Browse the repository at this point in the history
  • Loading branch information
DamianMorozov committed Feb 17, 2024
1 parent 0d30065 commit 87fb6c8
Show file tree
Hide file tree
Showing 67 changed files with 2,109 additions and 1,230 deletions.
60 changes: 42 additions & 18 deletions Clients/TgDownloaderConsole/Helpers/TgMenuHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,17 @@ internal void ShowTableDownload(TgDownloadSettingsModel tgDownloadSettings) =>
internal void ShowTableAdvanced(TgDownloadSettingsModel tgDownloadSettings) =>
ShowTableCore(tgDownloadSettings, TgLocale.MenuMainAdvanced, FillTableColumns, FillTableRowsAdvanced);

internal void ShowTableScanSources(TgDownloadSettingsModel tgDownloadSettings) =>
ShowTableCore(tgDownloadSettings, TgLocale.MenuMainDownload, FillTableColumns, FillTableRowsScanDownloadedSources);

internal void ShowTableViewSources(TgDownloadSettingsModel tgDownloadSettings) =>
ShowTableCore(tgDownloadSettings, TgLocale.MenuMainAdvanced, FillTableColumns, FillTableRowsViewDownloadedSources);

internal void ShowTableMarkHistoryReadProgress(TgDownloadSettingsModel tgDownloadSettings) =>
ShowTableCore(tgDownloadSettings, TgLocale.MenuMainAdvanced, FillTableColumns,
FillTableRowsMarkHistoryReadProgress);

internal void ShowTableMarkHistoryReadComplete(TgDownloadSettingsModel tgDownloadSettings) =>
ShowTableCore(tgDownloadSettings, TgLocale.MenuMainAdvanced, FillTableColumns,
FillTableRowsMarkHistoryReadComplete);

internal void FillTableColumns(Table table)
{
if (table.Columns.Count > 0)
Expand Down Expand Up @@ -259,6 +264,8 @@ internal void FillTableRowsClient(TgDownloadSettingsModel tgDownloadSettings, Ta
{
table.AddRow(new Markup(TgLocale.WarningMessage(TgLocale.TgClientException)),
new Markup(TgLog.GetMarkupString(TgClient.ClientException.Message)));
table.AddRow(new Markup(TgLocale.WarningMessage(TgLocale.TgClientFix)),
new Markup(TgLog.GetMarkupString(TgLocale.TgClientFixTryToDeleteSession)));
}
}

Expand All @@ -282,6 +289,28 @@ internal void FillTableRowsDownloadedSources(TgDownloadSettingsModel tgDownloadS
}
}

/// <summary>
/// Mark history read.
/// </summary>
/// <param name="tgDownloadSettings"></param>
/// <param name="table"></param>
internal void FillTableRowsMarkHistoryReadProgress(TgDownloadSettingsModel tgDownloadSettings, Table table)
{
table.AddRow(new Markup(TgLocale.InfoMessage(TgLocale.MenuMarkAllMessagesAsRead)),
new Markup($"{TgLocale.MenuClientProgress} ..."));
}

/// <summary>
/// Mark history read.
/// </summary>
/// <param name="tgDownloadSettings"></param>
/// <param name="table"></param>
internal void FillTableRowsMarkHistoryReadComplete(TgDownloadSettingsModel tgDownloadSettings, Table table)
{
table.AddRow(new Markup(TgLocale.InfoMessage(TgLocale.MenuMarkAllMessagesAsRead)),
new Markup($"{TgLocale.MenuClientComplete} ..."));
}

internal void FillTableRowsDownload(TgDownloadSettingsModel tgDownloadSettings, Table table)
{
// Download.
Expand Down Expand Up @@ -332,14 +361,6 @@ internal void FillTableRowsAdvanced(TgDownloadSettingsModel tgDownloadSettings,
new Markup(tgDownloadSettings.SourceVm.IsAutoUpdate.ToString()));
}

/// <summary>
/// Source ID/username.
/// </summary>
/// <param name="tgDownloadSettings"></param>
/// <param name="table"></param>
internal void FillTableRowsScanDownloadedSources(TgDownloadSettingsModel tgDownloadSettings, Table table) =>
FillTableRowsDownloadedSources(tgDownloadSettings, table);

/// <summary>
/// Source ID/username.
/// </summary>
Expand All @@ -364,20 +385,23 @@ public bool AskQuestionReturnNegative(string question, bool isTrueFirst = false)

public TgSqlTableSourceModel GetSourceFromEnumerable(string title, IEnumerable<TgSqlTableSourceModel> sources)
{
sources = sources.OrderBy(item => item.UserName).ThenBy(item => item.Id);
List<string> list = new() { TgLocale.MenuMainReturn };
sources = sources.OrderBy(x => x.UserName).ThenBy(x => x.Title);
List<string> list = [TgLocale.MenuMainReturn];
list.AddRange(sources.Select(source => TgLog.GetMarkupString(source.ToConsoleString())));
string sourceString = AnsiConsole.Prompt(new SelectionPrompt<string>()
.Title(title)
.PageSize(Console.WindowHeight - 17)
.AddChoices(list));
if (!Equals(sourceString, TgLocale.MenuMainReturn))
{
int len = sourceString.IndexOf('|', 8) - 9;
string sourceId = sourceString.Substring(8, len).TrimEnd(' ');
if (long.TryParse(sourceId, out long id))
return ContextManager.SourceRepository.GetAsync(id).Result;
}
string[] parts = sourceString.Split('|');
if (parts.Length > 3)
{
string sourceId = parts[2].TrimEnd(' ');
if (long.TryParse(sourceId, out long id))
return ContextManager.SourceRepository.GetAsync(id).Result;
}
}
return ContextManager.SourceRepository.GetNewAsync().Result;
}

Expand Down
251 changes: 210 additions & 41 deletions Clients/TgDownloaderConsole/Helpers/TgMenuHelperAction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,61 +24,230 @@ public bool CheckTgSettingsWithWarning(TgDownloadSettingsModel tgDownloadSetting
return result;
}

public void RunAction(TgDownloadSettingsModel tgDownloadSettings, Func<TgDownloadSettingsModel, Task> action,
private ProgressColumn[] GetProgressColumns() => new ProgressColumn[]
{
new TaskDescriptionColumn { Alignment = Justify.Left },
new ProgressBarColumn { Width = 25 },
new PercentageColumn(),
new DownloadedColumn { Culture = CultureInfo.InvariantCulture },
new TransferSpeedColumn { Culture = CultureInfo.InvariantCulture }
};


public void RunActionProgress(TgDownloadSettingsModel tgDownloadSettings, Func<TgDownloadSettingsModel, Task> action,
bool isSkipCheckTgSettings, bool isScanCount)
{
if (!isSkipCheckTgSettings && !CheckTgSettingsWithWarning(tgDownloadSettings))
return;

AnsiConsole.Status()
AnsiConsole.Progress()
.AutoRefresh(false)
.Spinner(Spinner.Known.Star)
.SpinnerStyle(Style.Parse("green"))
.Start("Thinking...", statusContext =>
{
statusContext.Spinner(Spinner.Known.Star);
statusContext.SpinnerStyle(Style.Parse("green"));
// Update Console Title
async Task UpdateConsoleTitleAsync(string title) => Console.Title = string.IsNullOrEmpty(title)
? $"{TgLocale.AppTitleConsoleShort}" : $"{TgLocale.AppTitleConsoleShort} {title}";
// Update status.
async Task UpdateStateMessageAsync(string message)
.AutoClear(true)
.HideCompleted(true)
.Columns(GetProgressColumns())
.StartAsync(async context =>
{
Stopwatch sw = Stopwatch.StartNew();
Stopwatch swFileRefresh = Stopwatch.StartNew();
// ProgressTask.
ProgressTask progressTaskFile = context.AddTask("Downloading file", new ProgressTaskSettings
{
AutoStart = true,
MaxValue = 0
});
ProgressTask progressTaskSource = context.AddTask("Downloading source", new ProgressTaskSettings
{
AutoStart = true,
MaxValue = tgDownloadSettings.SourceVm.SourceLastId
});
// Update console title.
async Task UpdateConsoleTitleAsync(string title)
{
await Task.Delay(TimeSpan.FromMilliseconds(1));
Console.Title = string.IsNullOrEmpty(title) ? $"{TgLocale.AppTitleConsoleShort}" : $"{TgLocale.AppTitleConsoleShort} {title}";
}
// Update source.
async Task UpdateStateSourceAsync(long sourceId, int messageId, string message)
{
if (!string.IsNullOrEmpty(message))
{
statusContext.Status(TgLog.GetMarkupString(message));
statusContext.Refresh();
}
}
async Task UpdateStateSourceAsync(long sourceId, int messageId, string message)
await Task.Delay(TimeSpan.FromMilliseconds(1));
if (string.IsNullOrEmpty(message)) return;
progressTaskSource.Description = $"Read the message {tgDownloadSettings.SourceVm.SourceFirstId} from {tgDownloadSettings.SourceVm.SourceLastId}";
progressTaskSource.Value = tgDownloadSettings.SourceVm.SourceFirstId;
context.Refresh();
}
// Update download file state.
async Task UpdateStateFileAsync(long sourceId, int messageId, string fileName, long fileSize, long transmitted, long fileSpeed, bool isFileNewDownload)
{
if (isScanCount)
statusContext.Status(
TgLog.GetMarkupString($"{GetStatus(tgDownloadSettings.SourceVm.SourceScanCount,
messageId)} | {message}"));
else
statusContext.Status(
TgLog.GetMarkupString($"{GetStatus(tgDownloadSettings.SourceVm.SourceLastId,
tgDownloadSettings.SourceVm.SourceFirstId)} | {message}"));
statusContext.Refresh();
}
TgClient.SetupActions(UpdateConsoleTitleAsync, UpdateStateMessageAsync, UpdateStateSourceAsync);
// Action.
Stopwatch sw = new();
sw.Start();
action(tgDownloadSettings).GetAwaiter().GetResult();
sw.Stop();
UpdateStateMessageAsync(
await Task.Delay(TimeSpan.FromMilliseconds(1));
progressTaskSource.Description = $"Read the message {tgDownloadSettings.SourceVm.SourceFirstId} from {tgDownloadSettings.SourceVm.SourceLastId}";
progressTaskSource.Value = tgDownloadSettings.SourceVm.SourceFirstId;
// Download job.
if (!string.IsNullOrEmpty(fileName) && !isFileNewDownload && tgDownloadSettings.SourceVm.SourceId.Equals(sourceId))
{
// ProgressTask.
progressTaskFile.Description = fileName;
progressTaskFile.Value = transmitted;
if (!progressTaskFile.MaxValue.Equals(fileSize))
progressTaskFile.MaxValue = fileSize;
// Download status job.
tgDownloadSettings.SourceVm.SourceFirstId = messageId;
tgDownloadSettings.SourceVm.CurrentFileName = fileName;
tgDownloadSettings.SourceVm.CurrentFileSize = fileSize;
tgDownloadSettings.SourceVm.CurrentFileTransmitted = transmitted;
tgDownloadSettings.SourceVm.CurrentFileSpeed = fileSpeed;
}
// Download reset.
else
{
// ProgressTask.
progressTaskFile.Value = 0;
progressTaskFile.MaxValue = fileSize;
// Download status reset.
tgDownloadSettings.SourceVm.SourceFirstId = messageId;
tgDownloadSettings.SourceVm.CurrentFileName = string.Empty;
tgDownloadSettings.SourceVm.CurrentFileSize = 0;
tgDownloadSettings.SourceVm.CurrentFileTransmitted = 0;
tgDownloadSettings.SourceVm.CurrentFileSpeed = 0;
}
// State.
if (!swFileRefresh.IsRunning)
swFileRefresh.Start();
else if (swFileRefresh.Elapsed > TimeSpan.FromMilliseconds(1_000))
{
swFileRefresh.Reset();
context.Refresh();
}
}
// Setup.
TgClient.SetupUpdateTitle(UpdateConsoleTitleAsync);
TgClient.SetupUpdateStateSource(UpdateStateSourceAsync);
TgClient.SetupUpdateStateFile(UpdateStateFileAsync);
// Action.
await action(tgDownloadSettings);
sw.Stop();
progressTaskFile.StopTask();
progressTaskSource.StopTask();
UpdateStateSourceAsync(0, 0,
isScanCount
? $"{GetStatus(sw, tgDownloadSettings.SourceVm.SourceScanCount, tgDownloadSettings.SourceVm.SourceScanCurrent)}"
: $"{GetStatus(sw, tgDownloadSettings.SourceVm.SourceFirstId, tgDownloadSettings.SourceVm.SourceLastId)}")
.GetAwaiter().GetResult();
});
TgLog.MarkupLine(TgLocale.TypeAnyKeyForReturn);
Console.ReadKey();
}

private string GetStatus(Stopwatch sw, long count, long current) =>
//TgLog.MarkupLine(TgLocale.TypeAnyKeyForReturn);
//Console.ReadKey();
TgLog.MarkupLine(TgLocale.WaitDownloadComplete);
while (!tgDownloadSettings.SourceVm.IsComplete)
{
Console.ReadKey();
TgLog.MarkupLine(TgLocale.WaitDownloadComplete);
}
}

public void RunActionStatus(TgDownloadSettingsModel tgDownloadSettings, Func<TgDownloadSettingsModel, Task> action,
bool isSkipCheckTgSettings, bool isScanCount)
{
if (!isSkipCheckTgSettings && !CheckTgSettingsWithWarning(tgDownloadSettings))
return;
AnsiConsole.Status()
.AutoRefresh(false)
.Spinner(Spinner.Known.Star)
.SpinnerStyle(Style.Parse("green"))
.Start("Thinking...", statusContext =>
{
statusContext.Spinner(Spinner.Known.Star);
statusContext.SpinnerStyle(Style.Parse("green"));
// Update console title.
async Task UpdateConsoleTitleAsync(string title)
{
await Task.Delay(TimeSpan.FromMilliseconds(1));
Console.Title = string.IsNullOrEmpty(title) ? $"{TgLocale.AppTitleConsoleShort}" : $"{TgLocale.AppTitleConsoleShort} {title}";
}
string GetFileStatus(string message = "") =>
string.IsNullOrEmpty(message)
? $"{GetStatus(tgDownloadSettings.SourceVm.SourceLastId, tgDownloadSettings.SourceVm.SourceFirstId)} | " +
$"Progress {tgDownloadSettings.SourceVm.ProgressPercentString}"
: $"{GetStatus(tgDownloadSettings.SourceVm.SourceLastId, tgDownloadSettings.SourceVm.SourceFirstId)} | {message} | " +
$"Progress {tgDownloadSettings.SourceVm.ProgressPercentString}";
// Update source.
async Task UpdateStateSourceAsync(long sourceId, int messageId, string message)
{
await Task.Delay(TimeSpan.FromMilliseconds(1));
if (string.IsNullOrEmpty(message))
return;
statusContext.Status(TgLog.GetMarkupString(isScanCount
? $"{GetStatus(tgDownloadSettings.SourceVm.SourceScanCount, messageId)} | {message} | " +
$"Progress {tgDownloadSettings.SourceVm.ProgressPercentString}"
: GetFileStatus(message)));
statusContext.Refresh();
}
// Update message.
async Task UpdateStateMessageAsync(string message)
{
await Task.Delay(TimeSpan.FromMilliseconds(1));
if (string.IsNullOrEmpty(message))
return;
statusContext.Status(TgLog.GetMarkupString(message));
statusContext.Refresh();
}
// Update download file state.
async Task UpdateStateFileAsync(long sourceId, int messageId, string fileName, long fileSize, long transmitted, long fileSpeed, bool isFileNewDownload)
{
await Task.Delay(TimeSpan.FromMilliseconds(1));
// Download job.
if (!string.IsNullOrEmpty(fileName) && !isFileNewDownload && tgDownloadSettings.SourceVm.SourceId.Equals(sourceId))
{
// Download status job.
tgDownloadSettings.SourceVm.SourceFirstId = messageId;
tgDownloadSettings.SourceVm.CurrentFileName = fileName;
tgDownloadSettings.SourceVm.CurrentFileSize = fileSize;
tgDownloadSettings.SourceVm.CurrentFileTransmitted = transmitted;
tgDownloadSettings.SourceVm.CurrentFileSpeed = fileSpeed;
}
// Download reset.
else
{
// Download status reset.
tgDownloadSettings.SourceVm.SourceFirstId = messageId;
tgDownloadSettings.SourceVm.CurrentFileName = string.Empty;
tgDownloadSettings.SourceVm.CurrentFileSize = 0;
tgDownloadSettings.SourceVm.CurrentFileTransmitted = 0;
tgDownloadSettings.SourceVm.CurrentFileSpeed = 0;
}
// State.
statusContext.Status(TgLog.GetMarkupString($"{GetFileStatus()} | " +
$"File {fileName} | " +
$"Transmitted {tgDownloadSettings.SourceVm.CurrentFileProgressPercentString} | Speed {tgDownloadSettings.SourceVm.CurrentFileSpeedKBString}"));
statusContext.Refresh();
}
// Setup.
TgClient.SetupUpdateTitle(UpdateConsoleTitleAsync);
TgClient.SetupUpdateStateSource(UpdateStateSourceAsync);
TgClient.SetupUpdateStateFile(UpdateStateFileAsync);
TgClient.SetupUpdateStateMessage(UpdateStateMessageAsync);
// Action.
Stopwatch sw = Stopwatch.StartNew();
action(tgDownloadSettings).GetAwaiter().GetResult();
sw.Stop();
// Update state source.
UpdateStateSourceAsync(0, 0,
isScanCount
? $"{GetStatus(sw, tgDownloadSettings.SourceVm.SourceScanCount, tgDownloadSettings.SourceVm.SourceScanCurrent)}"
: $"{GetStatus(sw, tgDownloadSettings.SourceVm.SourceFirstId, tgDownloadSettings.SourceVm.SourceLastId)}")
.GetAwaiter().GetResult();
});

//TgLog.MarkupLine(TgLocale.TypeAnyKeyForReturn);
//Console.ReadKey();
TgLog.MarkupLine(TgLocale.WaitDownloadComplete);
while (!tgDownloadSettings.SourceVm.IsComplete)
{
Console.ReadKey();
TgLog.MarkupLine(TgLocale.WaitDownloadComplete);
}
}

private string GetStatus(Stopwatch sw, long count, long current) =>
count is 0 && current is 0
? $"{TgLog.GetDtShortStamp()} | {sw.Elapsed} | "
: $"{TgLog.GetDtShortStamp()} | {sw.Elapsed} | {TgCommonUtils.CalcSourceProgress(count, current):#00.00} % | {TgCommonUtils.GetLongString(current)} / {TgCommonUtils.GetLongString(count)}";
Expand Down
Loading

0 comments on commit 87fb6c8

Please sign in to comment.