Esempio n. 1
0
        protected override void Load()
        {
            try {
                var stopwatch = Stopwatch.StartNew();

                Instance      = this;
                R.Permissions = new EssentialsPermissionsProvider();

                Provider.onServerDisconnected += PlayerDisconnectCallback;
                Provider.onServerConnected    += PlayerConnectCallback;

                Logger           = new EssLogger("[uEssentials] ");
                ConnectedPlayers = new Dictionary <ulong, UPlayer>();

                Logger.Log("Enabling uEssentials.", ConsoleColor.Green);

                if (Provider.Players.Count > 0)
                {
                    Provider.Players.ForEach(p => {
                        ConnectedPlayers.Add(p.SteamPlayerID.CSteamID.m_SteamID,
                                             new UPlayer(UnturnedPlayer.FromSteamPlayer(p)));
                    });
                }

                _folder            = Rocket.Core.Environment.PluginsDirectory + "/uEssentials/";
                _translationFolder = Folder + "translations/";
                _dataFolder        = Folder + "data/";
                _modulesFolder     = Folder + "modules/";

                var configPath = $"{Folder}config.json";

                Config = new EssConfig();
                Config.Load(configPath);

                if (Config.WebConfig.Enabled)
                {
                    var conf = new EssWebConfig();
                    conf.Load(configPath);
                    Config = conf;
                }

                CommandsConfig = new CommandsConfig();
                CommandsConfig.Load($"{Folder}commands.json");

                Updater        = new GithubUpdater();
                EventManager   = new EventManager();
                CommandManager = new CommandManager();
                ModuleManager  = new ModuleManager();
                HookManager    = new HookManager();

                EssLang.Load();

                Logger.Log("Plugin version: ", ConsoleColor.Green, suffix: "");

                #if EXPERIMENTAL
                const string label = "experimental"
                    #if EXPERIMENTAL_HASH
                                     + "-commit-$COMMIT_HASH$"
                    #endif
                ;

                Logger.Log($"{PLUGIN_VERSION} {label}", ConsoleColor.White, "");
                #else
                Logger.Log(PLUGIN_VERSION, ConsoleColor.White, "");
                #endif

                Logger.Log("Recommended Rocket version: ", ConsoleColor.Green, suffix: "");
                Logger.Log(ROCKET_VERSION, ConsoleColor.White, "");
                Logger.Log("Recommended Unturned version: ", ConsoleColor.Green, suffix: "");
                Logger.Log(UNTURNED_VERSION, ConsoleColor.White, "");
                Logger.Log("Author: ", ConsoleColor.Green, suffix: "");
                Logger.Log("leonardosc", ConsoleColor.White, "");
                Logger.Log("Wiki: ", ConsoleColor.Green, suffix: "");
                Logger.Log("uessentials.github.io", ConsoleColor.White, "");

                EventManager.RegisterAll(GetType().Assembly);

                if (!Config.EnableJoinLeaveMessage)
                {
                    EventManager.Unregister <EssentialsEventHandler>("JoinMessage");
                    EventManager.Unregister <EssentialsEventHandler>("LeaveMessage");
                }

                CommandManager.RegisterAll("Essentials.Commands");

                HookManager.RegisterAll();
                HookManager.LoadAll();

                if (Config.Economy.UseXp)
                {
                    EconomyProvider = Optional <IEconomyProvider> .Of(new ExpEconomyProvider());
                }
                else if (HookManager.GetActiveByType <UconomyHook>().IsPresent)
                {
                    EconomyProvider = Optional <IEconomyProvider> .Of(
                        HookManager.GetActiveByType <UconomyHook>().Value);
                }
                else
                {
                    EconomyProvider = Optional <IEconomyProvider> .Empty();
                }

                /*
                 *  Load native modules
                 */
                (
                    from type in Assembly.GetTypes()
                    where typeof(NativeModule).IsAssignableFrom(type)
                    where !type.IsAbstract
                    let mAttr = (ModuleInfo)type.GetCustomAttributes(typeof(ModuleInfo), false)[0]
                                where Config.EnabledSystems.Any(s => s.Equals(mAttr.Name, StringComparison.OrdinalIgnoreCase))
                                select type
                ).ForEach(type => {
                    ModuleManager.LoadModule((NativeModule)Activator.CreateInstance(type));
                });

                Logger.LogInfo($"Loaded {CommandManager.Commands.Count()} commands");

                Logger.LogInfo("Loading modules...");
                ModuleManager.LoadAll(ModulesFolder);
                Logger.LogInfo($"Loaded {ModuleManager.RunningModules.Count(t => !(t is NativeModule))} modules");

                if (Config.AutoAnnouncer.Enabled)
                {
                    Config.AutoAnnouncer.Start();
                }

                if (Config.AutoCommands.Enabled)
                {
                    Config.AutoCommands.Start();
                }

                if (!Config.Updater.AlertOnJoin)
                {
                    EventManager.Unregister <EssentialsEventHandler>("UpdateAlert");
                }

                if (Config.ServerFrameRate != -1)
                {
                    var frameRate = Config.ServerFrameRate;

                    if (Config.ServerFrameRate < -1)
                    {
                        frameRate = -1; // Set to default
                    }

                    UnityEngine.Application.targetFrameRate = frameRate;
                }

                if (Config.DisabledCommands.Count != 0)
                {
                    Config.DisabledCommands.ForEach(cmdName => {
                        var command = CommandManager.GetByName(cmdName);

                        if (command == null || command is CommandEssentials)
                        {
                            Logger.LogWarning($"There is no command named '{cmdName}' to disable.");
                        }
                        else
                        {
                            CommandManager.Unregister(command);
                            Logger.LogInfo($"Disabled command: '{command.Name}'");
                        }
                    });
                }

                if (Config.EnableTextCommands)
                {
                    var textCommandsFile = $"{Folder}textcommands.json";

                    TextCommands = new TextCommands();
                    TextCommands.Load(textCommandsFile);

                    TextCommands.Commands.ForEach(txtCommand => {
                        CommandManager.Register(new TextCommand(txtCommand));
                    });
                }

                if (!Config.EnableDeathMessages)
                {
                    EventManager.Unregister <EssentialsEventHandler>("DeathMessages");
                }

                #if EXPERIMENTAL
                Logger.LogWarning("THIS IS AN EXPERIMENTAL BUILD, CAN BE BUGGY.");
                Logger.LogWarning("THIS IS AN EXPERIMENTAL BUILD, CAN BE BUGGY.");
                #endif

                TryAddComponent <Tasks.TaskExecutor>();

                Tasks.New(t => {
                    File.Delete($"{Folder}uEssentials.en.translation.xml");
                    File.Delete($"{Folder}uEssentials.configuration.xml");
                }).Delay(100).Go();

                Tasks.New(t => {
                    UnregisterRocketCommands(true); // Second check, silently.
                }).Delay(3000).Go();

                CommandWindow.ConsoleInput.onInputText += ReloadCallback;
                UnregisterRocketCommands(); // First check.
                Logger.Log($"Enabled ({stopwatch.ElapsedMilliseconds} ms)", ConsoleColor.Green);
            } catch (Exception e) {
                var msg = new List <string>()
                {
                    "An error occurred while enabling uEssentials.",
                    "If this error is not related with wrong configuration please report",
                    "immediatly here https://github.com/uEssentials/uEssentials/issues",
                    "Error: " + e
                };

                if (!Provider.Version.EqualsIgnoreCase(UNTURNED_VERSION))
                {
                    msg.Add("I detected that you are using an different version of the recommended, " +
                            "please update your uEssentials/Unturned.");
                    msg.Add("If you are using the latest uEssentials release, please wait for update.");
                }

                if (Logger == null)
                {
                    Console.BackgroundColor = ConsoleColor.Red;
                    msg.ForEach(Console.WriteLine);
                    Console.BackgroundColor = ConsoleColor.White;
                }
                else
                {
                    msg.ForEach(Logger.LogError);
                }
            }

            #if DEV
            CommandWindow.ConsoleOutput.title = "Unturned Server";
            #else
            CheckUpdates();
            #endif

            #if DUMP_COMMANDS
            DumpCommands();
            #endif
        }
Esempio n. 2
0
        public UpdateResult CheckUpdate()
        {
            lock (this)
            {
                var result = new UpdateResult(
                    EssCore.PLUGIN_VERSION,
                    ToDecimalVersion(EssCore.PLUGIN_VERSION),
                    string.Empty
                    );

                try
                {
                    var httpRequest = (HttpWebRequest)WebRequest.Create(ReleasesUrl);
                    httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";
                    var respStream = httpRequest.GetResponse().GetResponseStream();

                    if (respStream == null)
                    {
                        throw new Exception("request returned null response");
                    }

                    using (var reader = new StreamReader(respStream))
                    {
                        var jsonData      = reader.ReadToEnd();
                        var jsonObj       = JObject.Parse(jsonData);
                        var latestVersion = jsonObj.GetValue("tag_name");

                        if (latestVersion == null)
                        {
                            throw new Exception("latest version not found.");
                        }

                        var latestVersionDecimal  = ToDecimalVersion(latestVersion.ToString());
                        var currentVersionDecimal = ToDecimalVersion(EssCore.PLUGIN_VERSION);

                        if (currentVersionDecimal < latestVersionDecimal)
                        {
                            var additionalData = new JObject();
                            var body           = jsonObj.GetValue("body")?.ToString() ?? "";
                            var assets         = jsonObj.GetValue("assets").Children <JObject>();

                            additionalData.Add("changes", body);
                            additionalData.Add("download_url", assets.First().GetValue("browser_download_url")?.ToString() ?? "null");

                            result = new UpdateResult(
                                latestVersion.ToString(),
                                latestVersionDecimal,
                                additionalData.ToString()
                                );
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogWarning("Could not check update!");
                    Logger.LogWarning(ex.Message);
                }

                return(LastResult = result);
            }
        }