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

Update unturned obsolete code #779

Merged
merged 9 commits into from
Nov 7, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion framework/OpenMod.Core/Commands/CommandContextBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public ICommandContext CreateContext(ICommandActor actor, string[] args, string
{
var exceptionContext = new CommandContext(null, actor, args.First(), prefix, args.Skip(1).ToList(), m_LifetimeScope.BeginLifetimeScopeEx());
var localizer = m_LifetimeScope.Resolve<IOpenModStringLocalizer>();
exceptionContext.Exception = new CommandNotFoundException(localizer["commands:errors:not_found", new { CommandName = args[0], Args = args }]);
exceptionContext.Exception = new CommandNotFoundException(localizer["commands:errors:not_found", new { CommandName = args[0], Args = args }]!);
//await actor.PrintMessageAsync(Color.Red, exceptionContext.Exception.Message);
return exceptionContext;
}
Expand Down
4 changes: 2 additions & 2 deletions framework/OpenMod.Core/Commands/CommandParameters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public async Task<object> GetAsync(int index, Type type)

if (Length <= index)
{
throw new CommandIndexOutOfRangeException(m_OpenModStringLocalizer["commands:errors:out_of_range_error", new { Index = index, Type = type, Length }], index, Length);
throw new CommandIndexOutOfRangeException(m_OpenModStringLocalizer["commands:errors:out_of_range_error", new { Index = index, Type = type, Length }]!, index, Length);
}

if (index < 0)
Expand All @@ -63,7 +63,7 @@ public async Task<object> GetAsync(int index, Type type)
return value;
}

throw new CommandParameterParseException(m_OpenModStringLocalizer["commands:errors:parse_error", new { Value = arg, Type = type }], arg, type);
throw new CommandParameterParseException(m_OpenModStringLocalizer["commands:errors:parse_error", new { Value = arg, Type = type }]!, arg, type);
}

/// <inheritdoc />
Expand Down
2 changes: 1 addition & 1 deletion framework/OpenMod.Core/Commands/CommandStoreOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public IReadOnlyCollection<ICommandSource> CreateCommandSources(IServiceProvider

foreach (var type in m_CommandSourceTypes)
{
sources.Add((ICommandSource)ActivatorUtilitiesEx.CreateInstance(lifetime, type));
sources.Add((ICommandSource)ActivatorUtilitiesEx.CreateInstance(lifetime!, type));
}

return sources;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public CommandWrongUsageException(string message) : base(message)
}

public CommandWrongUsageException(ICommandContext context, IOpenModStringLocalizer localizer)
: base(localizer["commands:errors:wrong_usage", new { Command = context.CommandPrefix + context.CommandAlias, Args = string.Join(" ", context.Parameters), context.CommandRegistration!.Syntax }])
: base(localizer["commands:errors:wrong_usage", new { Command = context.CommandPrefix + context.CommandAlias, Args = string.Join(" ", context.Parameters), context.CommandRegistration!.Syntax }]!)
{
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace OpenMod.Core.Commands
public class NotEnoughPermissionException : UserFriendlyException
{
public NotEnoughPermissionException(IOpenModStringLocalizer stringLocalizer, string permission)
: base(stringLocalizer["commands:errors:not_enough_permission", new { Permission = permission }])
: base(stringLocalizer["commands:errors:not_enough_permission", new { Permission = permission }]!)
{
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ protected override async Task OnExecuteAsync()
if (context.CommandRegistration == null)
{
await PrintAsync(m_StringLocalizer["commands:errors:not_found",
new { CommandName = context.GetCommandLine(includeArguments: false) }], Color.Red);
new { CommandName = context.GetCommandLine(includeArguments: false) }]!, Color.Red);
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ protected override async Task OnExecuteAsync()
if (allowedActors.All(d =>
d.Trim() != "*" && !Context.Actor.Type.Equals(d.Trim(), StringComparison.OrdinalIgnoreCase)))
{
throw new UserFriendlyException(m_StringLocalizer["commands:openmod:restricted"]);
throw new UserFriendlyException(m_StringLocalizer["commands:openmod:restricted"]!);
}

var args = Context.Parameters.ToList();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public class CommandOpenModRemove : Command
public CommandOpenModRemove(
IOpenModStringLocalizer stringLocalizer,
IConfiguration configuration,
IServiceProvider serviceProvider,
IServiceProvider serviceProvider,
NuGetPluginAssembliesSource nuGetPlugis) : base(serviceProvider)
{
m_StringLocalizer = stringLocalizer;
Expand All @@ -44,7 +44,7 @@ protected override async Task OnExecuteAsync()
var allowedActors = m_Configuration.GetSection("nuget:remove:allowedActors").Get<string[]>();
if (allowedActors.All(d => d.Trim() != "*" && !Context.Actor.Type.Equals(d.Trim(), StringComparison.OrdinalIgnoreCase)))
{
throw new UserFriendlyException(this.m_StringLocalizer["commands:openmod:restricted"]);
throw new UserFriendlyException(this.m_StringLocalizer["commands:openmod:restricted"]!);
}

string packageName = Context.Parameters[0];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,12 @@ public bool Supports(Type type)
}
catch (Exception ex) when (ex.InnerException is OverflowException)
{
var parseException = new CommandParameterParseException(m_OpenModStringLocalizer["commands:errors:overflow_error", new { Value = input, Type = type }], input, type);
var parseException = new CommandParameterParseException(m_OpenModStringLocalizer["commands:errors:overflow_error", new { Value = input, Type = type }]!, input, type);
return Task.FromException<object?>(parseException);
}
catch (Exception ex) when (ex.InnerException is FormatException)
{
var parseException = new CommandParameterParseException(m_OpenModStringLocalizer["commands:errors:parse_error", new { Value = input, Type = type }], input, type);
var parseException = new CommandParameterParseException(m_OpenModStringLocalizer["commands:errors:parse_error", new { Value = input, Type = type }]!, input, type);
return Task.FromException<object?>(parseException);
}
}
Expand Down
2 changes: 1 addition & 1 deletion framework/OpenMod.Core/Cooldowns/CommandEventListener.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public async Task HandleEventAsync(object? sender, CommandExecutingEvent @event)
var spanSinceLast = DateTime.Now - lastExecuted.Value;
if (spanSinceLast < cooldownSpan)
{
@event.CommandContext.Exception = new UserFriendlyException(m_StringLocalizer["commands:errors:cooldown", new { TimeLeft = cooldownSpan - spanSinceLast }]);
@event.CommandContext.Exception = new UserFriendlyException(m_StringLocalizer["commands:errors:cooldown", new { TimeLeft = cooldownSpan - spanSinceLast }]!);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ public static class ContainerBuilderExtensions
else
{
Log.Information("Descriptor: instance {ServiceType}, {ImplementationType}",
descriptor.ServiceType, descriptor.ImplementationInstance.GetType());
descriptor.ServiceType, descriptor.ImplementationInstance!.GetType());
var registrator = containerBuilder
.RegisterInstance(descriptor.ImplementationInstance)
.As(descriptor.ServiceType)
Expand Down
6 changes: 3 additions & 3 deletions framework/OpenMod.Core/Users/OfflineUserProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public bool SupportsUserType(string userType)
{
return null;
}

return new OfflineUser(this, m_UserDataStore, data);
}

Expand All @@ -57,7 +57,7 @@ public Task BroadcastAsync(string message, Color? color)
{
return Task.CompletedTask;
}

public Task<bool> BanAsync(IUser user, string? reason = null, DateTime? endTime = null)
{
return BanAsync(user, instigator: null, reason, endTime);
Expand All @@ -76,7 +76,7 @@ public async Task<bool> BanAsync(IUser user, IUser? instigator = null, string? r

expireDate ??= DateTime.MaxValue;
reason ??= m_StringLocalizer["ban_default"];
data.BanInfo = new BanData(reason, instigator, expireDate);
data.BanInfo = new BanData(reason!, instigator, expireDate);

await m_UserDataStore.SetUserDataAsync(data);
return true;
Expand Down
4 changes: 2 additions & 2 deletions framework/OpenMod.NuGet/NuGetAssembly.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ public sealed class NuGetAssembly
public string AssemblyName
{
get { return AssemblyName2.Name; }
set { /* ignore set */ }
set { AssemblyName2.Name = value; }
}
public AssemblyName AssemblyName2 { get; set; } = null!;

[Obsolete("Use " + nameof(AssemblyName2) + ".Version")]
public Version Version
{
get { return AssemblyName2.Version; }
set { /* ignore set */ }
set { AssemblyName2.Version = value; }
}

public WeakReference Assembly { get; set; } = null!;
Expand Down
108 changes: 70 additions & 38 deletions framework/OpenMod.Runtime/Runtime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public Runtime()

public string WorkingDirectory { get; private set; } = null!;

public string[] CommandlineArgs { get; private set; } = new string[0];
public string[] CommandlineArgs { get; private set; } = Array.Empty<string>();

public IDataStore DataStore { get; private set; } = null!;

Expand Down Expand Up @@ -107,14 +107,16 @@ public void Init(List<Assembly> openModAssemblies, RuntimeInitParameters paramet

var hostInformationType = openModHostAssemblies
.Select(asm =>
AssemblyExtensions.GetLoadableTypes(asm)
asm.GetLoadableTypes()
.FirstOrDefault(t => typeof(IHostInformation).IsAssignableFrom(t)))
.LastOrDefault(d => d != null);

#pragma warning disable IDE0270
if (hostInformationType == null)
{
throw new Exception("Failed to find IHostInformation in host assemblies.");
}
#pragma warning restore IDE0270

HostInformation = (IHostInformation)Activator.CreateInstance(hostInformationType);
m_OpenModHostAssemblies = openModHostAssemblies;
Expand Down Expand Up @@ -236,7 +238,7 @@ public void Init(List<Assembly> openModAssemblies, RuntimeInitParameters paramet
ConfigureAppConfiguration(context, builder, startup);
})
.ConfigureContainer<ContainerBuilder>(builder => SetupContainer(builder, startup))
.ConfigureServices((context, services) =>
.ConfigureServices((_, services) =>
{
SetupServices(services, startup);
})
Expand Down Expand Up @@ -313,6 +315,8 @@ public async Task PerformSoftReloadAsync()
await InitAsync(m_OpenModHostAssemblies!, m_RuntimeInitParameters!, m_HostBuilderFunc);
}

private static readonly Type s_FileSytemWatcherType = typeof(FileSystemWatcher);

private void PerformFileSystemWatcherPatch()
{
if (!RuntimeEnvironmentHelper.IsMono)
Expand All @@ -324,29 +328,57 @@ private void PerformFileSystemWatcherPatch()
{
using var tempFileSystemWatcher = new FileSystemWatcher();

var internalWatcher = typeof(FileSystemWatcher)
.GetField("watcher", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(tempFileSystemWatcher);
var internalWatcherField = s_FileSytemWatcherType
.GetField("watcher", BindingFlags.Instance | BindingFlags.NonPublic);

if (internalWatcherField == null)
{
m_Logger.LogWarning("Fail to obtain file system watcher.");
return;
}

var internalWatcher = internalWatcherField.GetValue(tempFileSystemWatcher);
m_Logger.LogInformation("Using watcher: {FileWatcherImplementation}", internalWatcher.GetType().Name);
return;
}

var watcher = typeof(FileSystemWatcher).Assembly
.GetType("System.IO.DefaultWatcher")
.GetField("instance", BindingFlags.Static | BindingFlags.NonPublic)
.GetValue(null);
var defaultWatcherType = s_FileSytemWatcherType.Assembly
.GetType("System.IO.DefaultWatcher");
if (defaultWatcherType == null)
{
m_Logger.LogWarning("Fail to obtain default watcher type.");
return;
}

var watcherType = watcher.GetType();
var watcherInstanceField = defaultWatcherType.GetField("instance", BindingFlags.Static | BindingFlags.NonPublic);
if (watcherInstanceField == null)
{
m_Logger.LogWarning("Fail to obtain watcher istance.");
return;
}

if (watcherType
.GetField("watches", BindingFlags.Static | BindingFlags.NonPublic)
.GetValue(watcher) is not Hashtable watches)
var watcherInstance = watcherInstanceField.GetValue(null);
var watcherType = watcherInstance.GetType();
var watchesField = watcherType.GetField("watches", BindingFlags.Static | BindingFlags.NonPublic);

if (watchesField == null)
{
throw new Exception("watches is not Hashtable");
m_Logger.LogWarning("Fail to obtain watches field.");
return;
}

if (watchesField.GetValue(watcherInstance) is not Hashtable watches)
{
m_Logger.LogWarning("Watches is not Hashtable.");
return;
}

var createFileDataMethod = watcherType.GetMethod("CreateFileData", BindingFlags.Static | BindingFlags.NonPublic);
if (createFileDataMethod == null)
{
m_Logger.LogWarning("Watcher CreateFileData not found.");
return;
}

lock (watches)
{
Expand All @@ -367,7 +399,7 @@ private void PerformFileSystemWatcherPatch()
var watcherDataType = entry.Value.GetType();

incSubdirsField ??= watcherDataType.GetField("IncludeSubdirs", BindingFlags.Public | BindingFlags.Instance);
if (incSubdirsField?.GetValue(entry.Value) is bool incSubdirs && !incSubdirs)
if (incSubdirsField?.GetValue(entry.Value) is false)//convert to bool and check if false
{
continue;
}
Expand Down Expand Up @@ -422,7 +454,7 @@ private void ConfigureConfiguration(IConfigurationBuilder builder, OpenModStartu

private void ConfigureAppConfiguration(HostBuilderContext? hostBuilderContext, IConfigurationBuilder builder, OpenModStartup? startup = null)
{
m_DateLogger ??= DateTime.Now;
var dateLogger = m_DateLogger ??= DateTime.Now;

if (hostBuilderContext != null && startup?.Context is OpenModStartupContext context)
{
Expand All @@ -440,15 +472,15 @@ private void ConfigureAppConfiguration(HostBuilderContext? hostBuilderContext, I
s.Variables = new Dictionary<string, string>
{
{ "workingDirectory", WorkingDirectory.Replace(@"\", "/") },
{ "date", m_DateLogger.Value.ToString("yyyy-MM-dd-HH-mm-ss") }
{ "date", dateLogger.ToString("yyyy-MM-dd-HH-mm-ss") }
};
});
}

private void SetupServices(IServiceCollection services, OpenModStartup startup)
{
services.AddSingleton<IRuntime>(this);
services.AddSingleton(HostInformation);
services.AddSingleton(HostInformation!);
services.AddHostedService<OpenModHostedService>();
services.AddOptions();
services.AddSingleton(((OpenModStartupContext)startup.Context).NuGetPackageManager);
Expand All @@ -462,10 +494,7 @@ private void SetupContainer(ContainerBuilder containerBuilder, OpenModStartup st

private void SetupSerilog(LoggerConfiguration? loggerConfiguration = null, IConfiguration? configuration = null)
{
Serilog.Debugging.SelfLog.Enable(s =>
{
Console.WriteLine(s);
});
Serilog.Debugging.SelfLog.Enable(Console.WriteLine);

Log.CloseAndFlush();
loggerConfiguration ??= new LoggerConfiguration();
Expand Down Expand Up @@ -521,26 +550,28 @@ private void SetupSerilog(LoggerConfiguration? loggerConfiguration = null, IConf
}

// setup global log only for first time (before loading NuGet packages)
if (m_LoggerFactory == null)
if (m_LoggerFactory != null)
{
Log.Logger = loggerConfiguration.CreateLogger();
m_LoggerFactory = new SerilogLoggerFactory();
m_Logger = m_LoggerFactory.CreateLogger<Runtime>();
return;
}

void SetupDefaultLogger(LoggerConfiguration configuration)
{
const string defaultConsoleLogTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}][{SourceContext}] {Message:lj}{NewLine}{Exception}";
const string defaultFileLogTemplate = "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}][{SourceContext}] {Message:lj}{NewLine}{Exception}";
Log.Logger = loggerConfiguration.CreateLogger();
m_LoggerFactory = new SerilogLoggerFactory();
m_Logger = m_LoggerFactory.CreateLogger<Runtime>();
}

m_DateLogger ??= DateTime.Now;
var logFilePath = $"{WorkingDirectory}/logs/openmod-{m_DateLogger:yyyy-MM-dd-HH-mm-ss}.log"
.Replace(@"\", "/");
private void SetupDefaultLogger(LoggerConfiguration loggerConfiguration)
{
const string defaultConsoleLogTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}][{SourceContext}] {Message:lj}{NewLine}{Exception}";
const string defaultFileLogTemplate = "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}][{SourceContext}] {Message:lj}{NewLine}{Exception}";

configuration
.WriteTo.Async(c => c.Console(LogEventLevel.Information, defaultConsoleLogTemplate))
.WriteTo.Async(c => c.File(logFilePath, LogEventLevel.Information, outputTemplate: defaultFileLogTemplate));
}
m_DateLogger ??= DateTime.Now;
var logFilePath = $"{WorkingDirectory}/logs/openmod-{m_DateLogger:yyyy-MM-dd-HH-mm-ss}.log"
.Replace(@"\", "/");

loggerConfiguration
.WriteTo.Async(c => c.Console(LogEventLevel.Information, defaultConsoleLogTemplate))
.WriteTo.Async(c => c.File(logFilePath, LogEventLevel.Information, outputTemplate: defaultFileLogTemplate));
}

public async Task ShutdownAsync()
Expand All @@ -564,6 +595,7 @@ public async Task ShutdownAsync()
m_DateLogger = null;
m_LoggerFactory = null;
m_Logger = null;

Log.CloseAndFlush();
}
}
Expand Down
2 changes: 1 addition & 1 deletion samples/UserDatabasePlugin/Commands/CommandLookup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ protected override async Task OnExecuteAsync()

if (lastJoinTime == null)
{
throw new UserFriendlyException(m_StringLocalizer["user_not_found", new { User = userNameOrId }]);
throw new UserFriendlyException(m_StringLocalizer["user_not_found", new { User = userNameOrId }]!);
}

await PrintAsync($"Id: {userId}");
Expand Down
Loading
Loading