public static List <string> ListOfPlayersInParty()
        {
            var playersInParty = new List <string>();

            try
            {
                var baseWindow = new CustomIngameUIElements(GameController.Instance.Game.IngameState.IngameUi.Address).PartyList;
                if (baseWindow != null)
                {
                    var partyList = baseWindow.Children[0]?.Children[0]?.Children;
                    foreach (var player in partyList)
                    {
                        if (player != null && player.ChildCount > 3)
                        {
                            playersInParty.Add(player?.Children[0]?.AsObject <EntityLabel>()?.Text);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                BasePlugin.LogError("Character: " + e.Message, 5);
            }

            return(playersInParty);
        }
Beispiel #2
0
        public bool Save()
        {
            var playerName = LocalPlayer.Name;

            // shit fix for null player name
            if (string.IsNullOrEmpty(playerName))
            {
                while (string.IsNullOrEmpty(GameController.Instance.Game.IngameState.Data.LocalPlayer.GetComponent <Player>().PlayerName))
                {
                    Thread.Sleep(5);
                    BasePlugin.LogError("CharacterData: Null or Empty Name", 10);
                }
                playerName = GameController.Instance.Game.IngameState.Data.LocalPlayer.GetComponent <Player>().PlayerName;
            }

            var path = string.Format("{0}\\Level Logs\\{1}", PluginDirectory, playerName);

            if (!MakeFolder(new DirectoryInfo(path)))
            {
                BasePlugin.LogError("Failed to make Directoryies", 10f);
                return(false);
            }

            try
            {
                File.AppendAllText(string.Format("{0}\\Log.txt", path), DataToString(true) + Environment.NewLine);
            }
            catch
            {
                return(false);
            }

            return(true);
        }
Beispiel #3
0
 private static void CheckAddPlugin(List <AvailablePlugin> AllAvailablePlugins, AvailablePlugin currentPlugin, int i)
 {
     if (currentPlugin != null)
     {
         if (string.IsNullOrEmpty(currentPlugin.PluginName))
         {
             BasePlugin.LogError($"AvailablePluginsConfigParser: Empty plugin name! (Under line: {i - 1})", 10);
         }
         else if (string.IsNullOrEmpty(currentPlugin.GitName))
         {
             BasePlugin.LogError($"AvailablePluginsConfigParser: No parameter GitName in plugin: {currentPlugin.PluginName}", 10);
         }
         else if (string.IsNullOrEmpty(currentPlugin.GitOwner))
         {
             BasePlugin.LogError($"AvailablePluginsConfigParser: No parameter GitOwner in plugin: {currentPlugin.PluginName}", 10);
         }
         else if (string.IsNullOrEmpty(currentPlugin.GitConfigURL))
         {
             BasePlugin.LogError($"AvailablePluginsConfigParser: No parameter GitConfigURL in plugin: {currentPlugin.PluginName}", 10);
         }
         else
         {
             AllAvailablePlugins.Add(currentPlugin);
         }
     }
 }
Beispiel #4
0
        private void OnSettingsToggle()
        {
            try
            {
                if (Settings.Enable.Value)
                {
                    GameController.Area.OnAreaChange += OnAreaChange;
                    GameController.Area.RefreshState();

                    isTown = GameController.Area.CurrentArea.IsTown;

                    keyboard     = new KeyboardHelper(GameController);
                    targetNumber = 0;

                    if (Settings.ChaosGolem.Value)
                    {
                        targetNumber += Settings.ChaosGolemMax.Value;
                    }
                    if (Settings.FireGolem.Value)
                    {
                        targetNumber += Settings.FireGolemMax.Value;
                    }
                    if (Settings.IceGolem.Value)
                    {
                        targetNumber += Settings.IceGolemMax.Value;
                    }
                    if (Settings.LightningGolem.Value)
                    {
                        targetNumber += Settings.LightningGolemMax.Value;
                    }
                    if (Settings.StoneGolem.Value)
                    {
                        targetNumber += Settings.StoneGolemMax.Value;
                    }

                    stopwatch.Reset();

                    var checkThread = new Thread(CheckThread)
                    {
                        IsBackground = true
                    };
                    checkThread.Start();
                }
                else
                {
                    GameController.Area.OnAreaChange -= OnAreaChange;

                    stopwatch.Stop();
                }
            }
            catch (Exception err)
            {
                BasePlugin.LogError(err, 5);
            }
        }
Beispiel #5
0
        private void GetDrawersRecurs(List <BaseSettingsDrawer> drawers, List <BaseSettingsDrawer> result)
        {
            foreach (var drawer in drawers)
            {
                if (!result.Contains(drawer))
                {
                    result.Add(drawer);
                }
                else
                {
                    BasePlugin.LogError($"{PluginName}: Possible stashoverflow or duplicating drawers detected while generating menu. Drawer SettingName: {drawer.SettingName}, Id: {drawer.SettingId}", 5);
                }
            }

            drawers.ForEach(x => GetDrawersRecurs(x.Children, result));
        }
        public static List <PartyElementWindow> GetPlayerInfoElementList(List <EntityWrapper> entityList)
        {
            var playersInParty = new List <PartyElementWindow>();

            try
            {
                var baseWindow = new CustomIngameUIElements(GameController.Instance.Game.IngameState.IngameUi.Address).PartyList;
                if (baseWindow != null)
                {
                    var partElementList = baseWindow.Children[0]?.Children[0]?.Children;
                    if (partElementList != null)
                    {
                        foreach (var partyElement in partElementList)
                        {
                            var playerName = partyElement?.Children[0]?.AsObject <EntityLabel>()?.Text;

                            var newElement = new PartyElementWindow();
                            newElement.PlayerName = playerName;

                            // get entity
                            foreach (var entity in entityList)
                            {
                                if (entity != null && entity.GetComponent <Player>().PlayerName == playerName)
                                {
                                    newElement.Data.PlayerEntity = entity;
                                }
                            }


                            //get party element
                            newElement.Element = partyElement;


                            playersInParty.Add(newElement);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                BasePlugin.LogError("CharacterData.GetPlayerInfoElementList(): " + e.Message, 5);
            }

            return(playersInParty);
        }
Beispiel #7
0
        public static void ApplyTheme(ThemeConfig theme)
        {
            var style = ImGui.GetStyle();

            style.AntiAliasedLines       = theme.AntiAliasedLines;
            style.DisplaySafeAreaPadding = theme.DisplaySafeAreaPadding;
            style.DisplayWindowPadding   = theme.DisplayWindowPadding;
            style.GrabRounding           = theme.GrabRounding;
            style.GrabMinSize            = theme.GrabMinSize;
            style.ScrollbarRounding      = theme.ScrollbarRounding;
            style.ScrollbarSize          = theme.ScrollbarSize;
            style.ColumnsMinSpacing      = theme.ColumnsMinSpacing;
            style.IndentSpacing          = theme.IndentSpacing;
            style.TouchExtraPadding      = theme.TouchExtraPadding;
            style.ItemInnerSpacing       = theme.ItemInnerSpacing;

            style.ItemSpacing         = theme.ItemSpacing;
            style.FrameRounding       = theme.FrameRounding;
            style.FramePadding        = theme.FramePadding;
            style.ChildWindowRounding = theme.ChildWindowRounding;
            style.WindowTitleAlign    = theme.WindowTitleAlign;
            style.WindowRounding      = theme.WindowRounding;
            //style.WindowMinSize = theme.WindowMinSize;
            style.WindowPadding              = theme.WindowPadding;
            style.Alpha                      = theme.Alpha;
            style.AntiAliasedFill            = theme.AntiAliasedFill;
            style.CurveTessellationTolerance = theme.CurveTessellationTolerance;


            foreach (var color in theme.Colors)
            {
                try
                {
                    if (color.Key == ColorTarget.Count)//This shit made a crash
                    {
                        continue;
                    }
                    style.SetColor(color.Key, color.Value);
                }
                catch (Exception ex) { BasePlugin.LogError(ex.Message, 5); }
            }
        }
Beispiel #8
0
        private static void SaveTheme(ThemeConfig theme, string fileName)
        {
            try
            {
                var fullPath        = Path.Combine(ThemesFolder, fileName + ThemeExtension);
                var settingsDirName = Path.GetDirectoryName(fullPath);
                if (!Directory.Exists(settingsDirName))
                {
                    Directory.CreateDirectory(settingsDirName);
                }

                using (var stream = new StreamWriter(File.Create(fullPath)))
                {
                    string json = JsonConvert.SerializeObject(theme, Formatting.Indented, SettingsHub.jsonSettings);
                    stream.Write(json);
                }
            }
            catch (Exception ex)
            {
                BasePlugin.LogError($"Error while loading theme: {ex.Message}", 3);
            }
        }
Beispiel #9
0
        private static ThemeConfig LoadTheme(string fileName, bool nullIfNotFound)
        {
            ThemeConfig result;

            try
            {
                var fullPath = Path.Combine(ThemesFolder, fileName + ThemeExtension);
                if (File.Exists(fullPath))
                {
                    string json = File.ReadAllText(fullPath);
                    return(JsonConvert.DeserializeObject <ThemeConfig>(json, SettingsHub.jsonSettings));
                }
            }
            catch (Exception ex)
            {
                BasePlugin.LogError($"Error while loading theme {fileName}: {ex.Message}, Generating default one", 3);
            }
            if (nullIfNotFound)
            {
                return(null);
            }
            return(GenerateDefaultTheme());
        }
Beispiel #10
0
        private void DllChanged(object sender, FileSystemEventArgs e)
        {
            if (!MainMenuWindow.Settings.AutoReloadDllOnChanges.Value)
            {
                return;
            }
            if (e.FullPath != _dllPath)
            {
                return;                         //Watchin only dll file
            }
            //Events being raised multiple times https://stackoverflow.com/questions/1764809/filesystemwatcher-changed-event-is-raised-twice
            var lastWriteTime = File.GetLastWriteTime(e.FullPath);

            if (Math.Abs((lastWriteTime - _lastWrite).TotalSeconds) < 1)
            {
                return;
            }

            _lastWrite = lastWriteTime;

            if (!File.Exists(_dllPath))
            {
                State = PluginState.Reload_DllNotFound;
                return;
            }

            try
            {
                ReloadPlugin(true);
                BasePlugin.LogMessage($"Reloaded dll: {Path.GetFileName(_dllPath)}", 3);
            }
            catch (Exception ex)
            {
                BasePlugin.LogError($"Cannot reload dll: {Path.GetFileName(_dllPath)}, Error: {ex.Message}", 3);
            }
        }
Beispiel #11
0
        public bool SwitchToTab(int tabIndex)
        {
            var latency = (int)GameController.Game.IngameState.CurLatency;
            // We don't want to Switch to a tab that we are already on
            var openLeftPanel = GameController.Game.IngameState.IngameUi.OpenLeftPanel;

            try
            {
                var stashTabToGoTo =
                    GameController.Game.IngameState.ServerData.StashPanel.GetStashInventoryByIndex(tabIndex)
                    .InventoryUiElement;

                if (stashTabToGoTo.IsVisible)
                {
                    return(true);
                }
            }
            catch
            {
                // Nothing to see here officer.
            }

            // We want to maximum wait 20 times the Current Latency before giving up in our while loops.
            var maxNumberOfTries  = latency * 20 > 2000 ? latency * 20 / WHILE_DELAY : 2000 / WHILE_DELAY;
            var clickWindowOffset = GameController.Window.GetWindowRectangle().TopLeft;

            if (tabIndex > 30)
            {
                return(SwitchToTabViaArrowKeys(tabIndex));
            }

            var stashPanel = GameController.Game.IngameState.ServerData.StashPanel;

            try
            {
                // Obs, this method only works with 31 stashtabs on 1920x1080, since you have to scroll at 32 tabs, and the frame stays in place.
                var viewAllTabsButton = GameController.Game.IngameState.ServerData.StashPanel.ViewAllStashButton;

                if (stashPanel.IsVisible && !viewAllTabsButton.IsVisible)
                {
                    // The user doesn't have a view all tabs button, eg. 4 tabs.
                    return(SwitchToTabViaArrowKeys(tabIndex));
                }

                var parent = openLeftPanel.Children[2].Children[0].Children[1].Children[3];
                var dropDownTabElements = parent.Children[2];

                var totalStashes = GameController.Game.IngameState.ServerData.StashPanel.TotalStashes;
                if (totalStashes > 30)
                {
                    dropDownTabElements = parent.Children[1];
                }

                if (!dropDownTabElements.IsVisible)
                {
                    var pos = viewAllTabsButton.GetClientRect();

                    Mouse.SetCursorPosAndLeftClick(pos.Center + clickWindowOffset);

                    var brCounter = 0;

                    while (!dropDownTabElements.IsVisible)
                    {
                        Thread.Sleep(WHILE_DELAY);

                        if (brCounter++ <= maxNumberOfTries)
                        {
                            continue;
                        }
                        BasePlugin.LogMessage($"1. Error in SwitchToTab: {tabIndex}.", 5);
                        return(false);
                    }

                    if (totalStashes > 30)
                    {
                        // TODO:Zafaar implemented something that allows us to get in contact with the ScrollBar.
                        Mouse.VerticalScroll(true, 5);
                        Thread.Sleep(latency + 50);
                    }
                }

                var tabPos = dropDownTabElements.Children[tabIndex].GetClientRect();

                Mouse.SetCursorPosAndLeftClick(tabPos.Center + clickWindowOffset);
                Thread.Sleep(latency);
            }
            catch (Exception e)
            {
                BasePlugin.LogError($"Error in GoToTab {tabIndex}: {e.Message}", 5);
                return(false);
            }

            Inventory stash;

            var counter = 0;

            do
            {
                Thread.Sleep(WHILE_DELAY);
                stash = stashPanel.VisibleStash;

                if (counter++ <= maxNumberOfTries)
                {
                    continue;
                }
                BasePlugin.LogMessage("2. Error opening stash: " + tabIndex, 5);
                return(false);
            } while (stash?.VisibleInventoryItems == null);
            return(true);
        }
Beispiel #12
0
        internal void InitializeSettingsMenu(bool ignoreAttribute = false)//ignoreAttribute - for Core plugins
        {
            SettingPropertyDrawers.Clear();
            StashTabNodesToUnload.ForEach(x => StashTabController.UnregisterStashNode(x));
            StashTabNodesToUnload.Clear();

            var settingsProps = Settings.GetType().GetProperties();

            foreach (var property in settingsProps)
            {
                if (property.Name == "Enable")
                {
                    continue;
                }

                if (property.GetCustomAttribute <IgnoreMenuAttribute>() != null)
                {
                    continue;
                }

                var menuAttrib = property.GetCustomAttribute <MenuAttribute>();
                if (ignoreAttribute && menuAttrib == null)
                {
                    menuAttrib = new MenuAttribute(System.Text.RegularExpressions.Regex.Replace(property.Name, "(\\B[A-Z])", " $1"));//fix camel case
                }
                if (menuAttrib != null)
                {
                    BaseSettingsDrawer drawer = null;
                    int drawerId = menuAttrib.index == -1 ? GetUniqDrawerId() : menuAttrib.index;
                    if (DrawersIds.Contains(drawerId))
                    {
                        BasePlugin.LogError($"{PluginName}: Already contain settings child with id {menuAttrib.parentIndex}. Fixed by giving a new uniq ID. Property " + property.Name, 5);
                        // drawer.SettingId = GetUniqDrawerId();
                    }
                    var propType = property.PropertyType;

                    if (propType == typeof(ButtonNode) || propType.IsSubclassOf(typeof(ButtonNode)))
                    {
                        drawer = new ButtonSettingDrawer(property.GetValue(Settings) as ButtonNode, menuAttrib.MenuName, drawerId);
                    }
                    else if (propType == typeof(TextNode) || propType.IsSubclassOf(typeof(TextNode)))
                    {
                        drawer = new TextSettingsDrawer(property.GetValue(Settings) as TextNode, menuAttrib.MenuName, drawerId);
                    }
                    else if (propType == typeof(EmptyNode) || propType.IsSubclassOf(typeof(EmptyNode)))
                    {
                        drawer = new LabelSettingDrawer(menuAttrib.MenuName, drawerId);
                    }
                    else if (propType == typeof(HotkeyNode) || propType.IsSubclassOf(typeof(HotkeyNode)))
                    {
                        drawer = new HotkeySettingDrawer(property.GetValue(Settings) as HotkeyNode, menuAttrib.MenuName, drawerId);
                    }
                    else if (propType == typeof(ToggleNode) || propType.IsSubclassOf(typeof(ToggleNode)))
                    {
                        drawer = new CheckboxSettingDrawer(property.GetValue(Settings) as ToggleNode, menuAttrib.MenuName, drawerId);
                    }
                    else if (propType == typeof(ColorNode) || propType.IsSubclassOf(typeof(ColorNode)))
                    {
                        drawer = new ColorSettingDrawer(property.GetValue(Settings) as ColorNode, menuAttrib.MenuName, drawerId);
                    }
                    else if (propType == typeof(ListNode) || propType.IsSubclassOf(typeof(ListNode)))
                    {
                        drawer = new ComboBoxSettingDrawer(property.GetValue(Settings) as ListNode, menuAttrib.MenuName, drawerId);
                    }
                    else if (propType == typeof(FileNode) || propType.IsSubclassOf(typeof(FileNode)))
                    {
                        drawer = new FilePickerDrawer(property.GetValue(Settings) as FileNode, menuAttrib.MenuName, drawerId);
                    }
                    else if (propType == typeof(StashTabNode) || propType.IsSubclassOf(typeof(StashTabNode)))
                    {
                        var stashNode = property.GetValue(Settings) as StashTabNode;
                        StashTabNodesToUnload.Add(stashNode);
                        StashTabController.RegisterStashNode(stashNode);
                        drawer = new StashTabNodeSettingDrawer(stashNode, menuAttrib.MenuName, drawerId);
                    }
                    else if (propType.IsGenericType)
                    {
                        var genericType = propType.GetGenericTypeDefinition();

                        if (genericType == typeof(RangeNode <>))
                        {
                            var genericParameter = propType.GenericTypeArguments;

                            if (genericParameter.Length > 0)
                            {
                                var argType     = genericParameter[0];
                                var valueDrawer = new CustomSettingsDrawer(menuAttrib.MenuName, drawerId);

                                if (argType == typeof(int))
                                {
                                    var rangeInt = property.GetValue(Settings) as RangeNode <int>;
                                    valueDrawer.DrawDelegate = delegate
                                    {
                                        rangeInt.Value = ImGuiExtension.IntSlider(valueDrawer.ImguiUniqLabel, rangeInt.Value, rangeInt.Min, rangeInt.Max);
                                    };
                                }
                                else if (argType == typeof(float))
                                {
                                    var rangeInt = property.GetValue(Settings) as RangeNode <float>;
                                    valueDrawer.DrawDelegate = delegate
                                    {
                                        rangeInt.Value = ImGuiExtension.FloatSlider(valueDrawer.ImguiUniqLabel, rangeInt.Value, rangeInt.Min, rangeInt.Max);
                                    };
                                }
                                else if (argType == typeof(double))
                                {
                                    var rangeInt = property.GetValue(Settings) as RangeNode <double>;
                                    valueDrawer.DrawDelegate = delegate
                                    {
                                        rangeInt.Value = ImGuiExtension.FloatSlider(valueDrawer.ImguiUniqLabel, (float)rangeInt.Value, (float)rangeInt.Min, (float)rangeInt.Max);
                                    };
                                }
                                else if (argType == typeof(byte))
                                {
                                    var rangeInt = property.GetValue(Settings) as RangeNode <byte>;
                                    valueDrawer.DrawDelegate = delegate
                                    {
                                        rangeInt.Value = (byte)ImGuiExtension.IntSlider(valueDrawer.ImguiUniqLabel, rangeInt.Value, rangeInt.Min, rangeInt.Max);
                                    };
                                }
                                else if (argType == typeof(long))
                                {
                                    var rangeInt = property.GetValue(Settings) as RangeNode <long>;
                                    valueDrawer.DrawDelegate = delegate
                                    {
                                        rangeInt.Value = ImGuiExtension.IntSlider(valueDrawer.ImguiUniqLabel, (int)rangeInt.Value, (int)rangeInt.Min, (int)rangeInt.Max);
                                    };
                                }
                                else if (argType == typeof(short))
                                {
                                    var rangeInt = property.GetValue(Settings) as RangeNode <short>;
                                    valueDrawer.DrawDelegate = delegate
                                    {
                                        rangeInt.Value = (short)ImGuiExtension.IntSlider(valueDrawer.ImguiUniqLabel, rangeInt.Value, rangeInt.Min, rangeInt.Max);
                                    };
                                }
                                else if (argType == typeof(ushort))
                                {
                                    var rangeInt = property.GetValue(Settings) as RangeNode <ushort>;
                                    valueDrawer.DrawDelegate = delegate
                                    {
                                        rangeInt.Value = (ushort)ImGuiExtension.IntSlider(valueDrawer.ImguiUniqLabel, rangeInt.Value, rangeInt.Min, rangeInt.Max);
                                    };
                                }
                                else if (argType == typeof(Vector2))
                                {
                                    var vect = property.GetValue(Settings) as RangeNode <Vector2>;
                                    valueDrawer.DrawDelegate = delegate
                                    {
                                        var val = vect.Value;
                                        ImGui.SliderVector2(valueDrawer.ImguiUniqLabel, ref val, vect.Min.X, vect.Max.X, "%.0f", 1);
                                        vect.Value = val;
                                    };
                                }
                                else
                                {
                                    BasePlugin.LogError($"{PluginName}: Generic node argument for range node '{argType.Name}' is not defined in code. Range node type: " + propType.Name, 5);
                                }

                                drawer = valueDrawer;
                            }
                            else
                            {
                                BasePlugin.LogError($"{PluginName}: Can't get GenericTypeArguments from option type: " + propType.Name, 5);
                            }
                        }
                        else
                        {
                            BasePlugin.LogError($"{PluginName}: Generic option node is not defined in code: " + genericType.Name, 5);
                        }
                    }
                    else
                    {
                        BasePlugin.LogError($"{PluginName}: Type of option node is not defined: " + propType.Name, 5);
                    }

                    if (drawer != null)
                    {
                        drawer.SettingTooltip = menuAttrib.Tooltip;

                        if (menuAttrib.parentIndex != -1)
                        {
                            var parent = GetAllDrawers().Find(x => x.SettingId == menuAttrib.parentIndex);
                            if (parent != null)
                            {
                                parent.Children.Add(drawer);
                                continue;
                            }
                            BasePlugin.LogError($"{PluginName}: Can't find child with id {menuAttrib.parentIndex} to parent node. Property " + property.Name, 5);
                        }
                        SettingPropertyDrawers.Add(drawer);
                    }
                    else
                    {
                        BasePlugin.LogError($"{PluginName}: Type of option node is not defined: " + propType.Name, 5);
                    }
                }
            }
        }
Beispiel #13
0
        public bool NewEntry()
        {
            try
            {
                var entry = new Entry
                {
                    Id   = DataToString(true),
                    Info = new Info
                    {
                        Date  = DateTime.Now,
                        Level = new Level
                        {
                            CurrentLevel            = LocalPlayer.Level,
                            CurrentLevelPercent     = Main.Instance.Progress(),
                            ExperiencedGained       = Main.Instance.ExperienceGained(),
                            ExperienceGainedPercent = Main.Instance.LevelPercentGained(),
                            LevelUps = (int)(LocalPlayer.Level - Main.Instance.JoinLevel)
                        },
                        Area = new Area
                        {
                            Name            = Main.Instance.JoinArea.DisplayName,
                            LevelDifference = LocalPlayer.Level - Main.Instance.JoinArea.Area.MonsterLevel > 0
                                ? string.Format("+{0}", LocalPlayer.Level - Main.Instance.JoinArea.Area.MonsterLevel)
                                : (LocalPlayer.Level - Main.Instance.JoinArea.Area.MonsterLevel).ToString(),
                            TimeSpent   = Main.Instance.RunTime(),
                            SameAreaEta = new SameAreaEta
                            {
                                Left          = Main.Instance.RunsToNextLevel(),
                                TotalForLevel = Main.Instance.TotalRunsToNextLevel()
                            }
                        }
                    }
                };

                var playerName = LocalPlayer.Name;

                // shit fix for null player name
                if (string.IsNullOrEmpty(playerName))
                {
                    while (string.IsNullOrEmpty(GameController.Instance.Game.IngameState.Data.LocalPlayer.GetComponent <Player>().PlayerName))
                    {
                        Thread.Sleep(5);
                        BasePlugin.LogError("CharacterData: Null or Empty Name", 10);
                    }
                    playerName = GameController.Instance.Game.IngameState.Data.LocalPlayer.GetComponent <Player>().PlayerName;
                }

                var path1 = string.Format("{0}\\Level Entry\\{1}\\", PluginDirectory, playerName);

                var path2         = string.Format("{0}JsonLog.json", path1);
                var directoryName = Path.GetDirectoryName(path1);
                var levelLogs     = new LevelLogs
                {
                    Entries = new List <Entry>()
                };
                if (!Directory.Exists(directoryName) && directoryName != null)
                {
                    Directory.CreateDirectory(directoryName);
                }
                try
                {
                    var str = File.ReadAllText(path2);
                    if (string.IsNullOrEmpty(str.Trim()))
                    {
                        throw new Exception();
                    }
                    if (str == "null")
                    {
                        throw new Exception();
                    }
                    levelLogs = JsonConvert.DeserializeObject <LevelLogs>(str);
                }
                catch
                {
                }

                levelLogs.Entries.Add(entry);
                var str1 = JsonConvert.SerializeObject(levelLogs, (Formatting)1);
                using (var streamWriter = new StreamWriter(File.Create(path2)))
                {
                    streamWriter.Write(str1);
                }
            }
            catch (Exception ex)
            {
                //BasePlugin.LogError("Plugin error save json!\n" + ex, 3f);
            }

            return(true);
        }
        public static void Parse(PluginToUpdate plugVariant)
        {
            try
            {
                var gitConfigFilePath = Path.Combine(plugVariant.PluginDirectory, ConfigFileName);

                if (File.Exists(gitConfigFilePath))
                {
                    plugVariant.bHasGitConfig = true;
                    var configLines = File.ReadAllLines(gitConfigFilePath);



                    var handleIgnore = false;
                    for (var i = 0; i < configLines.Length; i++)
                    {
                        var line = configLines[i];
                        if (line.StartsWith("#"))
                        {
                            continue;
                        }

                        var spacelessLine = line.Replace(" ", "");
                        if (spacelessLine.Replace("\r", "").Replace("\n", "").Length == 0)
                        {
                            continue;
                        }

                        if (handleIgnore)
                        {
                            plugVariant.IgnoredEntities.Add(line);
                            continue;
                        }
                        if (spacelessLine == OPTION_FILESIGNORE)
                        {
                            handleIgnore = true;
                            continue;
                        }

                        //Repository owner
                        var ownerIndex = line.IndexOf(OPTION_OWNER);
                        if (ownerIndex != -1)
                        {
                            plugVariant.RepoOwner = line.Substring(ownerIndex + OPTION_OWNER.Length);
                            TrimName(ref plugVariant.RepoOwner);
                            continue;
                        }

                        //Repository name
                        var reposNameIndex = line.IndexOf(OPTION_REPONAME);
                        if (reposNameIndex != -1)
                        {
                            plugVariant.RepoName = line.Substring(reposNameIndex + OPTION_REPONAME.Length);
                            TrimName(ref plugVariant.RepoName);
                            continue;
                        }

                        //Only from release
                        if (spacelessLine == OPTION_RELEASE)
                        {
                            if (plugVariant.UpdateVariant != ePluginSourceOfUpdate.Undefined)
                            {
                                BasePlugin.LogMessage(
                                    "PluginUpdater: " + plugVariant.PluginName +
                                    ",  both update variants (Release and Commit) is not allowed. Check GitUpdateConfig. Current update variant is: " +
                                    plugVariant.UpdateVariant, 10);
                            }
                            else
                            {
                                plugVariant.UpdateVariant = ePluginSourceOfUpdate.Release;
                            }
                            continue;
                        }

                        //Only from repository
                        if (spacelessLine == OPTION_REPOONLY)
                        {
                            if (plugVariant.UpdateVariant != ePluginSourceOfUpdate.Undefined)
                            {
                                BasePlugin.LogMessage(
                                    "PluginUpdater: " + plugVariant.PluginName +
                                    ",  both update variants (Release and Commit) is not allowed. Check GitUpdateConfig. Current update variant is: " +
                                    plugVariant.UpdateVariant, 10);
                            }
                            else
                            {
                                plugVariant.UpdateVariant = ePluginSourceOfUpdate.RepoBranch;
                            }
                            continue;
                        }

                        //Release tag regex filter
                        var tagIndex = line.IndexOf(OPTION_RELEASETAGREGEXFILTER);
                        if (tagIndex != -1)
                        {
                            plugVariant.ReleaseRegexTag = line.Substring(tagIndex + OPTION_RELEASETAGREGEXFILTER.Length);
                            TrimName(ref plugVariant.ReleaseRegexTag);
                            plugVariant.bCustomTag = true;
                        }

                        var branchNameIndex = line.IndexOf(OPTION_REPOBRANCH);
                        if (branchNameIndex != -1)
                        {
                            plugVariant.BranchName = line.Substring(branchNameIndex + OPTION_REPOBRANCH.Length);
                            TrimName(ref plugVariant.BranchName);
                        }
                    }

                    plugVariant.bAllowCheckUpdate = true;

                    if (string.IsNullOrEmpty(plugVariant.RepoOwner))
                    {
                        BasePlugin.LogError("PluginUpdater: Repository Owner is not defined in plugin: " + plugVariant.PluginName, 10);
                        plugVariant.UpdateState       = ePluginUpdateState.WrongConfig;
                        plugVariant.bAllowCheckUpdate = false;
                    }
                    if (string.IsNullOrEmpty(plugVariant.RepoName))
                    {
                        BasePlugin.LogError("PluginUpdater: Repository Name is not defined in plugin: " + plugVariant.PluginName, 10);
                        plugVariant.UpdateState       = ePluginUpdateState.WrongConfig;
                        plugVariant.bAllowCheckUpdate = false;
                    }
                    if (plugVariant.UpdateVariant == ePluginSourceOfUpdate.Undefined)
                    {
                        BasePlugin.LogError("PluginUpdater: Update type (Release or Repository) is not defined in plugin: " + plugVariant.PluginName, 10);
                        plugVariant.UpdateState       = ePluginUpdateState.WrongConfig;
                        plugVariant.bAllowCheckUpdate = false;
                    }
                }
            }
            catch
            {
                BasePlugin.LogError("PluginUpdater: Error while parsing git update config for plugin: " + plugVariant.PluginName, 10);
            }
        }
Beispiel #15
0
        private static bool MoveDirectoryFiles(string origDirectory, string sourceDirectory, string targetDirectory)
        {
            bool noErrors            = true;
            var  sourceDirectoryInfo = new DirectoryInfo(sourceDirectory);

            foreach (var file in sourceDirectoryInfo.GetFiles())
            {
                var  destFile  = Path.Combine(targetDirectory, file.Name);
                bool fileExist = File.Exists(destFile);

                try
                {
                    var fileLocalPath = destFile.Replace(origDirectory, "");

                    if (fileExist)
                    {
                        var backupPath    = origDirectory + @"\" + UpdateBackupDir + fileLocalPath;//Do not use Path.Combine due to Path.IsPathRooted checks
                        var backupDirPath = Path.GetDirectoryName(backupPath);

                        if (!Directory.Exists(backupDirPath))
                        {
                            Directory.CreateDirectory(backupDirPath);
                        }

                        File.Copy(destFile, backupPath, true);
                    }

                    File.Copy(file.FullName, destFile, true);
                    File.Delete(file.FullName);//Delete from temp update dir

                    if (fileExist)
                    {
                        PluginUpdateLog.Add("File Replaced:\t\t" + destFile + " vs " + file.FullName);
                    }
                    else
                    {
                        PluginUpdateLog.Add("File Added:\t\t\t" + destFile);
                    }
                }
                catch (Exception ex)
                {
                    noErrors = false;
                    if (fileExist)
                    {
                        BasePlugin.LogError("PoeHUD PluginUpdater: can't replace file: " + destFile + ", Error: " + ex.Message, 10);
                        PluginUpdateLog.Add("Error replacing file: \t" + destFile);
                    }
                    else
                    {
                        BasePlugin.LogError("PoeHUD PluginUpdater: can't move file: " + destFile + ", Error: " + ex.Message, 10);
                        PluginUpdateLog.Add("Error moving file: \t" + destFile);
                    }
                }
            }

            foreach (var directory in sourceDirectoryInfo.GetDirectories())
            {
                var destDir = Path.Combine(targetDirectory, directory.Name);

                if (Directory.Exists(destDir))
                {
                    PluginUpdateLog.Add("Merging directory: \t" + destDir);
                    var curDirProcessNoErrors = MoveDirectoryFiles(origDirectory, directory.FullName, destDir);

                    if (curDirProcessNoErrors)
                    {
                        Directory.Delete(directory.FullName, true);
                    }

                    noErrors = curDirProcessNoErrors || noErrors;
                }
                else
                {
                    Directory.Move(directory.FullName, destDir);
                    PluginUpdateLog.Add("Moving directory: \t" + destDir);
                }
            }
            return(noErrors);
        }
        public bool SwitchToTab(int tabIndex, FullRareSetManagerSettings Settings)
        {
            var latency = (int)GameController.Game.IngameState.CurLatency;
            // We don't want to Switch to a tab that we are already on
            var openLeftPanel = GameController.Game.IngameState.IngameUi.OpenLeftPanel;

            try
            {
                var stashTabToGoTo =
                    GameController.Game.IngameState.ServerData.StashPanel.GetStashInventoryByIndex(tabIndex)
                    .InventoryUiElement;

                if (stashTabToGoTo.IsVisible)
                {
                    return(true);
                }
            }
            catch
            {
                // Nothing to see here officer.
            }

            var _clickWindowOffset = GameController.Window.GetWindowRectangle().TopLeft;
            // We want to maximum wait 20 times the Current Latency before giving up in our while loops.
            var maxNumberOfTries = latency * 20 > 2000 ? latency * 20 / WHILE_DELAY : 2000 / WHILE_DELAY;

            if (tabIndex > 30)
            {
                return(SwitchToTabViaArrowKeys(tabIndex));
            }

            var stashPanel = GameController.Game.IngameState.ServerData.StashPanel;

            try
            {
                var viewAllTabsButton = GameController.Game.IngameState.ServerData.StashPanel.ViewAllStashButton;

                if (stashPanel.IsVisible && !viewAllTabsButton.IsVisible)
                {
                    // The user doesn't have a view all tabs button, eg. 4 tabs.
                    return(SwitchToTabViaArrowKeys(tabIndex));
                }

                var dropDownTabElements = GameController.Game.IngameState.ServerData.StashPanel.ViewAllStashPanel;

                if (!dropDownTabElements.IsVisible)
                {
                    var pos = viewAllTabsButton.GetClientRect();
                    Mouse.SetCursorPosAndLeftClick(pos.Center + _clickWindowOffset, Settings.ExtraDelay);
                    //Thread.Sleep(200);
                    Thread.Sleep(latency + Settings.ExtraDelay);
                    var brCounter = 0;

                    while (1 == 2 && !dropDownTabElements.IsVisible)
                    {
                        Thread.Sleep(WHILE_DELAY);

                        if (brCounter++ <= maxNumberOfTries)
                        {
                            continue;
                        }
                        BasePlugin.LogMessage($"1. Error in SwitchToTab: {tabIndex}.", 5);
                        return(false);
                    }

                    if (GameController.Game.IngameState.ServerData.StashPanel.TotalStashes > 30)
                    {
                        // TODO:Zafaar implemented something that allows us to get in contact with the ScrollBar.
                        Mouse.VerticalScroll(true, 5);
                        Thread.Sleep(latency + Settings.ExtraDelay);
                    }
                }


                // Dropdown menu have the following children: 0, 1, 2.
                // Where:
                // 0 is the icon (fx. chaos orb).
                // 1 is the name of the tab.
                // 2 is the slider.
                var        totalStashes = GameController.Game.IngameState.ServerData.StashPanel.TotalStashes;
                var        slider       = dropDownTabElements.Children[1].ChildCount == totalStashes;
                var        noSlider     = dropDownTabElements.Children[2].ChildCount == totalStashes;
                RectangleF tabPos;
                if (slider)
                {
                    tabPos = dropDownTabElements.GetChildAtIndex(1).GetChildAtIndex(tabIndex).GetClientRect();
                }
                else if (noSlider)
                {
                    tabPos = dropDownTabElements.GetChildAtIndex(2).GetChildAtIndex(tabIndex).GetClientRect();
                }
                else
                {
                    BasePlugin.LogError("Couldn't detect slider/non-slider, contact Preaches [Stashie]", 3);
                    return(false);
                }

                Mouse.SetCursorPosAndLeftClick(tabPos.Center + _clickWindowOffset, Settings.ExtraDelay);
                Thread.Sleep(latency + Settings.ExtraDelay);
            }
            catch (Exception e)
            {
                BasePlugin.LogError($"Error in GoToTab {tabIndex}: {e.Message}", 5);
                return(false);
            }

            Inventory stash;

            var counter = 0;

            do
            {
                Thread.Sleep(WHILE_DELAY);
                stash = stashPanel.VisibleStash;

                if (counter++ <= maxNumberOfTries)
                {
                    continue;
                }
                BasePlugin.LogMessage("2. Error opening stash: " + tabIndex, 5);
                return(true);
            } while (stash?.VisibleInventoryItems == null);
            return(true);
        }
Beispiel #17
0
        public async void UpdatePlugin()
        {
            if (FilesToDownload.Count == 0)
            {
                BasePlugin.LogMessage(
                    "Plugin don't have download information (changed files or release zip is not found)", 10);
                return;
            }

            var updateDirectory = Path.Combine(PluginDirectory, PoeHUD_PluginsUpdater.UpdateTempDir);

            if (Directory.Exists(updateDirectory))
            {
                Directory.Delete(updateDirectory, true);
            }

            Directory.CreateDirectory(updateDirectory);

            if (UpdateVariant == ePluginSourceOfUpdate.Release)
            {
                #region Release

                InstallProgress = "Preparing to download...";

                try
                {
                    using (var webClient = new WebClient())
                    {
                        webClient.DownloadProgressChanged +=
                            (s, e) => { InstallProgress = "Downloading: " + e.ProgressPercentage + "%"; };

                        var downloadFile = FilesToDownload[0];

                        var filename = downloadFile.Path;
                        await webClient.DownloadFileTaskAsync(downloadFile.Url, downloadFile.Path);

                        InstallProgress = "Extracting zip...";
                        ZipFile.ExtractToDirectory(filename, updateDirectory);
                        InstallProgress = "Extracting: Ok";

                        File.Delete(filename);


                        var dirInfo      = new DirectoryInfo(updateDirectory);
                        var dirInfoDirs  = dirInfo.GetDirectories();
                        var dirInfoFiles = dirInfo.GetFiles();

                        if (dirInfoDirs.Length == 1 && dirInfoFiles.Length == 0)
                        {
                            InstallProgress = "Fixing files hierarchy..";
                            var subDir = dirInfoDirs[0];

                            foreach (var file in subDir.GetFiles())
                            {
                                var destFile = Path.Combine(updateDirectory, file.Name);
                                File.Move(file.FullName, destFile);
                            }
                            foreach (var directory in subDir.GetDirectories())
                            {
                                var destDir = Path.Combine(updateDirectory, directory.Name);
                                Directory.Move(directory.FullName, destDir);
                            }
                            Directory.Delete(subDir.FullName);
                        }


                        foreach (var ignoreFile in IgnoredEntities)
                        {
                            var ignorePath = Path.Combine(updateDirectory, ignoreFile);

                            if (File.Exists(ignorePath))
                            {
                                File.Delete(ignorePath);
                                BasePlugin.LogMessage("Ignore File: " + ignorePath, 5);
                            }
                            else if (Directory.Exists(ignorePath))
                            {
                                Directory.Delete(ignorePath, true);
                                BasePlugin.LogMessage("Ignore Directory: " + ignorePath, 5);
                            }
                        }

                        InstallProgress = "";

                        var versionFilePath = Path.Combine(updateDirectory, PoeHUD_PluginsUpdater.VersionFileName);
                        File.WriteAllText(versionFilePath, RemoteVersion + Environment.NewLine + RemoteTag);

                        UpdateState = ePluginUpdateState.ReadyToInstal;
                    }
                }
                catch (Exception ex)
                {
                    InstallProgress = "Error updating";
                    BasePlugin.LogError(
                        "Plugins Updater: Error while updating plugin: " + PluginName + ", Error: " + ex.Message, 10);
                }
                DoAfterUpdate(this);
                #endregion
            }
            else if (UpdateVariant == ePluginSourceOfUpdate.RepoBranch)
            {
                InstallProgress = "Preparing to download...";

                try
                {
                    var downloadCount   = FilesToDownload.Count;
                    var downloadedCount = 0;

                    using (var webClient = new WebClient())
                    {
                        webClient.DownloadProgressChanged +=
                            (s, e) =>
                        {
                            InstallProgress = "Downloading: " + downloadedCount + "/" + downloadCount + " (" +
                                              e.ProgressPercentage + "%)";
                        };

                        foreach (var downloadFile in FilesToDownload)
                        {
                            var downloadDir = Path.GetDirectoryName(downloadFile.Path);
                            if (!Directory.Exists(downloadDir))
                            {
                                Directory.CreateDirectory(downloadDir);
                            }

                            await webClient.DownloadFileTaskAsync(downloadFile.Url, downloadFile.Path);

                            InstallProgress = "Downloading: " + downloadedCount + "/" + downloadCount;
                            downloadedCount++;
                        }

                        InstallProgress = "";

                        UpdateState = ePluginUpdateState.ReadyToInstal;
                    }
                }
                catch (Exception ex)
                {
                    InstallProgress = "Error updating";
                    BasePlugin.LogError(
                        "Plugins Updater: Error while updating plugin: " + PluginName + ", Error: " + ex.Message, 10);
                }
                DoAfterUpdate(this);
            }
            else
            {
                BasePlugin.LogMessage("Update type is not supported in code: " + UpdateVariant, 5);
            }
        }
 public void LogError(object message, float displayTime)
 {
     BasePlugin.LogError(message, displayTime);
 }
Beispiel #19
0
        private void GolemMain()
        {
            if (isTown)
            {
                return;
            }

            if (GameController == null || GameController.Window == null || GameController.Game.IngameState.Data.LocalPlayer == null || GameController.Game.IngameState.Data.LocalPlayer.Address == 0x00)
            {
                return;
            }

            if (!GameController.Window.IsForeground())
            {
                return;
            }

            if (!GameController.Game.IngameState.Data.LocalPlayer.IsValid)
            {
                return;
            }

            var playerLife = GameController.Game.IngameState.Data.LocalPlayer.GetComponent <Life>();

            if (playerLife == null)
            {
                return;
            }

            try
            {
                List <int> golems = GameController.Game.IngameState.Data.LocalPlayer.GetComponent <Actor>().Minions;

                // Don't cast if number of golems is superior or equal to the targetNumber
                if (golems.Count >= targetNumber)
                {
                    return;
                }

                if (Settings.DontCastOnNearbyMonster.Value)
                {
                    Vector3 positionPlayer = GameController.Game.IngameState.Data.LocalPlayer.GetComponent <Render>().Pos;

                    foreach (EntityWrapper monster in nearbyMonsters)
                    {
                        if (monster.IsValid && monster.IsAlive)
                        {
                            Render positionMonster = monster.GetComponent <Render>();
                            int    distance        = (int)Math.Sqrt(Math.Pow((double)(positionPlayer.X - positionMonster.X), 2.0) + Math.Pow((double)(positionPlayer.Y - positionMonster.Y), 2.0));
                            if (distance <= Settings.NearbyMonsterRange.Value)
                            {
                                return;  //don't cast if monsters are nearby
                            }
                        }
                    }
                }

                IngameUIElements ingameUiElements = GameController.Game.IngameState.IngameUi;
                int countChaosGolem     = 0;
                int countFireGolem      = 0;
                int countIceGolem       = 0;
                int countLightningGolem = 0;
                int countStoneGolem     = 0;

                foreach (var golemId in golems)
                {
                    if (GameController.Game.IngameState.Data.EntityList.EntitiesAsDictionary.ContainsKey(golemId))
                    {
                        var golemPathString = GameController.Game.IngameState.Data.EntityList.EntitiesAsDictionary[golemId].Path;

                        if (golemPathString.Contains("ChaosElemental"))
                        {
                            countChaosGolem++;
                        }
                        if (golemPathString.Contains("FireElemental"))
                        {
                            countFireGolem++;
                        }
                        if (golemPathString.Contains("IceElemental"))
                        {
                            countIceGolem++;
                        }
                        if (golemPathString.Contains("LightningGolem"))
                        {
                            countLightningGolem++;
                        }
                        if (golemPathString.Contains("RockGolem"))
                        {
                            countStoneGolem++;
                        }
                    }
                }

                if (Settings.ChaosGolem.Value && countChaosGolem < Settings.ChaosGolemMax.Value && ingameUiElements.SkillBar[Settings.ChaosGolemConnectedSkill.Value - 1].SkillIconPath.Contains("ChaosElementalSummon"))
                {
                    keyboard.KeyPressRelease(Settings.ChaosGolemKeyPressed.Value);
                }
                if (Settings.FireGolem.Value && countFireGolem < Settings.FireGolemMax.Value && ingameUiElements.SkillBar[Settings.FireGolemConnectedSkill.Value - 1].SkillIconPath.Contains("FireElementalSummon"))
                {
                    keyboard.KeyPressRelease(Settings.FireGolemKeyPressed.Value);
                }
                if (Settings.IceGolem.Value && countIceGolem < Settings.IceGolemMax.Value && ingameUiElements.SkillBar[Settings.IceGolemConnectedSkill.Value - 1].SkillIconPath.Contains("IceElementalSummon"))
                {
                    keyboard.KeyPressRelease(Settings.IceGolemKeyPressed.Value);
                }
                if (Settings.LightningGolem.Value && countLightningGolem < Settings.LightningGolemMax.Value && ingameUiElements.SkillBar[Settings.LightningGolemConnectedSkill.Value - 1].SkillIconPath.Contains("LightningGolem"))
                {
                    keyboard.KeyPressRelease(Settings.LightningGolemKeyPressed.Value);
                }
                if (Settings.StoneGolem.Value && countStoneGolem < Settings.StoneGolemMax.Value && ingameUiElements.SkillBar[Settings.StoneGolemConnectedSkill.Value - 1].SkillIconPath.Contains("RockGolemSummon"))
                {
                    keyboard.KeyPressRelease(Settings.StoneGolemKeyPressed.Value);
                }
            }
            catch (Exception err)
            {
                BasePlugin.LogError(err, 5);
            }
        }