Use file-scoped namespaces

This commit is contained in:
Archi
2021-11-10 21:23:24 +01:00
parent 95ad16e26d
commit 1e6ab11d9f
142 changed files with 25006 additions and 25006 deletions

View File

@@ -31,154 +31,170 @@ using JetBrains.Annotations;
using NLog;
using SteamKit2;
namespace ArchiSteamFarm.NLog {
public sealed class ArchiLogger {
private readonly Logger Logger;
namespace ArchiSteamFarm.NLog;
public ArchiLogger(string name) {
if (string.IsNullOrEmpty(name)) {
throw new ArgumentNullException(nameof(name));
}
public sealed class ArchiLogger {
private readonly Logger Logger;
Logger = LogManager.GetLogger(name);
public ArchiLogger(string name) {
if (string.IsNullOrEmpty(name)) {
throw new ArgumentNullException(nameof(name));
}
[PublicAPI]
public void LogGenericDebug(string message, [CallerMemberName] string? previousMethodName = null) {
if (string.IsNullOrEmpty(message)) {
throw new ArgumentNullException(nameof(message));
}
Logger = LogManager.GetLogger(name);
}
Logger.Debug($"{previousMethodName}() {message}");
[PublicAPI]
public void LogGenericDebug(string message, [CallerMemberName] string? previousMethodName = null) {
if (string.IsNullOrEmpty(message)) {
throw new ArgumentNullException(nameof(message));
}
[PublicAPI]
public void LogGenericDebuggingException(Exception exception, [CallerMemberName] string? previousMethodName = null) {
if (exception == null) {
throw new ArgumentNullException(nameof(exception));
}
Logger.Debug($"{previousMethodName}() {message}");
}
if (!Debugging.IsUserDebugging) {
return;
}
Logger.Debug(exception, $"{previousMethodName}()");
[PublicAPI]
public void LogGenericDebuggingException(Exception exception, [CallerMemberName] string? previousMethodName = null) {
if (exception == null) {
throw new ArgumentNullException(nameof(exception));
}
[PublicAPI]
public void LogGenericError(string message, [CallerMemberName] string? previousMethodName = null) {
if (string.IsNullOrEmpty(message)) {
throw new ArgumentNullException(nameof(message));
}
Logger.Error($"{previousMethodName}() {message}");
if (!Debugging.IsUserDebugging) {
return;
}
[PublicAPI]
public void LogGenericException(Exception exception, [CallerMemberName] string? previousMethodName = null) {
if (exception == null) {
throw new ArgumentNullException(nameof(exception));
}
Logger.Debug(exception, $"{previousMethodName}()");
}
Logger.Error(exception, $"{previousMethodName}()");
[PublicAPI]
public void LogGenericError(string message, [CallerMemberName] string? previousMethodName = null) {
if (string.IsNullOrEmpty(message)) {
throw new ArgumentNullException(nameof(message));
}
[PublicAPI]
public void LogGenericInfo(string message, [CallerMemberName] string? previousMethodName = null) {
if (string.IsNullOrEmpty(message)) {
throw new ArgumentNullException(nameof(message));
}
Logger.Error($"{previousMethodName}() {message}");
}
Logger.Info($"{previousMethodName}() {message}");
[PublicAPI]
public void LogGenericException(Exception exception, [CallerMemberName] string? previousMethodName = null) {
if (exception == null) {
throw new ArgumentNullException(nameof(exception));
}
[PublicAPI]
public void LogGenericTrace(string message, [CallerMemberName] string? previousMethodName = null) {
if (string.IsNullOrEmpty(message)) {
throw new ArgumentNullException(nameof(message));
}
Logger.Error(exception, $"{previousMethodName}()");
}
Logger.Trace($"{previousMethodName}() {message}");
[PublicAPI]
public void LogGenericInfo(string message, [CallerMemberName] string? previousMethodName = null) {
if (string.IsNullOrEmpty(message)) {
throw new ArgumentNullException(nameof(message));
}
[PublicAPI]
public void LogGenericWarning(string message, [CallerMemberName] string? previousMethodName = null) {
if (string.IsNullOrEmpty(message)) {
throw new ArgumentNullException(nameof(message));
}
Logger.Info($"{previousMethodName}() {message}");
}
Logger.Warn($"{previousMethodName}() {message}");
[PublicAPI]
public void LogGenericTrace(string message, [CallerMemberName] string? previousMethodName = null) {
if (string.IsNullOrEmpty(message)) {
throw new ArgumentNullException(nameof(message));
}
[PublicAPI]
public void LogGenericWarningException(Exception exception, [CallerMemberName] string? previousMethodName = null) {
if (exception == null) {
throw new ArgumentNullException(nameof(exception));
}
Logger.Trace($"{previousMethodName}() {message}");
}
Logger.Warn(exception, $"{previousMethodName}()");
[PublicAPI]
public void LogGenericWarning(string message, [CallerMemberName] string? previousMethodName = null) {
if (string.IsNullOrEmpty(message)) {
throw new ArgumentNullException(nameof(message));
}
[PublicAPI]
public void LogNullError(string nullObjectName, [CallerMemberName] string? previousMethodName = null) {
if (string.IsNullOrEmpty(nullObjectName)) {
throw new ArgumentNullException(nameof(nullObjectName));
}
Logger.Warn($"{previousMethodName}() {message}");
}
LogGenericError(string.Format(CultureInfo.CurrentCulture, Strings.ErrorObjectIsNull, nullObjectName), previousMethodName);
[PublicAPI]
public void LogGenericWarningException(Exception exception, [CallerMemberName] string? previousMethodName = null) {
if (exception == null) {
throw new ArgumentNullException(nameof(exception));
}
internal void LogChatMessage(bool echo, string message, ulong chatGroupID = 0, ulong chatID = 0, ulong steamID = 0, [CallerMemberName] string? previousMethodName = null) {
if (string.IsNullOrEmpty(message)) {
throw new ArgumentNullException(nameof(message));
}
Logger.Warn(exception, $"{previousMethodName}()");
}
if (((chatGroupID == 0) || (chatID == 0)) && (steamID == 0)) {
throw new InvalidOperationException($"(({nameof(chatGroupID)} || {nameof(chatID)}) && {nameof(steamID)})");
}
StringBuilder loggedMessage = new($"{previousMethodName}() {message} {(echo ? "->" : "<-")} ");
if ((chatGroupID != 0) && (chatID != 0)) {
loggedMessage.Append(CultureInfo.InvariantCulture, $"{chatGroupID}-{chatID}");
if (steamID != 0) {
loggedMessage.Append(CultureInfo.InvariantCulture, $"/{steamID}");
}
} else if (steamID != 0) {
loggedMessage.Append(steamID);
}
LogEventInfo logEventInfo = new(LogLevel.Trace, Logger.Name, loggedMessage.ToString()) {
Properties = {
["Echo"] = echo,
["Message"] = message,
["ChatGroupID"] = chatGroupID,
["ChatID"] = chatID,
["SteamID"] = steamID
}
};
Logger.Log(logEventInfo);
[PublicAPI]
public void LogNullError(string nullObjectName, [CallerMemberName] string? previousMethodName = null) {
if (string.IsNullOrEmpty(nullObjectName)) {
throw new ArgumentNullException(nameof(nullObjectName));
}
internal async Task LogFatalException(Exception exception, [CallerMemberName] string? previousMethodName = null) {
if (exception == null) {
throw new ArgumentNullException(nameof(exception));
LogGenericError(string.Format(CultureInfo.CurrentCulture, Strings.ErrorObjectIsNull, nullObjectName), previousMethodName);
}
internal void LogChatMessage(bool echo, string message, ulong chatGroupID = 0, ulong chatID = 0, ulong steamID = 0, [CallerMemberName] string? previousMethodName = null) {
if (string.IsNullOrEmpty(message)) {
throw new ArgumentNullException(nameof(message));
}
if (((chatGroupID == 0) || (chatID == 0)) && (steamID == 0)) {
throw new InvalidOperationException($"(({nameof(chatGroupID)} || {nameof(chatID)}) && {nameof(steamID)})");
}
StringBuilder loggedMessage = new($"{previousMethodName}() {message} {(echo ? "->" : "<-")} ");
if ((chatGroupID != 0) && (chatID != 0)) {
loggedMessage.Append(CultureInfo.InvariantCulture, $"{chatGroupID}-{chatID}");
if (steamID != 0) {
loggedMessage.Append(CultureInfo.InvariantCulture, $"/{steamID}");
}
} else if (steamID != 0) {
loggedMessage.Append(steamID);
}
Logger.Fatal(exception, $"{previousMethodName}()");
// If LogManager has been initialized already, don't do anything else
if (LogManager.Configuration != null) {
return;
LogEventInfo logEventInfo = new(LogLevel.Trace, Logger.Name, loggedMessage.ToString()) {
Properties = {
["Echo"] = echo,
["Message"] = message,
["ChatGroupID"] = chatGroupID,
["ChatID"] = chatID,
["SteamID"] = steamID
}
};
// Otherwise, we ran into fatal exception before logging module could even get initialized, so activate fallback logging that involves file and console
string message = string.Format(CultureInfo.CurrentCulture, DateTime.Now + " " + Strings.ErrorEarlyFatalExceptionInfo, SharedInfo.Version) + Environment.NewLine;
Logger.Log(logEventInfo);
}
internal async Task LogFatalException(Exception exception, [CallerMemberName] string? previousMethodName = null) {
if (exception == null) {
throw new ArgumentNullException(nameof(exception));
}
Logger.Fatal(exception, $"{previousMethodName}()");
// If LogManager has been initialized already, don't do anything else
if (LogManager.Configuration != null) {
return;
}
// Otherwise, we ran into fatal exception before logging module could even get initialized, so activate fallback logging that involves file and console
string message = string.Format(CultureInfo.CurrentCulture, DateTime.Now + " " + Strings.ErrorEarlyFatalExceptionInfo, SharedInfo.Version) + Environment.NewLine;
try {
await File.WriteAllTextAsync(SharedInfo.LogFile, message).ConfigureAwait(false);
} catch {
// Ignored, we can't do anything about this
}
try {
Console.Write(message);
} catch {
// Ignored, we can't do anything about this
}
while (true) {
message = string.Format(CultureInfo.CurrentCulture, Strings.ErrorEarlyFatalExceptionPrint, previousMethodName, exception.Message, exception.StackTrace) + Environment.NewLine;
try {
await File.WriteAllTextAsync(SharedInfo.LogFile, message).ConfigureAwait(false);
await File.AppendAllTextAsync(SharedInfo.LogFile, message).ConfigureAwait(false);
} catch {
// Ignored, we can't do anything about this
}
@@ -189,49 +205,33 @@ namespace ArchiSteamFarm.NLog {
// Ignored, we can't do anything about this
}
while (true) {
message = string.Format(CultureInfo.CurrentCulture, Strings.ErrorEarlyFatalExceptionPrint, previousMethodName, exception.Message, exception.StackTrace) + Environment.NewLine;
if (exception.InnerException != null) {
exception = exception.InnerException;
try {
await File.AppendAllTextAsync(SharedInfo.LogFile, message).ConfigureAwait(false);
} catch {
// Ignored, we can't do anything about this
}
try {
Console.Write(message);
} catch {
// Ignored, we can't do anything about this
}
if (exception.InnerException != null) {
exception = exception.InnerException;
continue;
}
break;
}
}
internal void LogInvite(SteamID steamID, bool? handled = null, [CallerMemberName] string? previousMethodName = null) {
if ((steamID == null) || (steamID.AccountType == EAccountType.Invalid)) {
throw new ArgumentNullException(nameof(steamID));
continue;
}
ulong steamID64 = steamID;
string loggedMessage = $"{previousMethodName}() {steamID.AccountType} {steamID64}{(handled.HasValue ? $" = {handled.Value}" : "")}";
LogEventInfo logEventInfo = new(LogLevel.Trace, Logger.Name, loggedMessage) {
Properties = {
["AccountType"] = steamID.AccountType,
["Handled"] = handled,
["SteamID"] = steamID64
}
};
Logger.Log(logEventInfo);
break;
}
}
internal void LogInvite(SteamID steamID, bool? handled = null, [CallerMemberName] string? previousMethodName = null) {
if ((steamID == null) || (steamID.AccountType == EAccountType.Invalid)) {
throw new ArgumentNullException(nameof(steamID));
}
ulong steamID64 = steamID;
string loggedMessage = $"{previousMethodName}() {steamID.AccountType} {steamID64}{(handled.HasValue ? $" = {handled.Value}" : "")}";
LogEventInfo logEventInfo = new(LogLevel.Trace, Logger.Name, loggedMessage) {
Properties = {
["AccountType"] = steamID.AccountType,
["Handled"] = handled,
["SteamID"] = steamID64
}
};
Logger.Log(logEventInfo);
}
}

View File

@@ -38,408 +38,408 @@ using NLog;
using NLog.Config;
using NLog.Targets;
namespace ArchiSteamFarm.NLog {
internal static class Logging {
internal const string NLogConfigurationFile = "NLog.config";
namespace ArchiSteamFarm.NLog;
private const byte ConsoleResponsivenessDelay = 250; // In milliseconds
private const string GeneralLayout = @"${date:format=yyyy-MM-dd HH\:mm\:ss}|${processname}-${processid}|${level:uppercase=true}|" + LayoutMessage;
private const string LayoutMessage = @"${logger}|${message}${onexception:inner= ${exception:format=toString,Data}}";
internal static class Logging {
internal const string NLogConfigurationFile = "NLog.config";
private static readonly ConcurrentHashSet<LoggingRule> ConsoleLoggingRules = new();
private static readonly SemaphoreSlim ConsoleSemaphore = new(1, 1);
private const byte ConsoleResponsivenessDelay = 250; // In milliseconds
private const string GeneralLayout = @"${date:format=yyyy-MM-dd HH\:mm\:ss}|${processname}-${processid}|${level:uppercase=true}|" + LayoutMessage;
private const string LayoutMessage = @"${logger}|${message}${onexception:inner= ${exception:format=toString,Data}}";
private static string Backspace => "\b \b";
private static readonly ConcurrentHashSet<LoggingRule> ConsoleLoggingRules = new();
private static readonly SemaphoreSlim ConsoleSemaphore = new(1, 1);
private static bool IsUsingCustomConfiguration;
private static bool IsWaitingForUserInput;
private static string Backspace => "\b \b";
internal static void EnableTraceLogging() {
if (IsUsingCustomConfiguration || (LogManager.Configuration == null)) {
return;
}
private static bool IsUsingCustomConfiguration;
private static bool IsWaitingForUserInput;
bool reload = false;
foreach (LoggingRule rule in LogManager.Configuration.LoggingRules.Where(static rule => rule.IsLoggingEnabledForLevel(LogLevel.Debug) && !rule.IsLoggingEnabledForLevel(LogLevel.Trace))) {
rule.EnableLoggingForLevel(LogLevel.Trace);
reload = true;
}
if (reload) {
LogManager.ReconfigExistingLoggers();
}
internal static void EnableTraceLogging() {
if (IsUsingCustomConfiguration || (LogManager.Configuration == null)) {
return;
}
internal static async Task<string?> GetUserInput(ASF.EUserInputType userInputType, string botName = SharedInfo.ASF) {
if ((userInputType == ASF.EUserInputType.None) || !Enum.IsDefined(typeof(ASF.EUserInputType), userInputType)) {
throw new InvalidEnumArgumentException(nameof(userInputType), (int) userInputType, typeof(ASF.EUserInputType));
}
bool reload = false;
if (string.IsNullOrEmpty(botName)) {
throw new ArgumentNullException(nameof(botName));
}
foreach (LoggingRule rule in LogManager.Configuration.LoggingRules.Where(static rule => rule.IsLoggingEnabledForLevel(LogLevel.Debug) && !rule.IsLoggingEnabledForLevel(LogLevel.Trace))) {
rule.EnableLoggingForLevel(LogLevel.Trace);
reload = true;
}
if (Program.Service || (ASF.GlobalConfig?.Headless ?? GlobalConfig.DefaultHeadless)) {
ASF.ArchiLogger.LogGenericWarning(Strings.ErrorUserInputRunningInHeadlessMode);
if (reload) {
LogManager.ReconfigExistingLoggers();
}
}
internal static async Task<string?> GetUserInput(ASF.EUserInputType userInputType, string botName = SharedInfo.ASF) {
if ((userInputType == ASF.EUserInputType.None) || !Enum.IsDefined(typeof(ASF.EUserInputType), userInputType)) {
throw new InvalidEnumArgumentException(nameof(userInputType), (int) userInputType, typeof(ASF.EUserInputType));
}
if (string.IsNullOrEmpty(botName)) {
throw new ArgumentNullException(nameof(botName));
}
if (Program.Service || (ASF.GlobalConfig?.Headless ?? GlobalConfig.DefaultHeadless)) {
ASF.ArchiLogger.LogGenericWarning(Strings.ErrorUserInputRunningInHeadlessMode);
return null;
}
await ConsoleSemaphore.WaitAsync().ConfigureAwait(false);
string? result;
try {
OnUserInputStart();
try {
switch (userInputType) {
case ASF.EUserInputType.Login:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteamLogin, botName));
result = ConsoleReadLine();
break;
case ASF.EUserInputType.Password:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteamPassword, botName));
result = ConsoleReadLineMasked();
break;
case ASF.EUserInputType.SteamGuard:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteamGuard, botName));
result = ConsoleReadLine();
break;
case ASF.EUserInputType.SteamParentalCode:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteamParentalCode, botName));
result = ConsoleReadLineMasked();
break;
case ASF.EUserInputType.TwoFactorAuthentication:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteam2FA, botName));
result = ConsoleReadLine();
break;
default:
ASF.ArchiLogger.LogGenericError(string.Format(CultureInfo.CurrentCulture, Strings.WarningUnknownValuePleaseReport, nameof(userInputType), userInputType));
return null;
}
if (!Console.IsOutputRedirected) {
Console.Clear(); // For security purposes
}
} catch (Exception e) {
OnUserInputEnd();
ASF.ArchiLogger.LogGenericException(e);
return null;
}
await ConsoleSemaphore.WaitAsync().ConfigureAwait(false);
string? result;
try {
OnUserInputStart();
try {
switch (userInputType) {
case ASF.EUserInputType.Login:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteamLogin, botName));
result = ConsoleReadLine();
break;
case ASF.EUserInputType.Password:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteamPassword, botName));
result = ConsoleReadLineMasked();
break;
case ASF.EUserInputType.SteamGuard:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteamGuard, botName));
result = ConsoleReadLine();
break;
case ASF.EUserInputType.SteamParentalCode:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteamParentalCode, botName));
result = ConsoleReadLineMasked();
break;
case ASF.EUserInputType.TwoFactorAuthentication:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteam2FA, botName));
result = ConsoleReadLine();
break;
default:
ASF.ArchiLogger.LogGenericError(string.Format(CultureInfo.CurrentCulture, Strings.WarningUnknownValuePleaseReport, nameof(userInputType), userInputType));
return null;
}
if (!Console.IsOutputRedirected) {
Console.Clear(); // For security purposes
}
} catch (Exception e) {
OnUserInputEnd();
ASF.ArchiLogger.LogGenericException(e);
return null;
} finally {
OnUserInputEnd();
}
} finally {
ConsoleSemaphore.Release();
OnUserInputEnd();
}
// ReSharper disable once RedundantSuppressNullableWarningExpression - required for .NET Framework
return !string.IsNullOrEmpty(result) ? result!.Trim() : null;
} finally {
ConsoleSemaphore.Release();
}
internal static void InitCoreLoggers(bool uniqueInstance) {
// ReSharper disable once RedundantSuppressNullableWarningExpression - required for .NET Framework
return !string.IsNullOrEmpty(result) ? result!.Trim() : null;
}
internal static void InitCoreLoggers(bool uniqueInstance) {
try {
if ((Directory.GetCurrentDirectory() != AppContext.BaseDirectory) && File.Exists(NLogConfigurationFile)) {
LogManager.Configuration = new XmlLoggingConfiguration(NLogConfigurationFile);
}
} catch (Exception e) {
ASF.ArchiLogger.LogGenericException(e);
}
if (LogManager.Configuration != null) {
IsUsingCustomConfiguration = true;
InitConsoleLoggers();
LogManager.ConfigurationChanged += OnConfigurationChanged;
return;
}
ConfigurationItemFactory.Default.ParseMessageTemplates = false;
LoggingConfiguration config = new();
#pragma warning disable CA2000 // False positive, we're adding this disposable object to the global scope, so we can't dispose it
ColoredConsoleTarget coloredConsoleTarget = new("ColoredConsole") { Layout = GeneralLayout };
#pragma warning restore CA2000 // False positive, we're adding this disposable object to the global scope, so we can't dispose it
config.AddTarget(coloredConsoleTarget);
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, coloredConsoleTarget));
if (uniqueInstance) {
try {
if ((Directory.GetCurrentDirectory() != AppContext.BaseDirectory) && File.Exists(NLogConfigurationFile)) {
LogManager.Configuration = new XmlLoggingConfiguration(NLogConfigurationFile);
if (!Directory.Exists(SharedInfo.ArchivalLogsDirectory)) {
Directory.CreateDirectory(SharedInfo.ArchivalLogsDirectory);
}
} catch (Exception e) {
ASF.ArchiLogger.LogGenericException(e);
}
if (LogManager.Configuration != null) {
IsUsingCustomConfiguration = true;
InitConsoleLoggers();
LogManager.ConfigurationChanged += OnConfigurationChanged;
return;
}
ConfigurationItemFactory.Default.ParseMessageTemplates = false;
LoggingConfiguration config = new();
#pragma warning disable CA2000 // False positive, we're adding this disposable object to the global scope, so we can't dispose it
ColoredConsoleTarget coloredConsoleTarget = new("ColoredConsole") { Layout = GeneralLayout };
FileTarget fileTarget = new("File") {
ArchiveFileName = Path.Combine("${currentdir}", SharedInfo.ArchivalLogsDirectory, SharedInfo.ArchivalLogFile),
ArchiveNumbering = ArchiveNumberingMode.Rolling,
ArchiveOldFileOnStartup = true,
CleanupFileName = false,
ConcurrentWrites = false,
DeleteOldFileOnStartup = true,
FileName = Path.Combine("${currentdir}", SharedInfo.LogFile),
Layout = GeneralLayout,
MaxArchiveFiles = 10
};
#pragma warning restore CA2000 // False positive, we're adding this disposable object to the global scope, so we can't dispose it
config.AddTarget(coloredConsoleTarget);
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, coloredConsoleTarget));
if (uniqueInstance) {
try {
if (!Directory.Exists(SharedInfo.ArchivalLogsDirectory)) {
Directory.CreateDirectory(SharedInfo.ArchivalLogsDirectory);
}
} catch (Exception e) {
ASF.ArchiLogger.LogGenericException(e);
}
#pragma warning disable CA2000 // False positive, we're adding this disposable object to the global scope, so we can't dispose it
FileTarget fileTarget = new("File") {
ArchiveFileName = Path.Combine("${currentdir}", SharedInfo.ArchivalLogsDirectory, SharedInfo.ArchivalLogFile),
ArchiveNumbering = ArchiveNumberingMode.Rolling,
ArchiveOldFileOnStartup = true,
CleanupFileName = false,
ConcurrentWrites = false,
DeleteOldFileOnStartup = true,
FileName = Path.Combine("${currentdir}", SharedInfo.LogFile),
Layout = GeneralLayout,
MaxArchiveFiles = 10
};
#pragma warning restore CA2000 // False positive, we're adding this disposable object to the global scope, so we can't dispose it
config.AddTarget(fileTarget);
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget));
}
LogManager.Configuration = config;
InitConsoleLoggers();
config.AddTarget(fileTarget);
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget));
}
internal static void InitHistoryLogger() {
if (LogManager.Configuration == null) {
LogManager.Configuration = config;
InitConsoleLoggers();
}
internal static void InitHistoryLogger() {
if (LogManager.Configuration == null) {
return;
}
HistoryTarget? historyTarget = LogManager.Configuration.AllTargets.OfType<HistoryTarget>().FirstOrDefault();
if ((historyTarget == null) && !IsUsingCustomConfiguration) {
historyTarget = new HistoryTarget("History") {
Layout = GeneralLayout,
MaxCount = 20
};
LogManager.Configuration.AddTarget(historyTarget);
LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, historyTarget));
LogManager.ReconfigExistingLoggers();
}
ArchiKestrel.OnNewHistoryTarget(historyTarget);
}
internal static void StartInteractiveConsole() {
if ((ASF.GlobalConfig?.SteamOwnerID ?? GlobalConfig.DefaultSteamOwnerID) == 0) {
ASF.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Strings.InteractiveConsoleNotAvailable, nameof(ASF.GlobalConfig.SteamOwnerID)));
return;
}
Utilities.InBackground(HandleConsoleInteractively, true);
ASF.ArchiLogger.LogGenericInfo(Strings.InteractiveConsoleEnabled);
}
private static async Task BeepUntilCanceled(CancellationToken cancellationToken, byte secondsDelay = 30) {
if (secondsDelay == 0) {
throw new ArgumentOutOfRangeException(nameof(secondsDelay));
}
while (!cancellationToken.IsCancellationRequested) {
try {
await Task.Delay(secondsDelay * 1000, cancellationToken).ConfigureAwait(false);
} catch (TaskCanceledException) {
return;
}
HistoryTarget? historyTarget = LogManager.Configuration.AllTargets.OfType<HistoryTarget>().FirstOrDefault();
if ((historyTarget == null) && !IsUsingCustomConfiguration) {
historyTarget = new HistoryTarget("History") {
Layout = GeneralLayout,
MaxCount = 20
};
LogManager.Configuration.AddTarget(historyTarget);
LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, historyTarget));
LogManager.ReconfigExistingLoggers();
}
ArchiKestrel.OnNewHistoryTarget(historyTarget);
Console.Beep();
}
}
internal static void StartInteractiveConsole() {
if ((ASF.GlobalConfig?.SteamOwnerID ?? GlobalConfig.DefaultSteamOwnerID) == 0) {
ASF.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Strings.InteractiveConsoleNotAvailable, nameof(ASF.GlobalConfig.SteamOwnerID)));
private static string? ConsoleReadLine() {
using CancellationTokenSource cts = new();
return;
}
try {
CancellationToken token = cts.Token;
Utilities.InBackground(HandleConsoleInteractively, true);
ASF.ArchiLogger.LogGenericInfo(Strings.InteractiveConsoleEnabled);
Utilities.InBackground(() => BeepUntilCanceled(token));
return Console.ReadLine();
} finally {
cts.Cancel();
}
}
private static async Task BeepUntilCanceled(CancellationToken cancellationToken, byte secondsDelay = 30) {
if (secondsDelay == 0) {
throw new ArgumentOutOfRangeException(nameof(secondsDelay));
}
private static string ConsoleReadLineMasked(char mask = '*') {
using CancellationTokenSource cts = new();
while (!cancellationToken.IsCancellationRequested) {
try {
await Task.Delay(secondsDelay * 1000, cancellationToken).ConfigureAwait(false);
} catch (TaskCanceledException) {
return;
}
try {
CancellationToken token = cts.Token;
Console.Beep();
}
}
Utilities.InBackground(() => BeepUntilCanceled(token));
private static string? ConsoleReadLine() {
using CancellationTokenSource cts = new();
StringBuilder result = new();
try {
CancellationToken token = cts.Token;
ConsoleKeyInfo keyInfo;
Utilities.InBackground(() => BeepUntilCanceled(token));
while ((keyInfo = Console.ReadKey(true)).Key != ConsoleKey.Enter) {
if (!char.IsControl(keyInfo.KeyChar)) {
result.Append(keyInfo.KeyChar);
Console.Write(mask);
} else if ((keyInfo.Key == ConsoleKey.Backspace) && (result.Length > 0)) {
result.Length--;
return Console.ReadLine();
} finally {
cts.Cancel();
}
}
private static string ConsoleReadLineMasked(char mask = '*') {
using CancellationTokenSource cts = new();
try {
CancellationToken token = cts.Token;
Utilities.InBackground(() => BeepUntilCanceled(token));
StringBuilder result = new();
ConsoleKeyInfo keyInfo;
while ((keyInfo = Console.ReadKey(true)).Key != ConsoleKey.Enter) {
if (!char.IsControl(keyInfo.KeyChar)) {
result.Append(keyInfo.KeyChar);
Console.Write(mask);
} else if ((keyInfo.Key == ConsoleKey.Backspace) && (result.Length > 0)) {
result.Length--;
if (Console.CursorLeft == 0) {
Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
Console.Write(' ');
Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
} else {
Console.Write(Backspace);
}
if (Console.CursorLeft == 0) {
Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
Console.Write(' ');
Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
} else {
Console.Write(Backspace);
}
}
Console.WriteLine();
return result.ToString();
} finally {
cts.Cancel();
}
}
private static async Task HandleConsoleInteractively() {
while (!Program.ShutdownSequenceInitialized) {
Console.WriteLine();
return result.ToString();
} finally {
cts.Cancel();
}
}
private static async Task HandleConsoleInteractively() {
while (!Program.ShutdownSequenceInitialized) {
try {
if (IsWaitingForUserInput || !Console.KeyAvailable) {
continue;
}
await ConsoleSemaphore.WaitAsync().ConfigureAwait(false);
try {
if (IsWaitingForUserInput || !Console.KeyAvailable) {
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
if (keyInfo.Key != ConsoleKey.C) {
continue;
}
await ConsoleSemaphore.WaitAsync().ConfigureAwait(false);
OnUserInputStart();
try {
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
Console.Write($@">> {Strings.EnterCommand}");
string? command = ConsoleReadLine();
if (keyInfo.Key != ConsoleKey.C) {
if (string.IsNullOrEmpty(command)) {
continue;
}
OnUserInputStart();
string? commandPrefix = ASF.GlobalConfig != null ? ASF.GlobalConfig.CommandPrefix : GlobalConfig.DefaultCommandPrefix;
try {
Console.Write($@">> {Strings.EnterCommand}");
string? command = ConsoleReadLine();
// ReSharper disable RedundantSuppressNullableWarningExpression - required for .NET Framework
if (!string.IsNullOrEmpty(commandPrefix) && command!.StartsWith(commandPrefix!, StringComparison.Ordinal)) {
// ReSharper restore RedundantSuppressNullableWarningExpression - required for .NET Framework
if (string.IsNullOrEmpty(command)) {
// ReSharper disable once RedundantSuppressNullableWarningExpression - required for .NET Framework
if (command.Length == commandPrefix!.Length) {
// If the message starts with command prefix and is of the same length as command prefix, then it's just empty command trigger, useless
continue;
}
string? commandPrefix = ASF.GlobalConfig != null ? ASF.GlobalConfig.CommandPrefix : GlobalConfig.DefaultCommandPrefix;
// ReSharper disable RedundantSuppressNullableWarningExpression - required for .NET Framework
if (!string.IsNullOrEmpty(commandPrefix) && command!.StartsWith(commandPrefix!, StringComparison.Ordinal)) {
// ReSharper restore RedundantSuppressNullableWarningExpression - required for .NET Framework
// ReSharper disable once RedundantSuppressNullableWarningExpression - required for .NET Framework
if (command.Length == commandPrefix!.Length) {
// If the message starts with command prefix and is of the same length as command prefix, then it's just empty command trigger, useless
continue;
}
command = command[commandPrefix.Length..];
}
Bot? targetBot = Bot.Bots?.OrderBy(static bot => bot.Key, Bot.BotsComparer).Select(static bot => bot.Value).FirstOrDefault();
if (targetBot == null) {
Console.WriteLine($@"<< {Strings.ErrorNoBotsDefined}");
continue;
}
Console.WriteLine($@"<> {Strings.Executing}");
ulong steamOwnerID = ASF.GlobalConfig?.SteamOwnerID ?? GlobalConfig.DefaultSteamOwnerID;
string? response = await targetBot.Commands.Response(steamOwnerID, command!).ConfigureAwait(false);
if (string.IsNullOrEmpty(response)) {
ASF.ArchiLogger.LogNullError(nameof(response));
Console.WriteLine(Strings.ErrorIsEmpty, nameof(response));
continue;
}
Console.WriteLine($@"<< {response}");
} finally {
OnUserInputEnd();
command = command[commandPrefix.Length..];
}
Bot? targetBot = Bot.Bots?.OrderBy(static bot => bot.Key, Bot.BotsComparer).Select(static bot => bot.Value).FirstOrDefault();
if (targetBot == null) {
Console.WriteLine($@"<< {Strings.ErrorNoBotsDefined}");
continue;
}
Console.WriteLine($@"<> {Strings.Executing}");
ulong steamOwnerID = ASF.GlobalConfig?.SteamOwnerID ?? GlobalConfig.DefaultSteamOwnerID;
string? response = await targetBot.Commands.Response(steamOwnerID, command!).ConfigureAwait(false);
if (string.IsNullOrEmpty(response)) {
ASF.ArchiLogger.LogNullError(nameof(response));
Console.WriteLine(Strings.ErrorIsEmpty, nameof(response));
continue;
}
Console.WriteLine($@"<< {response}");
} finally {
ConsoleSemaphore.Release();
OnUserInputEnd();
}
} catch (Exception e) {
ASF.ArchiLogger.LogGenericException(e);
return;
} finally {
await Task.Delay(ConsoleResponsivenessDelay).ConfigureAwait(false);
ConsoleSemaphore.Release();
}
}
}
} catch (Exception e) {
ASF.ArchiLogger.LogGenericException(e);
private static void InitConsoleLoggers() {
ConsoleLoggingRules.Clear();
foreach (LoggingRule loggingRule in LogManager.Configuration.LoggingRules.Where(static loggingRule => loggingRule.Targets.Any(static target => target is ColoredConsoleTarget or ConsoleTarget))) {
ConsoleLoggingRules.Add(loggingRule);
}
}
private static void OnConfigurationChanged(object? sender, LoggingConfigurationChangedEventArgs e) {
if (e == null) {
throw new ArgumentNullException(nameof(e));
}
InitConsoleLoggers();
if (IsWaitingForUserInput) {
OnUserInputStart();
}
HistoryTarget? historyTarget = LogManager.Configuration.AllTargets.OfType<HistoryTarget>().FirstOrDefault();
ArchiKestrel.OnNewHistoryTarget(historyTarget);
}
private static void OnUserInputEnd() {
IsWaitingForUserInput = false;
if (ConsoleLoggingRules.Count == 0) {
return;
}
bool reconfigure = false;
foreach (LoggingRule consoleLoggingRule in ConsoleLoggingRules.Where(static consoleLoggingRule => !LogManager.Configuration.LoggingRules.Contains(consoleLoggingRule))) {
LogManager.Configuration.LoggingRules.Add(consoleLoggingRule);
reconfigure = true;
}
if (reconfigure) {
LogManager.ReconfigExistingLoggers();
}
}
private static void OnUserInputStart() {
IsWaitingForUserInput = true;
if (ConsoleLoggingRules.Count == 0) {
return;
}
bool reconfigure = false;
foreach (LoggingRule _ in ConsoleLoggingRules.Where(static consoleLoggingRule => LogManager.Configuration.LoggingRules.Remove(consoleLoggingRule))) {
reconfigure = true;
}
if (reconfigure) {
LogManager.ReconfigExistingLoggers();
} finally {
await Task.Delay(ConsoleResponsivenessDelay).ConfigureAwait(false);
}
}
}
private static void InitConsoleLoggers() {
ConsoleLoggingRules.Clear();
foreach (LoggingRule loggingRule in LogManager.Configuration.LoggingRules.Where(static loggingRule => loggingRule.Targets.Any(static target => target is ColoredConsoleTarget or ConsoleTarget))) {
ConsoleLoggingRules.Add(loggingRule);
}
}
private static void OnConfigurationChanged(object? sender, LoggingConfigurationChangedEventArgs e) {
if (e == null) {
throw new ArgumentNullException(nameof(e));
}
InitConsoleLoggers();
if (IsWaitingForUserInput) {
OnUserInputStart();
}
HistoryTarget? historyTarget = LogManager.Configuration.AllTargets.OfType<HistoryTarget>().FirstOrDefault();
ArchiKestrel.OnNewHistoryTarget(historyTarget);
}
private static void OnUserInputEnd() {
IsWaitingForUserInput = false;
if (ConsoleLoggingRules.Count == 0) {
return;
}
bool reconfigure = false;
foreach (LoggingRule consoleLoggingRule in ConsoleLoggingRules.Where(static consoleLoggingRule => !LogManager.Configuration.LoggingRules.Contains(consoleLoggingRule))) {
LogManager.Configuration.LoggingRules.Add(consoleLoggingRule);
reconfigure = true;
}
if (reconfigure) {
LogManager.ReconfigExistingLoggers();
}
}
private static void OnUserInputStart() {
IsWaitingForUserInput = true;
if (ConsoleLoggingRules.Count == 0) {
return;
}
bool reconfigure = false;
foreach (LoggingRule _ in ConsoleLoggingRules.Where(static consoleLoggingRule => LogManager.Configuration.LoggingRules.Remove(consoleLoggingRule))) {
reconfigure = true;
}
if (reconfigure) {
LogManager.ReconfigExistingLoggers();
}
}
}

View File

@@ -27,59 +27,59 @@ using JetBrains.Annotations;
using NLog;
using NLog.Targets;
namespace ArchiSteamFarm.NLog.Targets {
[Target(TargetName)]
internal sealed class HistoryTarget : TargetWithLayout {
internal const string TargetName = "History";
namespace ArchiSteamFarm.NLog.Targets;
private const byte DefaultMaxCount = 20;
[Target(TargetName)]
internal sealed class HistoryTarget : TargetWithLayout {
internal const string TargetName = "History";
internal IEnumerable<string> ArchivedMessages => HistoryQueue;
private const byte DefaultMaxCount = 20;
private readonly FixedSizeConcurrentQueue<string> HistoryQueue = new(DefaultMaxCount);
internal IEnumerable<string> ArchivedMessages => HistoryQueue;
// This is NLog config property, it must have public get() and set() capabilities
[UsedImplicitly]
public byte MaxCount {
get => HistoryQueue.MaxCount;
private readonly FixedSizeConcurrentQueue<string> HistoryQueue = new(DefaultMaxCount);
set {
if (value == 0) {
ASF.ArchiLogger.LogNullError(nameof(value));
// This is NLog config property, it must have public get() and set() capabilities
[UsedImplicitly]
public byte MaxCount {
get => HistoryQueue.MaxCount;
return;
}
set {
if (value == 0) {
ASF.ArchiLogger.LogNullError(nameof(value));
HistoryQueue.MaxCount = value;
}
}
// This parameter-less constructor is intentionally public, as NLog uses it for creating targets
// It must stay like this as we want to have our targets defined in our NLog.config
[UsedImplicitly]
public HistoryTarget() { }
internal HistoryTarget(string name) : this() => Name = name;
protected override void Write(LogEventInfo logEvent) {
if (logEvent == null) {
throw new ArgumentNullException(nameof(logEvent));
return;
}
base.Write(logEvent);
string message = Layout.Render(logEvent);
HistoryQueue.Enqueue(message);
NewHistoryEntry?.Invoke(this, new NewHistoryEntryArgs(message));
}
internal event EventHandler<NewHistoryEntryArgs>? NewHistoryEntry;
internal sealed class NewHistoryEntryArgs : EventArgs {
internal readonly string Message;
internal NewHistoryEntryArgs(string message) => Message = message ?? throw new ArgumentNullException(nameof(message));
HistoryQueue.MaxCount = value;
}
}
// This parameter-less constructor is intentionally public, as NLog uses it for creating targets
// It must stay like this as we want to have our targets defined in our NLog.config
[UsedImplicitly]
public HistoryTarget() { }
internal HistoryTarget(string name) : this() => Name = name;
protected override void Write(LogEventInfo logEvent) {
if (logEvent == null) {
throw new ArgumentNullException(nameof(logEvent));
}
base.Write(logEvent);
string message = Layout.Render(logEvent);
HistoryQueue.Enqueue(message);
NewHistoryEntry?.Invoke(this, new NewHistoryEntryArgs(message));
}
internal event EventHandler<NewHistoryEntryArgs>? NewHistoryEntry;
internal sealed class NewHistoryEntryArgs : EventArgs {
internal readonly string Message;
internal NewHistoryEntryArgs(string message) => Message = message ?? throw new ArgumentNullException(nameof(message));
}
}

View File

@@ -33,107 +33,107 @@ using NLog.Config;
using NLog.Layouts;
using NLog.Targets;
namespace ArchiSteamFarm.NLog.Targets {
[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
[Target(TargetName)]
internal sealed class SteamTarget : AsyncTaskTarget {
internal const string TargetName = "Steam";
namespace ArchiSteamFarm.NLog.Targets;
// This is NLog config property, it must have public get() and set() capabilities
[UsedImplicitly]
public Layout? BotName { get; set; }
[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
[Target(TargetName)]
internal sealed class SteamTarget : AsyncTaskTarget {
internal const string TargetName = "Steam";
// This is NLog config property, it must have public get() and set() capabilities
[UsedImplicitly]
public ulong ChatGroupID { get; set; }
// This is NLog config property, it must have public get() and set() capabilities
[UsedImplicitly]
public Layout? BotName { get; set; }
// This is NLog config property, it must have public get() and set() capabilities
[RequiredParameter]
[UsedImplicitly]
public ulong SteamID { get; set; }
// This is NLog config property, it must have public get() and set() capabilities
[UsedImplicitly]
public ulong ChatGroupID { get; set; }
// This parameter-less constructor is intentionally public, as NLog uses it for creating targets
// It must stay like this as we want to have our targets defined in our NLog.config
// Keeping date in default layout also doesn't make much sense (Steam offers that), so we remove it by default
public SteamTarget() => Layout = "${level:uppercase=true}|${logger}|${message}";
// This is NLog config property, it must have public get() and set() capabilities
[RequiredParameter]
[UsedImplicitly]
public ulong SteamID { get; set; }
protected override async Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken) {
if (logEvent == null) {
throw new ArgumentNullException(nameof(logEvent));
}
// This parameter-less constructor is intentionally public, as NLog uses it for creating targets
// It must stay like this as we want to have our targets defined in our NLog.config
// Keeping date in default layout also doesn't make much sense (Steam offers that), so we remove it by default
public SteamTarget() => Layout = "${level:uppercase=true}|${logger}|${message}";
base.Write(logEvent);
if ((SteamID == 0) || (Bot.Bots == null) || Bot.Bots.IsEmpty) {
return;
}
string message = Layout.Render(logEvent);
if (string.IsNullOrEmpty(message)) {
return;
}
Bot? bot = null;
string? botName = BotName?.Render(logEvent);
if (!string.IsNullOrEmpty(botName)) {
// ReSharper disable once RedundantSuppressNullableWarningExpression - required for .NET Framework
bot = Bot.GetBot(botName!);
if (bot?.IsConnectedAndLoggedOn != true) {
return;
}
}
Task task;
if (ChatGroupID != 0) {
task = SendGroupMessage(message, bot);
} else if (bot?.SteamID != SteamID) {
task = SendPrivateMessage(message, bot);
} else {
return;
}
await task.ConfigureAwait(false);
protected override async Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken) {
if (logEvent == null) {
throw new ArgumentNullException(nameof(logEvent));
}
private async Task SendGroupMessage(string message, Bot? bot = null) {
if (string.IsNullOrEmpty(message)) {
throw new ArgumentNullException(nameof(message));
}
base.Write(logEvent);
if (bot == null) {
bot = Bot.Bots?.Values.FirstOrDefault(static targetBot => targetBot.IsConnectedAndLoggedOn);
if ((SteamID == 0) || (Bot.Bots == null) || Bot.Bots.IsEmpty) {
return;
}
if (bot == null) {
return;
}
}
string message = Layout.Render(logEvent);
if (!await bot.SendMessage(ChatGroupID, SteamID, message).ConfigureAwait(false)) {
bot.ArchiLogger.LogGenericTrace(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, nameof(Bot.SendMessage)));
if (string.IsNullOrEmpty(message)) {
return;
}
Bot? bot = null;
string? botName = BotName?.Render(logEvent);
if (!string.IsNullOrEmpty(botName)) {
// ReSharper disable once RedundantSuppressNullableWarningExpression - required for .NET Framework
bot = Bot.GetBot(botName!);
if (bot?.IsConnectedAndLoggedOn != true) {
return;
}
}
private async Task SendPrivateMessage(string message, Bot? bot = null) {
if (string.IsNullOrEmpty(message)) {
throw new ArgumentNullException(nameof(message));
}
Task task;
if (ChatGroupID != 0) {
task = SendGroupMessage(message, bot);
} else if (bot?.SteamID != SteamID) {
task = SendPrivateMessage(message, bot);
} else {
return;
}
await task.ConfigureAwait(false);
}
private async Task SendGroupMessage(string message, Bot? bot = null) {
if (string.IsNullOrEmpty(message)) {
throw new ArgumentNullException(nameof(message));
}
if (bot == null) {
bot = Bot.Bots?.Values.FirstOrDefault(static targetBot => targetBot.IsConnectedAndLoggedOn);
if (bot == null) {
bot = Bot.Bots?.Values.FirstOrDefault(targetBot => targetBot.IsConnectedAndLoggedOn && (targetBot.SteamID != SteamID));
if (bot == null) {
return;
}
return;
}
}
if (!await bot.SendMessage(SteamID, message).ConfigureAwait(false)) {
bot.ArchiLogger.LogGenericTrace(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, nameof(Bot.SendMessage)));
if (!await bot.SendMessage(ChatGroupID, SteamID, message).ConfigureAwait(false)) {
bot.ArchiLogger.LogGenericTrace(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, nameof(Bot.SendMessage)));
}
}
private async Task SendPrivateMessage(string message, Bot? bot = null) {
if (string.IsNullOrEmpty(message)) {
throw new ArgumentNullException(nameof(message));
}
if (bot == null) {
bot = Bot.Bots?.Values.FirstOrDefault(targetBot => targetBot.IsConnectedAndLoggedOn && (targetBot.SteamID != SteamID));
if (bot == null) {
return;
}
}
if (!await bot.SendMessage(SteamID, message).ConfigureAwait(false)) {
bot.ArchiLogger.LogGenericTrace(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, nameof(Bot.SendMessage)));
}
}
}