Example #1
0
        public async Task <IVehicleShop> AddVehicleShopBuyable(string id, decimal price)
        {
            var data = await GetVehicleShopData(id);

            var dbContext = GetDbContext();

            if (data == null)
            {
                data = new VehicleShopModel
                {
                    VehicleId = id,
                    BuyPrice  = price
                };

                await dbContext.VehicleShops.AddAsync(data);
            }
            else
            {
                data.BuyPrice = price;

                dbContext.VehicleShops.Update(data);
            }

            await dbContext.SaveChangesAsync();

            return(ActivatorUtilitiesEx.CreateInstance <VehicleShop>(GetPluginScope(), data));
        }
Example #2
0
        public async Task <IItemShop> AddItemShopSellable(string id, decimal price)
        {
            var data = await GetItemShopData(id);

            var dbContext = GetDbContext();

            if (data == null)
            {
                data = new ItemShopModel
                {
                    ItemId    = id,
                    SellPrice = price
                };

                await dbContext.ItemShops.AddAsync(data);
            }
            else
            {
                data.SellPrice = price;

                dbContext.ItemShops.Update(data);
            }

            await dbContext.SaveChangesAsync();

            return(ActivatorUtilitiesEx.CreateInstance <ItemShop>(GetPluginScope(), data));
        }
Example #3
0
        public JobScheduler(
            IRuntime runtime,
            ILogger <JobScheduler> logger,
            IDataStoreFactory dataStoreFactory,
            IOptions <JobExecutorOptions> options)
        {
            m_Runtime = runtime;
            m_Logger  = logger;

            m_DataStore = dataStoreFactory.CreateDataStore(new DataStoreCreationParameters
            {
                Component        = runtime,
                LogOnChange      = true,
                WorkingDirectory = runtime.WorkingDirectory
            });

            AsyncHelper.RunSync(ReadJobsFileAsync);

            m_ScheduledJobs = new List <ScheduledJob>();
            m_DataStore.AddChangeWatcher(c_DataStoreKey, runtime, () =>
            {
                m_ScheduledJobs.Clear();
                AsyncHelper.RunSync(() => StartAsync(isFromFileChange: true));
            });

            m_JobExecutors = new List <ITaskExecutor>();
            foreach (var provider in options.Value.JobExecutorTypes)
            {
                m_JobExecutors.Add(
                    (ITaskExecutor)ActivatorUtilitiesEx.CreateInstance(runtime.LifetimeScope, provider));
            }
        }
Example #4
0
        public IDataStore CreateDataStore(DataStoreCreationParameters parameters)
        {
            var lifetime = parameters.Component?.LifetimeScope
                           ?? m_ServiceProvider.GetRequiredService <IRuntime>().LifetimeScope;

            return(ActivatorUtilitiesEx.CreateInstance <YamlDataStore>(lifetime, parameters));
        }
Example #5
0
        [EventListener(Priority = EventListenerPriority.Lowest)] // Lowest so it starts up as early as possible
        public Task HandleEventAsync(object?sender, OpenModInitializedEvent @event)
        {
            var bind = m_OpenModConfiguration.GetSection("rcon:bind").Get <string>();
            var cancellationToken = GetCancellationToken();
            var sourceRconEnabled = m_OpenModConfiguration.GetSection("rcon:srcds:enabled").Get <bool>();

            if (sourceRconEnabled)
            {
                var port               = m_OpenModConfiguration.GetSection("rcon:srcds:port").Get <int>();
                var endpoint           = new IPEndPoint(IPAddress.Parse(bind), port);
                var sourceRconListener = ActivatorUtilitiesEx.CreateInstance <SourceRconHost>(m_Runtime.LifetimeScope);

                Task.Run(() => sourceRconListener.StartListeningAsync(endpoint, cancellationToken), cancellationToken);
            }

            var minecraftRconEnabled = m_OpenModConfiguration.GetSection("rcon:minecraft:enabled").Get <bool>();

            if (minecraftRconEnabled)
            {
                var port     = m_OpenModConfiguration.GetSection("rcon:minecraft:port").Get <int>();
                var endpoint = new IPEndPoint(IPAddress.Parse(bind), port);
                var minecraftRconListener = ActivatorUtilitiesEx.CreateInstance <MinecraftRconHost>(m_Runtime.LifetimeScope);

                Task.Run(() => minecraftRconListener.StartListeningAsync(endpoint, cancellationToken), cancellationToken);
            }

            return(Task.CompletedTask);
        }
        public async Task InitAsync(ILifetimeScope lifetimeScope)
        {
            if (m_LifetimeScope != null && lifetimeScope != m_LifetimeScope)
            {
                return;
            }

            m_LifetimeScope = lifetimeScope;
            var configuration = lifetimeScope.Resolve <IConfiguration>();

            m_Plugin = lifetimeScope.Resolve <Kits>();

            var configType = configuration["database:connectionType"];
            var database   = m_Options.GetPreferredDatabase(configType);

            if (database == null)
            {
                m_Database = ActivatorUtilitiesEx.CreateInstance <DataStoreKitDatabase>(lifetimeScope);
                m_Logger.LogWarning(
                    $"Unable to parse {configType}. Setting to default: `datastore`");
            }
            else
            {
                m_Logger.LogInformation($"Datastore type set to `{configType}`");
                m_Database = (IKitDatabaseProvider)ActivatorUtilitiesEx.CreateInstance(lifetimeScope, database);
            }

            m_ConfigurationChangedWatcher = m_EventBus.Subscribe <PluginConfigurationChangedEvent>(m_Plugin,
                                                                                                   PluginConfigurationChanged);

            await m_Database.LoadDatabaseAsync();

            await RegisterPermissionsAsync();
        }
Example #7
0
        private void StartRocketModRcon(string bind, int port)
        {
            var cancellationToken  = GetCancellationToken();
            var endpoint           = new IPEndPoint(IPAddress.Parse(bind), port);
            var rocketRconListener = ActivatorUtilitiesEx.CreateInstance <RocketModRconHost>(m_Runtime.LifetimeScope);

            Task.Run(() => rocketRconListener.StartListeningAsync(endpoint, cancellationToken), cancellationToken);
        }
Example #8
0
        public async Task <IVehicleShop?> GetVehicleShop(string id)
        {
            var data = await GetVehicleShopData(id);

            return(data == null
                ? null
                : ActivatorUtilitiesEx.CreateInstance <VehicleShop>(GetPluginScope(), data));
        }
Example #9
0
        public UserManager(IOptions <UserManagerOptions> options, ILifetimeScope lifetimeScope)
        {
            m_UserProviders = new List <IUserProvider>();

            foreach (var provider in options.Value.UserProviderTypes)
            {
                m_UserProviders.Add((IUserProvider)ActivatorUtilitiesEx.CreateInstance(lifetimeScope, provider));
            }
        }
Example #10
0
        public static TContainer WithOpenModConsole <TContainer>(
            this TContainer @this,
            string baseRoute,
            IServiceProvider serviceProvider)
            where TContainer : class, IWebModuleContainer
        {
            var lifetime = serviceProvider.GetRequiredService <ILifetimeScope>();
            var module   = ActivatorUtilitiesEx.CreateInstance <OpenModConsoleModule>(lifetime, baseRoute);

            return(@this.WithModule(module));
        }
Example #11
0
        public Task InitAsync()
        {
            foreach (var permissionSourceType in m_Options.Value.PermissionSources)
            {
                m_PermissionSources.Add((IPermissionStore)ActivatorUtilitiesEx.CreateInstance(m_LifetimeScope, permissionSourceType));
            }

            foreach (var permissionCheckProviderType in m_Options.Value.PermissionCheckProviders)
            {
                m_PermissionCheckProviders.Add((IPermissionCheckProvider)ActivatorUtilitiesEx.CreateInstance(m_LifetimeScope, permissionCheckProviderType));
            }

            return(Task.CompletedTask);
        }
Example #12
0
        public static TContainer WithOpenModFileSystem <TContainer>(
            this TContainer @this,
            string baseRoute,
            IServiceProvider serviceProvider,
            Action <OpenModFileSystemModule> configure)
            where TContainer : class, IWebModuleContainer
        {
            configure = Validate.NotNull(nameof(configure), configure);

            var lifetime = serviceProvider.GetRequiredService <ILifetimeScope>();
            var module   = ActivatorUtilitiesEx.CreateInstance <OpenModFileSystemModule>(lifetime, baseRoute);

            return(@this.WithModule(module, configure));
        }
        private Task CreateDatabaseProvider()
        {
            var dataBaseType = DbStoreType switch
            {
                StoreType.DataStore => typeof(DataStoreDatabase),
                StoreType.LiteDb => typeof(LiteDbDatabase),
                StoreType.MySql => typeof(MySqlDatabase),
                StoreType.UserData => typeof(UserDataDatabase),
                _ => throw new ArgumentOutOfRangeException(nameof(DbStoreType), DbStoreType, null)
            };

            // ReSharper disable once PossibleNullReferenceException
            m_Database = ActivatorUtilitiesEx.CreateInstance(LifetimeScope, dataBaseType) as IEconomyProvider;
            return(m_Database is MySqlDatabase mySqlDatabase?mySqlDatabase.CheckShemasAsync() : Task.CompletedTask);
        }
Example #14
0
        public void ActivateEventListeners()
        {
            m_Logger.LogTrace("Activating oxide events listeners");

            foreach (var type in FindListenerTypes())
            {
                var eventsListener = (OxideEventsListenerBase)ActivatorUtilitiesEx.CreateInstance(m_LifetimeScope, type);
                m_RustEventsListeners.Add(eventsListener);
            }

            foreach (var eventsListener in m_RustEventsListeners)
            {
                Interface.Oxide.RootPluginManager.AddPlugin(eventsListener);
            }
        }
        public ICommand Instantiate(IServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            if (CommandType != null)
            {
                var lifetime = serviceProvider.GetRequiredService <ILifetimeScope>();
                return((ICommand)ActivatorUtilitiesEx.CreateInstance(lifetime, CommandType));
            }

            return(new MethodCommandWrapper(CommandMethod !, serviceProvider));
        }
Example #16
0
        protected override async UniTask OnLoadAsync()
        {
            await UniTask.SwitchToThreadPool();

            RegisterPermissions();

            await RegisterDataStores();

            m_TpaRequestManager.SetLocalizer(m_StringLocalizer);

            // https://github.com/aspnet/Configuration/issues/451
            m_BroadcastingService.Configure(m_Configuration.GetValue <ushort>("broadcasting:effectId"),
                                            m_Configuration.GetSection("broadcasting:repeatingMessages").Get <string[]>(),
                                            m_Configuration.GetValue <int>("broadcasting:repeatingInterval"),
                                            m_Configuration.GetValue <int>("broadcasting:repeatingDuration"));

            ActivatorUtilitiesEx.CreateInstance <AfkChecker>(LifetimeScope);
        }
Example #17
0
        public void Install()
        {
            if (!IsRocketModInstalled())
            {
                return;
            }

            if (!IsRocketModUnturnedLoaded(out _))
            {
                return;
            }

            if (m_Installed)
            {
                return;
            }

            m_Logger.LogInformation("RocketMod is installed, enabling RocketMod integration");

            m_HarmonyInstance = new Harmony(c_HarmonyId);
            m_HarmonyInstance.PatchAllConditional(typeof(OpenModUnturnedHost).Assembly, "rocketmod");
            m_EventBus.Subscribe <CommandExecutedEvent>(m_RocketModComponent, (services, sender, @event) =>
            {
                var scope    = services.GetRequiredService <ILifetimeScope>();
                var listener = ActivatorUtilitiesEx.CreateInstance <RocketModCommandEventListener>(scope);
                return(listener.HandleEventAsync(sender, @event));
            });

            if (U.Settings != null)
            {
                // Rocketmod already initialized
                OnRocketModIntialized();
                OnRocketModPluginsLoaded();
            }
            else
            {
                PatchInitialize();
                PatchLogging();
                PatchPluginsLoaded();
                PatchRcon();
            }

            m_Installed = true;
        }
Example #18
0
        public IReadOnlyCollection <ICommandSource> CreateCommandSources(IServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            var lifetime = serviceProvider.GetService <ILifetimeScope>();
            var sources  = new List <ICommandSource>();

            sources.AddRange(m_CommandSources);

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

            return(sources);
        }
Example #19
0
        public void ActivateEventListeners()
        {
            m_Logger.LogTrace("Activating unturned events listeners");

            var listenerTypes = GetType().Assembly.FindTypes <IUnturnedEventsListener>(false).ToList();

            foreach (var type in listenerTypes)
            {
                var eventsListener = (IUnturnedEventsListener)ActivatorUtilitiesEx.CreateInstance(m_LifetimeScope, type);
                m_UnturnedEventsListeners.Add(eventsListener);
            }

            foreach (var eventsListener in m_UnturnedEventsListeners)
            {
                eventsListener.Subscribe();
            }

            Provider.clients.Do(SubscribePlayer);

            Provider.onEnemyConnected    += SubscribePlayer;
            Provider.onEnemyDisconnected += UnsubscribePlayer;
        }
Example #20
0
 public CommandParameterResolver(
     ILifetimeScope lifetimeScope,
     IOptions <CommandParameterResolverOptions> options)
 {
     m_CommandParameterResolveProviders = options.Value.CommandParameterResolverTypes
                                          .Select(type => (ICommandParameterResolveProvider)ActivatorUtilitiesEx.CreateInstance(lifetimeScope, type))
                                          .ToList();
 }
Example #21
0
        public Task InitAsync()
        {
            try
            {
                if (RocketModIntegration.IsRocketModInstalled())
                {
                    var rocketModIntegration = ActivatorUtilitiesEx.CreateInstance <RocketModIntegration>(LifetimeScope);
                    rocketModIntegration.Install();
                }
            }
            catch (Exception ex)
            {
                m_Logger.LogError(ex, "Failed to integrate with RocketMod");
            }

            // ReSharper disable PossibleNullReferenceException
            IsComponentAlive = true;

            try
            {
                m_Harmony = new Harmony(OpenModComponentId);
                m_Harmony.PatchAll(GetType().Assembly);
            }
            catch (Exception ex)
            {
                m_Logger.LogError(ex, "Failed to patch with Harmony. Report this error on the OpenMod discord: https://discord.com/invite/jRrCJVm");
            }

            m_UnturnedCommandHandler.Value.Subscribe();
            BindUnturnedEvents();

            var ioHandlers = (List <ICommandInputOutput>) typeof(CommandWindow)
                             .GetField("ioHandlers", BindingFlags.NonPublic | BindingFlags.Instance)
                             .GetValue(Dedicator.commandWindow);

            CommandLineFlag?shouldManageConsole = null;
            var             previousShouldManageConsoleValue = true;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                /* Fix Unturned destroying console and breaking Serilog formatting and colors */
                var windowsConsole           = typeof(Provider).Assembly.GetType("SDG.Unturned.WindowsConsole");
                var shouldManageConsoleField = windowsConsole?.GetField("shouldManageConsole",
                                                                        BindingFlags.Static | BindingFlags.NonPublic);

                if (shouldManageConsoleField != null)
                {
                    shouldManageConsole = (CommandLineFlag)shouldManageConsoleField.GetValue(null);
                    previousShouldManageConsoleValue = shouldManageConsole.value;
                    shouldManageConsole.value        = false;
                }
            }

            m_IoHandlers = ioHandlers.ToList(); // copy Unturneds IoHandlers
            // unturned built-in io handlers
            var defaultIoHandlers = ioHandlers.Where(c =>
                                                     c.GetType().FullName
                                                     .Equals("SDG.Unturned.ThreadedWindowsConsoleInputOutput") || // type doesnt exist on Linux
                                                     c.GetType().FullName.Equals("SDG.Unturned.WindowsConsoleInputOutput") || // type doesnt exist on Linux
                                                     c.GetType() == typeof(ThreadedConsoleInputOutput) ||
                                                     c.GetType() == typeof(ConsoleInputOutput)).ToList();

            foreach (var ioHandler in defaultIoHandlers)
            {
                Dedicator.commandWindow.removeIOHandler(ioHandler);
            }

            if (shouldManageConsole != null)
            {
                shouldManageConsole.value = previousShouldManageConsoleValue;
            }

            m_OpenModIoHandler = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                ? ActivatorUtilities.CreateInstance <OpenModWindowsConsoleInputOutput>(m_ServiceProvider)
                : ActivatorUtilities.CreateInstance <OpenModConsoleInputOutput>(m_ServiceProvider);

            Dedicator.commandWindow.addIOHandler(m_OpenModIoHandler);

            m_Logger.LogInformation("OpenMod for Unturned v{HostVersion} is initializing...",
                                    m_HostInformation.HostVersion);

            m_Logger.LogInformation("OpenMod for Unturned is ready");

            return(Task.CompletedTask);
            // ReSharper restore PossibleNullReferenceException
        }
Example #22
0
 protected virtual Task <TClient> CreateRconClientAsync(TcpClient tcpClient)
 {
     return(Task.FromResult(ActivatorUtilitiesEx.CreateInstance <TClient>(m_LifetimeScope, tcpClient, this)));
 }
Example #23
0
        public async Task <IOpenModPlugin?> TryActivatePluginAsync(Assembly assembly)
        {
            try
            {
                if (m_IsDisposing)
                {
                    throw new ObjectDisposedException(nameof(PluginActivator));
                }

                var pluginMetadata = assembly.GetCustomAttribute <PluginMetadataAttribute>();
                if (pluginMetadata == null)
                {
                    m_Logger.LogError(
                        $"Failed to load plugin from assembly {assembly}: couldn't find any plugin metadata");
                    return(null);
                }

                var pluginTypes = assembly.FindTypes <IOpenModPlugin>().ToList();
                if (pluginTypes.Count == 0)
                {
                    m_Logger.LogError(
                        $"Failed to load plugin from assembly {assembly}: couldn't find any IOpenModPlugin implementation");
                    return(null);
                }

                if (pluginTypes.Count > 1)
                {
                    m_Logger.LogError(
                        $"Failed to load plugin from assembly {assembly}: assembly has multiple IOpenModPlugin instances");
                    return(null);
                }

                var            pluginType = pluginTypes.Single();
                IOpenModPlugin pluginInstance;
                try
                {
                    var lifetimeScope = m_LifetimeScope.BeginLifetimeScopeEx(containerBuilder =>
                    {
                        var workingDirectory = PluginHelper.GetWorkingDirectory(m_Runtime, pluginMetadata.Id);

                        var configurationBuilder = new ConfigurationBuilder();
                        if (Directory.Exists(workingDirectory))
                        {
                            configurationBuilder
                            .SetBasePath(workingDirectory)
                            .AddYamlFile("config.yaml", optional: true, reloadOnChange: true);
                        }

                        var configuration = configurationBuilder
                                            .AddEnvironmentVariables(pluginMetadata.Id.Replace(".", "_") + "_")
                                            .Build();

                        containerBuilder.Register(_ => configuration)
                        .As <IConfiguration>()
                        .As <IConfigurationRoot>()
                        .SingleInstance()
                        .OwnedByLifetimeScope();

                        containerBuilder.RegisterType(pluginType)
                        .AsSelf()
                        .As <IOpenModComponent>()
                        .As <IOpenModPlugin>()
                        .SingleInstance()
                        .OwnedByLifetimeScope();

                        containerBuilder.RegisterType <ScopedPermissionChecker>()
                        .As <IPermissionChecker>()
                        .InstancePerLifetimeScope()
                        .OwnedByLifetimeScope();

                        containerBuilder.Register(_ => m_DataStoreFactory.CreateDataStore(new DataStoreCreationParameters
                        {
#pragma warning disable 618
                            ComponentId = pluginMetadata.Id,
#pragma warning restore 618
                            Prefix           = null,
                            Suffix           = "data",
                            WorkingDirectory = workingDirectory
                        }))
                        .As <IDataStore>()
                        .SingleInstance()
                        .OwnedByLifetimeScope();

                        var stringLocalizer = Directory.Exists(workingDirectory)
                            ? m_StringLocalizerFactory.Create("translations", workingDirectory)
                            : NullStringLocalizer.Instance;

                        containerBuilder.Register(_ => stringLocalizer)
                        .As <IStringLocalizer>()
                        .SingleInstance()
                        .OwnedByLifetimeScope();

                        var services =
                            ServiceRegistrationHelper.FindFromAssembly <PluginServiceImplementationAttribute>(assembly,
                                                                                                              m_Logger);

                        var servicesRegistrations = services.OrderBy(d => d.Priority,
                                                                     new PriorityComparer(PriortyComparisonMode.LowestFirst));

                        foreach (var servicesRegistration in servicesRegistrations)
                        {
                            var implementationType = servicesRegistration.ServiceImplementationType;
                            containerBuilder.RegisterType(implementationType)
                            .As(implementationType)
                            .WithLifetime(servicesRegistration.Lifetime)
                            .OwnedByLifetimeScope();

                            foreach (var service in servicesRegistration.ServiceTypes)
                            {
                                containerBuilder.Register(c => c.Resolve(implementationType))
                                .As(service)
                                .WithLifetime(servicesRegistration.Lifetime)
                                .OwnedByLifetimeScope();
                            }
                        }

                        foreach (var type in pluginType.Assembly.FindTypes <IPluginContainerConfigurator>())
                        {
                            var configurator = (IPluginContainerConfigurator)ActivatorUtilitiesEx.CreateInstance(m_LifetimeScope, type);
                            configurator.ConfigureContainer(new PluginServiceConfigurationContext(m_LifetimeScope, configuration, containerBuilder));
                        }

                        var configurationEvent = new PluginContainerConfiguringEvent(pluginMetadata, pluginType,
                                                                                     configuration, containerBuilder, workingDirectory);
                        AsyncHelper.RunSync(() => m_EventBus.EmitAsync(m_Runtime, this, configurationEvent));
                    });

                    pluginInstance = (IOpenModPlugin)lifetimeScope.Resolve(pluginType);

                    var pluginLoggerType = typeof(ILogger <>).MakeGenericType(pluginType);
                    var pluginLogger     = (ILogger)pluginInstance.LifetimeScope.Resolve(pluginLoggerType);

                    RegisterConfigChangeCallback(pluginInstance, pluginLogger);

                    var pluginActivateEvent = new PluginActivatingEvent(pluginInstance);
                    await m_EventBus.EmitAsync(m_Runtime, this, pluginActivateEvent);

                    if (pluginActivateEvent.IsCancelled)
                    {
                        await lifetimeScope.DisposeAsync();

                        return(null);
                    }
                }
                catch (Exception ex)
                {
                    m_Logger.LogError(ex,
                                      $"Failed to load plugin from type: {pluginType.FullName} in assembly: {assembly.FullName}");
                    return(null);
                }

                try
                {
                    await pluginInstance.LoadAsync();

                    var serviceProvider  = pluginInstance.LifetimeScope.Resolve <IServiceProvider>();
                    var pluginHelpWriter = ActivatorUtilities.CreateInstance <PluginHelpWriter>(serviceProvider);
                    await pluginHelpWriter.WriteHelpFileAsync();
                }
                catch (Exception ex)
                {
                    m_Logger.LogError(ex, $"Failed to load plugin: {pluginInstance.DisplayName} v{pluginInstance.Version}");

                    try
                    {
                        await pluginInstance.LifetimeScope.DisposeAsync();
                    }
                    catch (Exception e)
                    {
                        m_Logger.LogError(e, "Failed to unload plugin: {DisplayName} v{Version}", pluginInstance.DisplayName, pluginInstance.Version);
                    }

                    return(null);
                }

                m_ActivatedPlugins.Add(new WeakReference(pluginInstance));
                return(pluginInstance);
            }
            catch (Exception ex)
            {
                m_Logger.LogError(ex, $"Failed to load plugin from assembly: {assembly.FullName}");
                return(null);
            }
        }
Example #24
0
        public Task InitAsync()
        {
            if (RocketModIntegration.IsRocketModInstalled())
            {
                var rocketModIntegration = ActivatorUtilitiesEx.CreateInstance <RocketModIntegration>(LifetimeScope);
                rocketModIntegration.Install();
            }

            // ReSharper disable PossibleNullReferenceException
            IsComponentAlive = true;

            m_Harmony = new Harmony(OpenModComponentId);
            m_Harmony.PatchAll(GetType().Assembly);

            m_UnturnedCommandHandler.Value.Subscribe();
            BindUnturnedEvents();

            var ioHandlers = (List <ICommandInputOutput>) typeof(CommandWindow)
                             .GetField("ioHandlers", BindingFlags.NonPublic | BindingFlags.Instance)
                             .GetValue(Dedicator.commandWindow);

            CommandLineFlag?shouldManageConsole = null;
            var             previousShouldManageConsoleValue = true;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                /* Fix Unturned destroying console and breaking Serilog formatting and colors */
                var windowsConsole           = typeof(Provider).Assembly.GetType("SDG.Unturned.WindowsConsole");
                var shouldManageConsoleField = windowsConsole?.GetField("shouldManageConsole",
                                                                        BindingFlags.Static | BindingFlags.NonPublic);

                if (shouldManageConsoleField != null)
                {
                    shouldManageConsole = (CommandLineFlag)shouldManageConsoleField.GetValue(null);
                    previousShouldManageConsoleValue = shouldManageConsole.value;
                    shouldManageConsole.value        = false;
                }
            }

            m_IoHandlers = ioHandlers.ToList(); // copy Unturneds IoHandlers
            // unturned built-in io handlers
            var defaultIoHandlers = ioHandlers.Where(c =>
                                                     c.GetType().FullName
                                                     .Equals("SDG.Unturned.ThreadedWindowsConsoleInputOutput") || // type doesnt exist on Linux
                                                     c.GetType().FullName.Equals("SDG.Unturned.WindowsConsoleInputOutput") || // type doesnt exist on Linux
                                                     c.GetType() == typeof(ThreadedConsoleInputOutput) ||
                                                     c.GetType() == typeof(ConsoleInputOutput)).ToList();

            foreach (var ioHandler in defaultIoHandlers)
            {
                Dedicator.commandWindow.removeIOHandler(ioHandler);
            }

            if (shouldManageConsole != null)
            {
                shouldManageConsole.value = previousShouldManageConsoleValue;
            }

            m_OpenModIoHandler = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                ? ActivatorUtilities.CreateInstance <OpenModWindowsConsoleInputOutput>(m_ServiceProvider)
                : ActivatorUtilities.CreateInstance <OpenModConsoleInputOutput>(m_ServiceProvider);

            Dedicator.commandWindow.addIOHandler(m_OpenModIoHandler);

            m_Logger.LogInformation($"OpenMod for Unturned v{m_HostInformation.HostVersion} is initializing...");

            TlsWorkaround.Install();

            if (!s_UniTaskInited)
            {
                var unitySynchronizationContetextField =
                    typeof(PlayerLoopHelper).GetField("unitySynchronizationContetext",
                                                      BindingFlags.Static | BindingFlags.NonPublic);
                unitySynchronizationContetextField.SetValue(null, SynchronizationContext.Current);

                var mainThreadIdField =
                    typeof(PlayerLoopHelper).GetField("mainThreadId", BindingFlags.Static | BindingFlags.NonPublic);
                mainThreadIdField.SetValue(null, Thread.CurrentThread.ManagedThreadId);

                var playerLoop = PlayerLoop.GetDefaultPlayerLoop();
                PlayerLoopHelper.Initialize(ref playerLoop);
                s_UniTaskInited = true;
            }

            m_Logger.LogInformation("OpenMod for Unturned is ready.");

            return(Task.CompletedTask);
            // ReSharper restore PossibleNullReferenceException
        }
        private OpenModController CreateComponentFactory(Type type, IOpenModComponent component)
        {
            var scope = component.LifetimeScope.BeginLifetimeScope("AutofacWebRequest");

            return((OpenModController)ActivatorUtilitiesEx.CreateInstance(scope, type));
        }
Example #26
0
        public Task HandleEventAsync(object sender, RocketModPluginsLoadedEvent @event)
        {
            var permissionSystem = m_UnturnedConfiguration.Configuration
                                   .GetSection("rocketmodIntegration:permissionSystem")
                                   .Get <string>();

            if (permissionSystem.Equals("OpenMod", StringComparison.OrdinalIgnoreCase))
            {
                var scope = m_RocketModComponent.LifetimeScope;
                var permissionProxyProvider = ActivatorUtilitiesEx.CreateInstance <RocketModPermissionProxyProvider>(scope);
                permissionProxyProvider.Install();
            }

            var economySystem = m_UnturnedConfiguration.Configuration
                                .GetSection("rocketmodIntegration:economySystem")
                                .Get <string>();

            if (economySystem.Equals("OpenMod_Uconomy", StringComparison.OrdinalIgnoreCase))
            {
                var uconomyAssembly = UconomyIntegration.GetUconomyAssembly();
                if (uconomyAssembly != null)
                {
                    var databaseType    = uconomyAssembly.GetType("fr34kyn01535.Uconomy.DatabaseManager");
                    var harmonyInstance = new Harmony(UconomyIntegration.HarmonyId);

                    var getBalanceMethod       = databaseType.GetMethod("GetBalance", c_BindingFlags);
                    var getBalancePrefixMethod = typeof(UconomyGetBalancePatch)
                                                 .GetMethod(nameof(UconomyGetBalancePatch.GetBalancePrefix), c_BindingFlags);
                    harmonyInstance.Patch(getBalanceMethod, prefix: new HarmonyMethod(getBalancePrefixMethod));

                    var increaseBalancePrefixMethod = typeof(UconomyBalanceIncreasePatch)
                                                      .GetMethod(nameof(UconomyBalanceIncreasePatch.IncreaseBalancePrefix), c_BindingFlags);
                    var increaseBalanceMethod = databaseType.GetMethod("IncreaseBalance", c_BindingFlags);
                    harmonyInstance.Patch(increaseBalanceMethod, prefix: new HarmonyMethod(increaseBalancePrefixMethod));

                    var checkSchemaMethod = databaseType.GetMethod("CheckSchema", c_BindingFlags) !;
                    harmonyInstance.NopPatch(checkSchemaMethod);

                    var checkSetupAccount = databaseType.GetMethod("CheckSetupAccount", c_BindingFlags) !;
                    harmonyInstance.NopPatch(checkSetupAccount);

                    var executeQueryMethod       = databaseType.GetMethod("ExecuteQuery", c_BindingFlags);
                    var executeQueryPrefixMethod = typeof(UconomyExecuteQueryPatch)
                                                   .GetMethod(nameof(UconomyExecuteQueryPatch.ExecuteQueryPrefix), c_BindingFlags);
                    harmonyInstance.Patch(executeQueryMethod, prefix: new HarmonyMethod(executeQueryPrefixMethod));

                    UconomyGetBalancePatch.OnPreGetBalance           += OnPreGetBalance;
                    UconomyBalanceIncreasePatch.OnPreIncreaseBalance += OnPreIncreaseBalance;

                    m_RocketModComponent.LifetimeScope.Disposer.AddInstanceForDisposal(new DisposeAction(() =>
                    {
                        harmonyInstance.UnpatchAll(UconomyIntegration.HarmonyId);

                        UconomyGetBalancePatch.OnPreGetBalance           -= OnPreGetBalance;
                        UconomyBalanceIncreasePatch.OnPreIncreaseBalance -= OnPreIncreaseBalance;
                    }));
                }
                else
                {
                    var logger = m_LoggerFactory.CreateLogger <RocketModIntegration>();
                    logger.LogWarning("Economy system was set to OpenMod_Uconomy but Uconomy is not loaded. Defaulting to Separate.");
                }
            }

            RemoveRocketCommandListeners();
            return(Task.CompletedTask);
        }