Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

在非ansi环境强制显示进度条等信息 #327

Merged
merged 16 commits into from
Jun 30, 2024
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions src/N_m3u8DL-RE.Common/Log/CustomAnsiConsole.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
using System.Text;
using System.Text.RegularExpressions;
using Spectre.Console;

namespace N_m3u8DL_RE.Common.Log;

public class NonAnsiWriter : TextWriter
{
public override Encoding Encoding => Console.OutputEncoding;

private string lastOut = "";

public override void Write(char value)
{
Console.Write(value);
}

public override void Write(string value)
{
if (lastOut == value)
{
return;
}
lastOut = value;
RemoveAnsiEscapeSequences(value);
}

private void RemoveAnsiEscapeSequences(string input)
{
// Use regular expression to remove ANSI escape sequences
string output = Regex.Replace(input, @"\x1B\[(\d+;?)+m", "");
output = Regex.Replace(output, @"\[\??\d+[AKlh]", "");
output = Regex.Replace(output,"[\r\n] +","");
if (string.IsNullOrWhiteSpace(output))
{
return;
}
// Implement your custom write logic here, e.g., write to console
Console.Write(output);
}
}

/// <summary>
/// A console capable of writing ANSI escape sequences.
/// </summary>
public static class CustomAnsiConsole
{
// var ansiConsoleSettings = new AnsiConsoleSettings();
RikaCelery marked this conversation as resolved.
Show resolved Hide resolved
// ansiConsoleSettings.Ansi = AnsiSupport.Yes;
public static IAnsiConsole Console { get; set; } = AnsiConsole.Console;

public static void InitConsole(bool forceAnsi, bool noAnsiColor)
{
if (forceAnsi)
{
var ansiConsoleSettings = new AnsiConsoleSettings();
if (noAnsiColor)
{
ansiConsoleSettings.Out = new AnsiConsoleOutput(new NonAnsiWriter());
}

ansiConsoleSettings.Interactive = InteractionSupport.Yes;
ansiConsoleSettings.Ansi = AnsiSupport.Yes;
// ansiConsoleSettings.Ansi = AnsiSupport.Yes;
RikaCelery marked this conversation as resolved.
Show resolved Hide resolved
Console = AnsiConsole.Create(ansiConsoleSettings);
Console.Profile.Width = int.MaxValue;
}
else
{
var ansiConsoleSettings = new AnsiConsoleSettings();
if (noAnsiColor)
{
ansiConsoleSettings.Out = new AnsiConsoleOutput(new NonAnsiWriter());
}
Console = AnsiConsole.Create(ansiConsoleSettings);
}
}

/// <summary>
/// Writes the specified markup to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Markup(string value)
{
Console.Markup(value);
}

/// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void MarkupLine(string value)
{
Console.MarkupLine(value);
}
}
22 changes: 15 additions & 7 deletions src/N_m3u8DL-RE.Common/Log/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,11 @@ public static void InitLogFile()
try
{
var logDir = Path.GetDirectoryName(Environment.ProcessPath) + "/Logs";
if (!Directory.Exists(logDir)) { Directory.CreateDirectory(logDir); }
if (!Directory.Exists(logDir))
{
Directory.CreateDirectory(logDir);
}

LogFilePath = Path.Combine(logDir, DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss-fff") + ".log");
//若文件存在则加序号
int index = 1;
Expand All @@ -49,11 +53,12 @@ public static void InitLogFile()
{
LogFilePath = Path.Combine(Path.GetDirectoryName(LogFilePath)!, $"{fileName}-{index++}.log");
}

string now = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
string init = "LOG " + DateTime.Now.ToString("yyyy/MM/dd") + Environment.NewLine
+ "Save Path: " + Path.GetDirectoryName(LogFilePath) + Environment.NewLine
+ "Task Start: " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + Environment.NewLine
+ "Task CommandLine: " + Environment.CommandLine;
+ "Save Path: " + Path.GetDirectoryName(LogFilePath) + Environment.NewLine
+ "Task Start: " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + Environment.NewLine
+ "Task CommandLine: " + Environment.CommandLine;
init += $"{Environment.NewLine}{Environment.NewLine}";
File.WriteAllText(LogFilePath, init, Encoding.UTF8);
}
Expand All @@ -74,13 +79,14 @@ private static void HandleLog(string write, string subWrite = "")
{
if (subWrite == "")
{
AnsiConsole.MarkupLine(write);
CustomAnsiConsole.MarkupLine(write);
RikaCelery marked this conversation as resolved.
Show resolved Hide resolved
}
else
{
AnsiConsole.Markup(write);
CustomAnsiConsole.Markup(write);
Console.WriteLine(subWrite);
}

if (IsWriteFile && File.Exists(LogFilePath))
{
var plain = write.RemoveMarkup() + subWrite.RemoveMarkup();
Expand Down Expand Up @@ -112,6 +118,7 @@ private static string ReplaceVars(string data, params object[] ps)
{
data = VarsRepRegex().Replace(data, $"{ps[i]}", 1);
}

return data;
}

Expand Down Expand Up @@ -202,6 +209,7 @@ public static void ErrorMarkUp(Exception exception)
{
data = exception.ToString().EscapeMarkup();
}

ErrorMarkUp(data);
}

Expand Down Expand Up @@ -233,4 +241,4 @@ public static void Extra(string data, params object[] ps)
}
}
}
}
}
3 changes: 3 additions & 0 deletions src/N_m3u8DL-RE.Common/Resource/ResString.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public class ResString
public static string customRangeFound { get => GetText("customRangeFound"); }
public static string customAdKeywordsFound { get => GetText("customAdKeywordsFound"); }
public static string customRangeInvalid { get => GetText("customRangeInvalid"); }
public static string consoleRedirected { get => GetText("consoleRedirected"); }
public static string autoBinaryMerge { get => GetText("autoBinaryMerge"); }
public static string autoBinaryMerge2 { get => GetText("autoBinaryMerge2"); }
public static string autoBinaryMerge3 { get => GetText("autoBinaryMerge3"); }
Expand Down Expand Up @@ -55,6 +56,8 @@ public class ResString
public static string cmd_customHLSKey { get => GetText("cmd_customHLSKey"); }
public static string cmd_customHLSIv { get => GetText("cmd_customHLSIv"); }
public static string cmd_Input { get => GetText("cmd_Input"); }
public static string cmd_forceAnsiConsole { get => GetText("cmd_forceAnsiConsole"); }
public static string cmd_noAnsiColor { get => GetText("cmd_noAnsiColor"); }
public static string cmd_keys { get => GetText("cmd_keys"); }
public static string cmd_keyText { get => GetText("cmd_keyText"); }
public static string cmd_loadKeyFailed { get => GetText("cmd_loadKeyFailed"); }
Expand Down
18 changes: 18 additions & 0 deletions src/N_m3u8DL-RE.Common/Resource/StaticText.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,18 @@ internal class StaticText
zhTW: "即時解密已被強制關閉",
enUS: "Real-time decryption has been disabled"
),
["cmd_forceAnsiConsole"] = new TextContainer
(
zhCN: "强制认定终端为支持Ansi且可交互的终端",
zhTW: "強制認定終端為支援Ansi且可交往的終端",
enUS: "Force assuming the terminal is ANSI-compatible and interactive"
),
["cmd_noAnsiColor"] = new TextContainer
(
zhCN: "去除ansi颜色",
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里文本中"Ansi"大小和上面"cmd_forceAnsiConsole"的大小写要统一标准

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

我改成全大写了

zhTW: "關閉ansi顏色",
enUS: "Remove ANSI colors"
),
["customRangeWarn"] = new TextContainer
(
zhCN: "请注意,自定义下载范围有时会导致音画不同步",
Expand All @@ -46,6 +58,12 @@ internal class StaticText
zhTW: "用戶自定義下載範圍:",
enUS: "User customed range: "
),
["consoleRedirected"] = new TextContainer
(
zhCN: "输出被重定向, 将清除Ansi颜色",
zhTW: "輸出被重定向, 將清除Ansi顏色",
enUS: "Output is redirected, Ansi colors are cleared."
),
["processImageSub"] = new TextContainer
(
zhCN: "正在处理图形字幕",
Expand Down
6 changes: 5 additions & 1 deletion src/N_m3u8DL-RE/CommandLine/CommandInvoker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ internal partial class CommandInvoker
private readonly static Option<bool> AppendUrlParams = new(new string[] { "--append-url-params" }, description: ResString.cmd_appendUrlParams, getDefaultValue: () => false);
private readonly static Option<bool> MP4RealTimeDecryption = new (new string[] { "--mp4-real-time-decryption" }, description: ResString.cmd_MP4RealTimeDecryption, getDefaultValue: () => false);
private readonly static Option<bool> UseShakaPackager = new (new string[] { "--use-shaka-packager" }, description: ResString.cmd_useShakaPackager, getDefaultValue: () => false);
private readonly static Option<bool> ForceAnsiConsole = new(new string[] { "--force-ansi-console" }, description: ResString.cmd_forceAnsiConsole);
private readonly static Option<bool> NoAnsiColor = new(new string[] { "--no-ansi-color" }, description: ResString.cmd_noAnsiColor);
private readonly static Option<string?> DecryptionBinaryPath = new(new string[] { "--decryption-binary-path" }, description: ResString.cmd_decryptionBinaryPath) { ArgumentHelpName = "PATH" };
private readonly static Option<string?> FFmpegBinaryPath = new(new string[] { "--ffmpeg-binary-path" }, description: ResString.cmd_ffmpegBinaryPath) { ArgumentHelpName = "PATH" };
private readonly static Option<string?> BaseUrl = new(new string[] { "--base-url" }, description: ResString.cmd_baseUrl);
Expand Down Expand Up @@ -484,6 +486,8 @@ protected override MyOption GetBoundValue(BindingContext bindingContext)
var option = new MyOption
{
Input = bindingContext.ParseResult.GetValueForArgument(Input),
ForceAnsiConsole = bindingContext.ParseResult.GetValueForOption(ForceAnsiConsole),
NoAnsiColor = bindingContext.ParseResult.GetValueForOption(NoAnsiColor),
LogLevel = bindingContext.ParseResult.GetValueForOption(LogLevel),
AutoSelect = bindingContext.ParseResult.GetValueForOption(AutoSelect),
SkipMerge = bindingContext.ParseResult.GetValueForOption(SkipMerge),
Expand Down Expand Up @@ -594,7 +598,7 @@ public static async Task<int> InvokeArgs(string[] args, Func<MyOption, Task> act

var rootCommand = new RootCommand(VERSION_INFO)
{
Input, TmpDir, SaveDir, SaveName, BaseUrl, ThreadCount, DownloadRetryCount, AutoSelect, SkipMerge, SkipDownload, CheckSegmentsCount,
Input, TmpDir, SaveDir, SaveName, BaseUrl, ThreadCount, DownloadRetryCount, ForceAnsiConsole,NoAnsiColor,AutoSelect, SkipMerge, SkipDownload, CheckSegmentsCount,
RikaCelery marked this conversation as resolved.
Show resolved Hide resolved
BinaryMerge, UseFFmpegConcatDemuxer, DelAfterDone, NoDateInfo, NoLog, WriteMetaJson, AppendUrlParams, ConcurrentDownload, Headers, /**SavePattern,**/ SubOnly, SubtitleFormat, AutoSubtitleFix,
FFmpegBinaryPath,
LogLevel, UILanguage, UrlProcessorArgs, Keys, KeyTextFile, DecryptionBinaryPath, UseShakaPackager, MP4RealTimeDecryption,
Expand Down
8 changes: 8 additions & 0 deletions src/N_m3u8DL-RE/CommandLine/MyOption.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,14 @@ internal class MyOption
/// </summary>
public bool BinaryMerge { get; set; }
/// <summary>
/// See: <see cref="CommandInvoker.ForceAnsiConsole"/>.
/// </summary>
public bool ForceAnsiConsole { get; set; }
/// <summary>
/// See: <see cref="CommandInvoker.NoAnsiColor"/>.
/// </summary>
public bool NoAnsiColor { get; set; }
/// <summary>
/// See: <see cref="CommandInvoker.UseFFmpegConcatDemuxer"/>.
/// </summary>
public bool UseFFmpegConcatDemuxer { get; set; }
Expand Down
11 changes: 8 additions & 3 deletions src/N_m3u8DL-RE/DownloadManager/HTTPLiveRecordManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -197,19 +197,24 @@ public async Task<bool> StartRecordAsync()
ConcurrentDictionary<int, SpeedContainer> SpeedContainerDic = new(); //速度计算
ConcurrentDictionary<StreamSpec, bool?> Results = new();

var progress = AnsiConsole.Progress().AutoClear(true);
var progress = CustomAnsiConsole.Console.Progress().AutoClear(true);
progress.AutoRefresh = DownloaderConfig.MyOptions.LogLevel != LogLevel.OFF;

//进度条的列定义
progress.Columns(new ProgressColumn[]
var progressColumns = new ProgressColumn[]
{
new TaskDescriptionColumn() { Alignment = Justify.Left },
new RecordingDurationColumn(RecordingDurDic), //时长显示
new RecordingSizeColumn(RecordingSizeDic), //大小显示
new RecordingStatusColumn(),
new DownloadSpeedColumn(SpeedContainerDic), //速度计算
new SpinnerColumn(),
});
};
if (DownloaderConfig.MyOptions.NoAnsiColor)
{
progressColumns = progressColumns.SkipLast(1).ToArray();
}
progress.Columns(progressColumns);

await progress.StartAsync(async ctx =>
{
Expand Down
13 changes: 9 additions & 4 deletions src/N_m3u8DL-RE/DownloadManager/SimpleDownloadManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -616,12 +616,12 @@ public async Task<bool> StartDownloadAsync()
{
ConcurrentDictionary<int, SpeedContainer> SpeedContainerDic = new(); //速度计算
ConcurrentDictionary<StreamSpec, bool?> Results = new();

var progress = AnsiConsole.Progress().AutoClear(true);
var progress = CustomAnsiConsole.Console.Progress().AutoClear(true);
progress.AutoRefresh = DownloaderConfig.MyOptions.LogLevel != LogLevel.OFF;

//进度条的列定义
progress.Columns(new ProgressColumn[]
var progressColumns = new ProgressColumn[]
{
new TaskDescriptionColumn() { Alignment = Justify.Left },
new ProgressBarColumn(){ Width = 30 },
Expand All @@ -630,7 +630,12 @@ public async Task<bool> StartDownloadAsync()
new DownloadSpeedColumn(SpeedContainerDic), //速度计算
new RemainingTimeColumn(),
new SpinnerColumn(),
});
};
if (DownloaderConfig.MyOptions.NoAnsiColor)
{
progressColumns = progressColumns.SkipLast(1).ToArray();
}
progress.Columns(progressColumns);

if (DownloaderConfig.MyOptions.MP4RealTimeDecryption && !DownloaderConfig.MyOptions.UseShakaPackager
&& DownloaderConfig.MyOptions.Keys != null && DownloaderConfig.MyOptions.Keys.Length > 0)
Expand Down
13 changes: 9 additions & 4 deletions src/N_m3u8DL-RE/DownloadManager/SimpleLiveRecordManager2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -801,19 +801,24 @@ public async Task<bool> StartRecordAsync()
await StreamingUtil.WriteMasterListAsync(SelectedSteams, saveName, saveDir);
}*/

var progress = AnsiConsole.Progress().AutoClear(true);
var progress = CustomAnsiConsole.Console.Progress().AutoClear(true);
progress.AutoRefresh = DownloaderConfig.MyOptions.LogLevel != LogLevel.OFF;

//进度条的列定义
progress.Columns(new ProgressColumn[]
var progressColumns = new ProgressColumn[]
{
new TaskDescriptionColumn() { Alignment = Justify.Left },
new RecordingDurationColumn(RecordedDurDic, RefreshedDurDic), //时长显示
new RecordingStatusColumn(),
new PercentageColumn(),
new DownloadSpeedColumn(SpeedContainerDic), //速度计算
new SpinnerColumn(),
});
};
if (DownloaderConfig.MyOptions.NoAnsiColor)
{
progressColumns = progressColumns.SkipLast(1).ToArray();
}
progress.Columns(progressColumns);

await progress.StartAsync(async ctx =>
{
Expand Down
9 changes: 9 additions & 0 deletions src/N_m3u8DL-RE/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ static async Task Main(string[] args)
Console.CancelKeyPress += Console_CancelKeyPress;
ServicePointManager.DefaultConnectionLimit = 1024;
try { Console.CursorVisible = true; } catch { }

string loc = "en-US";
string currLoc = Thread.CurrentThread.CurrentUICulture.Name;
if (currLoc == "zh-CN" || currLoc == "zh-SG") loc = "zh-CN";
Expand Down Expand Up @@ -70,6 +71,14 @@ static int GetOrder(StreamSpec streamSpec)

static async Task DoWorkAsync(MyOption option)
{

if (Console.IsOutputRedirected||Console.IsErrorRedirected)
RikaCelery marked this conversation as resolved.
Show resolved Hide resolved
{
option.ForceAnsiConsole = true;
option.NoAnsiColor = true;
Logger.Info(ResString.consoleRedirected);
}
CustomAnsiConsole.InitConsole(option.ForceAnsiConsole,option.NoAnsiColor);
RikaCelery marked this conversation as resolved.
Show resolved Hide resolved
//检测更新
CheckUpdateAsync();

Expand Down
2 changes: 1 addition & 1 deletion src/N_m3u8DL-RE/Util/FilterUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ public static List<StreamSpec> SelectStreams(IEnumerable<StreamSpec> lists)
prompt.Select(basicStreams.Concat(audios).Concat(subs).First());

//多选
var selectedStreams = AnsiConsole.Prompt(prompt);
var selectedStreams = CustomAnsiConsole.Console.Prompt(prompt);

return selectedStreams;
}
Expand Down