Exemple #1
0
        public void OnPressed()
        {
            Logger.Instance.WriteGlobal("Hotkey pressed: {0}+{1} : {2}", _hotkey.Modifier.ToString().Replace(", ", "+"),
                                        _hotkey.Key, Name);
            // Get active window
            IntPtr hwnd = WinAPI.GetForegroundWindow();

            BotClass test = BotSettings.Instance.Bots.FirstOrDefault(x => x.Diablo.MainWindowHandle == hwnd);

            if (test != null)
            {
                DiabloClass diablo = test.Diablo;
                if (diablo == null)
                {
                    return;
                }

                // Get window rectangle
                WinAPI.RECT rct;
                if (WinAPI.GetWindowRect(new HandleRef(test, hwnd), out rct))
                {
                    // Get screen where window is located
                    var    rect   = new Rectangle(rct.Left, rct.Top, rct.Width, rct.Heigth);
                    Screen screen = Screen.FromRectangle(rect);
                    // Set window fullscreen to current screen
                    WinAPI.SetWindowPos(hwnd, IntPtr.Zero, screen.Bounds.X, screen.Bounds.Y, screen.Bounds.Width,
                                        screen.Bounds.Height,
                                        WinAPI.SetWindowPosFlags.SWP_SHOWWINDOW | WinAPI.SetWindowPosFlags.SWP_NOSENDCHANGING);
                }
            }
        }
Exemple #2
0
        public void OnPressed()
        {
            Logger.Instance.WriteGlobal("Hotkey pressed: {0}+{1} : {2}", _hotkey.Modifier.ToString().Replace(", ", "+"),
                                        _hotkey.Key, Name);

            // Get active window
            IntPtr hwnd = WinAPI.GetForegroundWindow();

            BotClass test = BotSettings.Instance.Bots.FirstOrDefault(x => x.Diablo.MainWindowHandle == hwnd);

            if (test != null)
            {
                DiabloClass diablo = test.Diablo;
                if (diablo == null)
                {
                    return;
                }
                AutoPosition.ManualPositionWindow(hwnd, diablo.X, diablo.Y, diablo.W, diablo.H);
                return;
            }
            test = BotSettings.Instance.Bots.FirstOrDefault(x => x.Demonbuddy.MainWindowHandle == hwnd);
            if (test != null)
            {
                DemonbuddyClass demonbuddy = test.Demonbuddy;
                if (demonbuddy == null)
                {
                    return;
                }
                AutoPosition.ManualPositionWindow(hwnd, demonbuddy.X, demonbuddy.Y, demonbuddy.W, demonbuddy.H);
                return;
            }
            Logger.Instance.WriteGlobal("Reposition Current Failed");
        }
Exemple #3
0
        //
        internal static string SendStartInstruction(BotClass bot, BotClass opponentBot, int pointsToWin, int maxRounds, int dynamiteCount)
        {
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(string.Format("{0}/start", bot.Url));

                var postData = string.Format("opponentName={0}&pointsToWin={1}&maxRounds={2}&dynamiteCount={3}", opponentBot.Name, pointsToWin, maxRounds, dynamiteCount);

                var data = Encoding.ASCII.GetBytes(postData);

                request.Method        = "POST";
                request.Timeout       = 5000;
                request.ContentType   = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;

                using (var stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }

                var response = (HttpWebResponse)request.GetResponse();

                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                return(responseString);
            }
            catch
            {
                return("failed");
            }
        }
Exemple #4
0
        internal static string PostMove(BotClass bot, string move)
        {
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(string.Format("{0}/move", bot.Url));


                var data = Encoding.ASCII.GetBytes(move);

                //request.Timeout = 5000;
                request.Method        = "POST";
                request.ContentType   = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;

                using (var stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }

                var response = (HttpWebResponse)request.GetResponse();

                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                return(responseString);
            }
            catch
            {
                return("failed");
            }
        }
Exemple #5
0
        public void Clone(int index)
        {
            BotClass original  = (BotClass)Bots[index].Clone();
            int      nextIndex = index + 1;

            Bots.Insert(nextIndex, original);
        }
Exemple #6
0
        public static void ManualPositionWindow(IntPtr handle, int x, int y, int w, int h, BotClass bot = null)
        {
            // Set window position and size
            try
            {
                WinAPI.RECT rct;
                if (WinAPI.GetWindowRect(new HandleRef(bot, handle), out rct))
                {
                    if (w <= 0)
                        w = rct.Width;
                    if (h <= 0)
                        h = rct.Heigth;

                    DebugHelper.Write(bot, "ManualPosition window:{0}: X:{1} Y:{2} W:{3} H:{4}", handle, x, y, w, h);
                    if (
                        !WinAPI.SetWindowPos(handle, IntPtr.Zero, x, y, w, h,
                            WinAPI.SetWindowPosFlags.SWP_NOACTIVATE | WinAPI.SetWindowPosFlags.SWP_NOSENDCHANGING))
                        Logger.Instance.Write(bot, "ManualPosition window:{0}: Failed!", handle);
                }
                else
                    Logger.Instance.Write(bot, "ManualPosition Failed to get window rectangle");
            }
            catch (Exception ex)
            {
                DebugHelper.Write(bot, "Failed", "ManualPositionWindow(...)");
                DebugHelper.Exception(ex);
            }
        }
Exemple #7
0
    void botsetup(PlayerFaction faction)
    {
        string _name = Utils.RandomString(8);

        _bot = new BotClass {
            faction = faction, _name = _name
        };
    }
Exemple #8
0
        public void KillSession(BotClass bot)
        {
            lock (_webClientLock)
            {
                var logintime = bot.Demonbuddy.LoginTime;
                _webClient.Headers["Referer"] = "http://buddyauth.com/User/Sessions";
                var data  = new NameValueCollection();
                var match = GetSessions()
                            .Where(i => logintime.Subtract(i.time).TotalSeconds <16 && logintime.Subtract(i.time).TotalSeconds> -16)
                            .OrderBy(i => logintime.Subtract(i.time).TotalSeconds).FirstOrDefault();

                if (match.id == 0)
                {
                    Logger.Instance.Write(bot, "BuddyAuth: No session found.");
                    return;
                }

                data.Set("selectedSessions[" + match.number + "].Id", Convert.ToString(match.id));
                data.Set("selectedSessions[" + match.number + "].IsChecked", "true");

                try
                {
                    int retry = 3;
                    do
                    {
                        try
                        {
                            _webClient.UploadValues("http://buddyauth.com/User/Sessions", data);
                            Logger.Instance.Write(bot, "BuddyAuth: Session with id: {0} killed! (Time difference: {1})", match.id, logintime.Subtract(match.time).TotalSeconds);
                            return;
                        }
                        catch (WebException wex)
                        {
                            var code = ((HttpWebResponse)wex.Response).StatusCode;
                            if (code != HttpStatusCode.InternalServerError &&
                                code != HttpStatusCode.BadGateway &&
                                code != HttpStatusCode.ServiceUnavailable &&
                                code != HttpStatusCode.GatewayTimeout &&
                                code != HttpStatusCode.RequestTimeout)
                            {
                                Logger.Instance.Write(bot, "Failed: {0}", wex.Message);
                                return;
                            }

                            Logger.Instance.Write(bot, "Failed: {0} (next retry in 5 seconds) [{1}]", wex.Message, 3 - retry + 1);
                            Thread.Sleep(5000);
                        }
                    } while (retry-- > 0);
                }
                catch (Exception ex)
                {
                    DebugHelper.Write(bot, "BuddyAuth session killer failed!");
                    DebugHelper.Exception(ex);
                    return;
                }
                Logger.Instance.Write(bot, "BuddyAuth: No session found.");
            }
        }
        public void LoadSchedule(BotClass bot)
        {
            var loadScheduleThread = new Thread(ScheduleLoader)
            {
                Name = "ScheduleLoader"
            };

            loadScheduleThread.Start(bot);
        }
Exemple #10
0
 public static void Write(BotClass bot, string message, params object[] args)
 {
     Logger.Instance.AddLogmessage(
         new LogMessage
     {
         Color    = Color.DarkGreen,
         Loglevel = Loglevel.Verbose,
         Message  = string.Format("<{0}> {1}", bot.Name, string.Format(message, args))
     });
 }
Exemple #11
0
 public static void Write(BotClass bot, string message, params object[] args)
 {
     Logger.Instance.AddLogmessage(
         new LogMessage
         {
             Color = Color.DarkGreen,
             Loglevel = Loglevel.Verbose,
             Message = string.Format("<{0}> {1}", bot.Name, string.Format(message, args))
         });
 }
Exemple #12
0
        private void CreateChartStats(BotClass bot, Chart graph, ChartValueType valueType = ChartValueType.Auto)
        {
            if (Program.Mainform != null && graph != null)
            {
                try
                {
                    Program.Mainform.Invoke(new Action(() =>
                    {
                        try
                        {
                            if (bot.IsRunning)
                            {
                                Series serie = graph.Series.FirstOrDefault(x => x.Name == bot.Name);
                                if (serie == null)
                                {
                                    // Add Series
                                    graph.Series.Add(bot.Name);
                                    graph.Series[bot.Name].ChartType = SeriesChartType.FastLine;
                                    graph.Series[bot.Name].Points.Add(0);
                                    graph.Series[bot.Name].YAxisType       = AxisType.Primary;
                                    graph.Series[bot.Name].YValueType      = valueType;
                                    graph.Series[bot.Name].IsXValueIndexed = false;

                                    graph.Series[bot.Name].Color = Color.Black;
                                    foreach (
                                        Color color in
                                        ChartColors.Where(color => graph.Series.All(x => x.Color != color))
                                        )
                                    {
                                        graph.Series[bot.Name].Color = color;
                                    }
                                    graph.Series[bot.Name].Name = bot.Name;
                                }
                            }
                            else
                            {
                                Series serie = graph.Series.FirstOrDefault(x => x.Name == bot.Name);
                                if (serie != null)
                                {
                                    graph.Series.Remove(serie);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            DebugHelper.Exception(ex);
                        }
                    }));
                }
                catch (Exception ex)
                {
                    DebugHelper.Exception(ex);
                }
            }
        }
        /// <summary>
        ///     Write Log message for specific bot
        /// </summary>
        /// <param name="bot">BotClass</param>
        /// <param name="format"></param>
        /// <param name="args"></param>
        public void Write(BotClass bot, string format, params object[] args)
        {
            if (bot == null)
            {
                WriteGlobal(format, args);
                return;
            }
            var message = new LogMessage {
                Message = string.Format("<{0}> {1}", bot.Name, string.Format(format, args))
            };

            _instance.AddBuffer(message);
            AddToRtb(message);
        }
            private void HandleXml(string data)
            {
                BotStats stats;
                var      xml = new XmlSerializer(typeof(BotStats));

                using (var stringReader = new StringReader(data))
                {
                    stats = xml.Deserialize(stringReader) as BotStats;
                }

                if (stats != null)
                {
                    try
                    {
                        BotClass bot =
                            BotSettings.Instance.Bots.FirstOrDefault(
                                b =>
                                (b != null && b.Demonbuddy != null && b.Demonbuddy.Proc != null) &&
                                b.Demonbuddy.Proc.Id == stats.Pid);
                        if (bot != null)
                        {
                            if (bot.AntiIdle.Stats == null)
                            {
                                bot.AntiIdle.Stats = new BotStats();
                            }

                            bot.AntiIdle.UpdateCoinage(stats.Coinage);
                            bot.AntiIdle.Stats     = stats;
                            bot.AntiIdle.LastStats = DateTime.Now;
                            Send(bot.AntiIdle.Reply());
                            return;
                        }

                        Logger.Instance.WriteGlobal("Could not find a matching bot for Demonbuddy:{0}", stats.Pid);
                        return;
                    }
                    catch (Exception ex)
                    {
                        StatFailed++;
                        Send("Internal server error: " + ex.Message);
                        DebugHelper.Exception(ex);
                        return;
                    }
                }
                Send("Roger!");
            }
        public bool KillSession(BotClass bot)
        {
            var username = bot.Demonbuddy.BuddyAuthUsername;
            var password = bot.Demonbuddy.BuddyAuthPassword;

            // if username and password are empty stop here!
            if (username.Length <= 0 && password.Length <= 0) return false;

            var client = _buddyAuthWebClients.FirstOrDefault(c => c.Username.Equals(username) && c.Password.Equals(password));
            if (client == null)
            {
                client = new BuddyAuthWebClient(username,password);
                _buddyAuthWebClients.Add(client);
            }
            client.KillSession(bot);
            return false;
        }
Exemple #16
0
        }     // private void reloggerWorker()

        private bool StartBoth(BotClass bot)
        {
            bot.Diablo.Start();
            if (!bot.Diablo.IsRunning)
            {
                return(false);
            }

            bot.Demonbuddy.Start();
            if (!bot.Demonbuddy.IsRunning)
            {
                return(false);
            }

            bot.Status = "Monitoring";
            return(true);
        }
Exemple #17
0
        private void TestBots()
        {
            foreach (DataRow datarow in dtBotConfig.Rows)
            {
                BotClass bot = new BotClass(0, datarow[0].ToString(), datarow[1].ToString());
                OutputText(String.Format(">Testing {0} .......", bot.Name));

                if (HTTPUtility.GetMove(bot) != "failed")
                {
                    OutputText("test passed.\n");
                    datarow[3] = "Ok";
                }
                else
                {
                    datarow[2] = false;
                    datarow[3] = "Error";
                    OutputText(String.Format("{0} test failed:  Exception {1} \n", bot.Name, "failed to receive"));
                }
            }
        }
Exemple #18
0
        public bool KillSession(BotClass bot)
        {
            var username = bot.Demonbuddy.BuddyAuthUsername;
            var password = bot.Demonbuddy.BuddyAuthPassword;

            // if username and password are empty stop here!
            if (username.Length <= 0 && password.Length <= 0)
            {
                return(false);
            }

            var client = _buddyAuthWebClients.FirstOrDefault(c => c.Username.Equals(username) && c.Password.Equals(password));

            if (client == null)
            {
                client = new BuddyAuthWebClient(username, password);
                _buddyAuthWebClients.Add(client);
            }
            client.KillSession(bot);
            return(false);
        }
Exemple #19
0
        internal static string GetMove(BotClass bot)
        {
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(string.Format("{0}/move", bot.Url));

                //request.Timeout = 5000;
                request.Method      = "GET";
                request.ContentType = "application/x-www-form-urlencoded";



                var response = (HttpWebResponse)request.GetResponse();

                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                return(responseString);
            }
            catch
            {
                return("failed");
            }
        }
Exemple #20
0
            public void Update(BotClass bot)
            {
                long coinage = bot.AntiIdle.Stats.Coinage;

                if (coinage > 0)
                {
                    LastGain    = coinage - LastCoinage;
                    LastCoinage = coinage;
                    if (coinage < StartCoinage)
                    {
                        DebugHelper.Write(bot, "Reset! (Current coinage is below start coinage)", "GoldPerHour");
                        StartCoinage = 0;
                        TotalGain    = 0;
                    }
                    if (StartCoinage <= 0)
                    {
                        DebugHelper.Write(bot, "New start coinage: {0:N0}", "GoldPerHour", coinage);
                        StartCoinage = coinage;
                        StartTime    = DateTime.UtcNow;
                    }
                    else
                    {
                        if (LastGain > 0)
                        {
                            LastGainTime = DateTime.UtcNow;
                        }
                        else if (DateTime.UtcNow.Subtract(LastGainTime).TotalMinutes > 15)
                        {
                            DebugHelper.Write(bot, "Reset! No gold collected for 15 mins", "GoldPerHour");
                            Reset();
                        }
                        TotalGain += LastGain;
                        Debug.WriteLine("<{0}> LastGain: {1:N0}, TotalGain: {2:N0}, GPH: {3:N0}", bot.Name, LastGain,
                                        TotalGain, GoldPerHour);
                    }
                }
            }
        public void OnPressed()
        {
            Logger.Instance.WriteGlobal("Hotkey pressed: {0}+{1} : {2}", _hotkey.Modifier.ToString().Replace(", ", "+"),
                                        _hotkey.Key, Name);

            // Get active window
            IntPtr hwnd = WinAPI.GetForegroundWindow();

            BotClass test = BotSettings.Instance.Bots.FirstOrDefault(x => x.Diablo.MainWindowHandle == hwnd);

            if (test != null)
            {
                DiabloClass diablo = test.Diablo;
                if (diablo == null)
                {
                    return;
                }

                // Get window rectangle
                WinAPI.RECT rct;
                if (WinAPI.GetWindowRect(new HandleRef(test, hwnd), out rct))
                {
                    // Get screen where window is located
                    var    rect   = new Rectangle(rct.Left, rct.Top, rct.Width, rct.Heigth);
                    Screen screen = Screen.FromRectangle(rect);
                    // Calculate window position
                    double posX = (screen.Bounds.Width * 0.5) - 400 + screen.Bounds.X;
                    double posY = (screen.Bounds.Height * 0.5) - 300 + screen.Bounds.Y;
                    // Set window position and size
                    AutoPosition.ManualPositionWindow(hwnd, (int)posX, (int)posY, 800, 600);
                }

                return;
            }
            Logger.Instance.WriteGlobal("Resize Current Failed");
        }
 public void Update(BotClass bot)
 {
     long coinage = bot.AntiIdle.Stats.Coinage;
     if (coinage > 0)
     {
         LastGain = coinage - LastCoinage;
         LastCoinage = coinage;
         if (coinage < StartCoinage)
         {
             DebugHelper.Write(bot, "Reset! (Current coinage is below start coinage)", "GoldPerHour");
             StartCoinage = 0;
             TotalGain = 0;
         }
         if (StartCoinage <= 0)
         {
             DebugHelper.Write(bot, "New start coinage: {0:N0}", "GoldPerHour", coinage);
             StartCoinage = coinage;
             StartTime = DateTime.UtcNow;
         }
         else
         {
             if (LastGain > 0)
                 LastGainTime = DateTime.UtcNow;
             else if (DateTime.UtcNow.Subtract(LastGainTime).TotalMinutes > 15)
             {
                 DebugHelper.Write(bot, "Reset! No gold collected for 15 mins", "GoldPerHour");
                 Reset();
             }
             TotalGain += LastGain;
             Debug.WriteLine("<{0}> LastGain: {1:N0}, TotalGain: {2:N0}, GPH: {3:N0}", bot.Name, LastGain,
                 TotalGain, GoldPerHour);
         }
     }
 }
Exemple #23
0
 /// <summary>
 ///     Write Log message for specific bot
 /// </summary>
 /// <param name="bot">BotClass</param>
 /// <param name="format"></param>
 /// <param name="args"></param>
 public void Write(BotClass bot, string format, params object[] args)
 {
     if (bot == null)
     {
         WriteGlobal(format, args);
         return;
     }
     var message = new LogMessage {Message = string.Format("<{0}> {1}", bot.Name, string.Format(format, args))};
     instance.AddBuffer(message);
     addToRTB(message);
 }
        // Dont link this list

        public static void Create(BotClass bot)
        {
            var imp = new Impersonator();

            try
            {
                if (bot.UseWindowsUser)
                {
                    imp.Impersonate(bot.WindowsUserName, "localhost", bot.WindowsUserPassword);
                }

                bot.Status = "Create Diablo Clone";
                string basepath  = Path.GetDirectoryName(bot.Diablo.Location);
                string clonepath = Path.Combine(bot.DiabloCloneLocation, "Diablo III");

                // if diablo base path does not exist stop here!
                if (basepath != null && !Directory.Exists(basepath))
                {
                    bot.Stop();
                    throw new Exception("Diablo base directory does not exist!");
                }

                // Check if given language is installed on basepath
                string testpath = Path.Combine(basepath, @"Data_D3\PC\MPQs", General.GetLocale(bot.Diablo.Language));
                if (!Directory.Exists(testpath))
                {
                    bot.Stop();
                    throw new Exception(string.Format("ERROR: {0} language is not installed (path: {1})",
                                                      bot.Diablo.Language, testpath));
                }


                // if diablo clone does not exist create it
                if (!Directory.Exists(Path.Combine(clonepath, @"Data_D3\PC\MPQs\Cache")))
                {
                    Logger.Instance.Write(bot, "Creating new Diablo Clone");
                    Directory.CreateDirectory(Path.Combine(clonepath, @"Data_D3\PC\MPQs\Cache"));
                }

                // Create Search caches
                var baseFileCache  = new FileListCache(basepath);
                var cloneFileCache = new FileListCache(clonepath);

                // Check if all links are made for our clone
                foreach (FileListCache.MyFile p in baseFileCache.FileList)
                {
                    try
                    {
                        if (p.directory && !Directory.Exists(Path.Combine(clonepath.ToLower(), p.Path.ToLower())))
                        {
                            if (!_noLinks.Any(n => General.WildcardMatch(n.Source, p.Path)))
                            {
                                Logger.Instance.Write(bot, "NewLink: {0} -> {1}", Path.Combine(clonepath, p.Path),
                                                      Path.Combine(basepath, p.Path));
                                //if (!CreateSymbolicLink( Path.Combine(clonepath,p.Path),  Path.Combine(basepath,p.Path), 1))
                                //  throw new Exception("Failed to create link!");
                                Directory.CreateDirectory(Path.Combine(clonepath, p.Path));
                            }
                            continue;
                        }
                        if (!p.directory && !File.Exists(Path.Combine(clonepath.ToLower(), p.Path.ToLower())))
                        {
                            if (!_noLinks.Any(n => General.WildcardMatch(n.Source, p.Path)))
                            {
                                Logger.Instance.Write(bot, "NewLink: {0} -> {1}", Path.Combine(clonepath, p.Path),
                                                      Path.Combine(basepath, p.Path));
                                if (Path.GetExtension(Path.Combine(clonepath, p.Path)).ToLower().Equals(".exe"))
                                {
                                    if (
                                        !CreateHardLink(Path.Combine(clonepath, p.Path), Path.Combine(basepath, p.Path),
                                                        IntPtr.Zero))
                                    {
                                        throw new Exception("Failed to create link!");
                                    }
                                }
                                else
                                {
                                    if (
                                        !CreateSymbolicLink(Path.Combine(clonepath, p.Path),
                                                            Path.Combine(basepath, p.Path), 0))
                                    {
                                        throw new Exception("Failed to create link!");
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }

                // Remove links that have no target

                /*
                 * foreach (var p in cloneFileCache.FileList)
                 * {
                 *  try
                 *  {
                 *      if (p.directory && !Directory.Exists(Path.Combine(basepath, p.Path)))
                 *      {
                 *          if (!_noLinks.Any(n => General.WildcardMatch(n.Source.ToLower(), p.Path.ToLower())))
                 *              Console.WriteLine("Delete: {0}", p.Path);
                 *          continue;
                 *      }
                 *
                 *      if (!p.directory && !File.Exists(Path.Combine(basepath.ToLower(), p.Path.ToLower())))
                 *      {
                 *          if (!_noLinks.Any(n => General.WildcardMatch(n.Source, p.Path)))
                 *              Console.WriteLine("Delete: {0}", p.Path);
                 *      }
                 *  }
                 *  catch (Exception ex)
                 *  {
                 *      Logger.Instance.Write(bot, ex.ToString());
                 *  }
                 * }
                 */
            }
            catch (Exception ex)
            {
                bot.Stop();
                DebugHelper.Write(bot, "Failed to create clone!");
                DebugHelper.Exception(ex);
            }
            imp.Dispose();
        }
Exemple #25
0
        public static ProcessStartInfo ImpersonateStartInfo(ProcessStartInfo startinfo, BotClass bot)
        {
            if (bot.UseWindowsUser)
            {
                if (!ExistsAsAdmin(bot.WindowsUserName))
                {
                    if (bot.CreateWindowsUser)
                        Create(bot.WindowsUserName, bot.WindowsUserPassword, isAdmin: true);
                    else
                    {
                        Logger.Instance.Write(
                            "User Account \"{0}\" does not exist and we are not allowed to create it",
                            bot.WindowsUserName);
                        bot.Stop();
                        return startinfo;
                    }
                }

                startinfo.UserName = bot.WindowsUserName;
                var encPassword = new SecureString();
                foreach (char c in bot.WindowsUserPassword)
                    encPassword.AppendChar(c);
                startinfo.Password = encPassword;
                startinfo.UseShellExecute = false;
            }
            return startinfo;
        }
Exemple #26
0
        private void ReloggerWorker()
        {
            // Check if we are launched by windows RUN
            if (CommandLineArgs.WindowsAutoStart && !_autoStartDone)
            {
                _autoStartDone = true;
                Logger.Instance.WriteGlobal("Windows auto start delaying with {0} seconds", Settings.Default.StartDelay);
                Thread.Sleep((int)Settings.Default.StartDelay*1000);
                foreach (var bot in BotSettings.Instance.Bots.Where(c => c.IsEnabled))
                {
                    bot.AntiIdle.Reset(freshstart: true); // Reset AntiIdle
                    bot.IsStarted = true;
                    bot.Status = "Auto Start...";
                }
            }
            // Check if we are launched with the autostart
            if (CommandLineArgs.AutoStart && !_autoStartDone)
            {
                _autoStartDone = true;
                foreach (var bot in BotSettings.Instance.Bots.Where(c => c.IsEnabled))
                {
                    bot.AntiIdle.Reset(freshstart: true); // Reset AntiIdle
                    bot.IsStarted = true;
                    bot.Status = "Auto Start...";
                }
            }

            Logger.Instance.WriteGlobal("Relogger Thread Starting!");
            while (true)
            {
                try
                {
                    // Paused
                    if (Program.Pause)
                    {
                        Thread.Sleep(1000);
                        continue;
                    }
                    // Check / validate internet connection
                    if (!ConnectionCheck.IsConnected || !ConnectionCheck.ValidConnection)
                    {
                        Debug.WriteLine("Internet validation failed looping until success");
                        Thread.Sleep(1000);
                        continue;
                    }

                    foreach (var bot in BotSettings.Instance.Bots.Where(bot => bot != null))
                    {
                        if (Program.Pause) break;

                        var time = DateTime.Now; // set current time to calculate sleep time at end of loop
                        CurrentBot = bot;
                        Debug.WriteLine(bot.Name + ":" + ":" + bot.IsRunning);
                        Debug.WriteLine("State=" + bot.AntiIdle.State);
                        if (bot.IsRunning && bot.IsStarted && !bot.Week.ShouldRun(bot.IsRunning))
                        {
                            // We need to stop
                            Logger.Instance.Write("We are scheduled to stop");
                            bot.Week.NextSchedule(true);
                            bot.IsRunning = false;
                            bot.Diablo.Stop();
                            bot.Demonbuddy.Stop();
                            bot.Status = "Scheduled stop!";
                        }
                        else if (!bot.IsRunning && bot.IsStarted && bot.Week.ShouldRun(bot.IsRunning))
                        {
                            // we need to start
                            Logger.Instance.Write("We are scheduled to start");
                            bot.Week.NextSchedule(false);
                            bot.IsRunning = true;
                            bot.StartTime = DateTime.Now;
                            StartBoth(bot);
                        }
                        else if (bot.IsRunning)
                        {
                            // Check if process is responding
                            bot.Diablo.CrashCheck();
                            if (bot.AntiIdle.IsInitialized)
                                bot.Demonbuddy.CrashCheck();

                            if (!bot.Diablo.IsRunning)
                            {
                                Logger.Instance.Write("Diablo:{0}: Process is not running", bot.Diablo.Proc.Id);
                                if (bot.Demonbuddy.IsRunning)
                                {
                                    Logger.Instance.Write("Demonbuddy:{0}: Closing db", bot.Demonbuddy.Proc.Id);
                                    bot.Demonbuddy.Stop();
                                }
                                StartBoth(bot);
                            }
                            else if (!bot.Demonbuddy.IsRunning)
                            {
                                Logger.Instance.Write("Demonbuddy:{0}: Process is not running", bot.Demonbuddy.Proc.Id);
                                bot.Demonbuddy.Start();
                            }
                            else if (bot.AntiIdle.State != IdleState.Initialize && General.DateSubtract(bot.AntiIdle.LastStats) > 120)
                            {
                                Logger.Instance.Write("We did not recieve any stats during 120 seconds!");
                                bot.Restart();
                            }
                            else if (bot.AntiIdle.IsInitialized)
                            {
                                if (bot.ProfileSchedule.IsDone)
                                {
                                    Logger.Instance.Write("Profile: \"{0}\" Finished!", bot.ProfileSchedule.Current.Name);
                                    bot.AntiIdle.State = IdleState.NewProfile;
                                }
                            }

                        } // else if (bot.isRunning)
                        else
                            bot.StartTime = DateTime.Now;

                        // calculate sleeptime
                        var sleep = (int) (Program.Sleeptime - DateTime.Now.Subtract(time).TotalMilliseconds);
                        if (sleep > 0) Thread.Sleep(sleep);
                    }
                } // try
                catch (InvalidOperationException iox)
                { // Catch error when bot is edited while in a loop
                    Logger.Instance.WriteGlobal(iox.Message);
                    continue;
                }
                catch (Exception ex)
                {
                    if (_isStopped) return;
                    Logger.Instance.WriteGlobal("Relogger Crashed! with message {0}", ex.Message);
                    Logger.Instance.WriteGlobal(ex.StackTrace);
                    Logger.Instance.WriteGlobal("Waiting 10 seconds and try again!");
                    Thread.Sleep(10000);
                    continue;
                }
                Thread.Sleep(1000);
            } // while
        }
 public void LoadSchedule(BotClass bot)
 {
     var loadScheduleThread = new Thread(ScheduleLoader);
     loadScheduleThread.Start(bot);
 }
 public void LoadSchedule(BotClass bot)
 {
     var loadScheduleThread = new Thread(new ParameterizedThreadStart(ScheduleLoader));
     loadScheduleThread.Start(bot);
 }
            private void HandleMsg(string msg)
            {
                // Message Example:
                // PID:CMD DATA
                // 1234:GameLeft 25-09-1985 18:27:00
                Debug.WriteLine("Recieved: " + msg);
                try
                {
                    string pid = msg.Split(':')[0];
                    string cmd = msg.Substring(pid.Length + 1).Split(' ')[0];
                    int    x;
                    msg = msg.Substring(((x = pid.Length + cmd.Length + 2) >= msg.Length ? 0 : x));

                    BotClass b =
                        BotSettings.Instance.Bots.FirstOrDefault(
                            f =>
                            (f.Demonbuddy != null && f.Demonbuddy.Proc != null) &&
                            f.Demonbuddy.Proc.Id == Convert.ToInt32(pid));
                    if (b == null)
                    {
                        Send("Error: Unknown process");
                        StatFailed++;
                        return;
                    }

                    switch (cmd)
                    {
                    case "Initialized":
                        b.AntiIdle.Stats = new BotStats
                        {
                            LastGame    = DateTime.Now.Ticks,
                            LastPulse   = DateTime.Now.Ticks,
                            PluginPulse = DateTime.Now.Ticks,
                            LastRun     = DateTime.Now.Ticks
                        };
                        b.AntiIdle.LastStats     = DateTime.Now;
                        b.AntiIdle.State         = IdleState.CheckIdle;
                        b.AntiIdle.IsInitialized = true;
                        b.AntiIdle.InitAttempts  = 0;
                        Send("Roger!");
                        break;

                    case "GameLeft":
                        b.ProfileSchedule.Count++;
                        if (b.ProfileSchedule.Current.Runs > 0)
                        {
                            Logger.Instance.Write(b, "Runs completed ({0}/{1})", b.ProfileSchedule.Count,
                                                  b.ProfileSchedule.MaxRuns);
                        }
                        else
                        {
                            Logger.Instance.Write(b, "Runs completed {0}", b.ProfileSchedule.Count);
                        }

                        if (b.ProfileSchedule.IsDone)
                        {
                            string newprofile = b.ProfileSchedule.GetProfile;
                            Logger.Instance.Write(b, "Next profile: {0}", newprofile);
                            Send("LoadProfile " + newprofile);
                        }
                        else
                        {
                            Send("Roger!");
                        }
                        break;

                    case "UserStop":
                        b.Status         = string.Format("User Stop: {0:d-m H:M:s}", DateTime.Now);
                        b.AntiIdle.State = IdleState.UserStop;
                        Logger.Instance.Write(b, "Demonbuddy stopped by user");
                        Send("Roger!");
                        break;

                    case "StartDelay":
                        var delay = new DateTime(long.Parse(msg));
                        b.AntiIdle.StartDelay = delay.AddSeconds(60);
                        b.AntiIdle.State      = IdleState.StartDelay;
                        Send("Roger!");
                        break;

                    // Giles Compatibility
                    case "ThirdpartyStop":
                        b.Status         = string.Format("Thirdparty Stop: {0:d-m H:M:s}", DateTime.Now);
                        b.AntiIdle.State = IdleState.UserStop;
                        Logger.Instance.Write(b, "Demonbuddy stopped by Thirdparty");
                        Send("Roger!");
                        break;

                    case "TrinityPause":
                        b.AntiIdle.State = IdleState.UserPause;
                        Logger.Instance.Write(b, "Trinity Pause Detected");
                        Send("Roger!");
                        break;

                    case "AllCompiled":
                    {
                        Logger.Instance.Write(b, "Check Force Enable Plugins? {0}", b.Demonbuddy.ForceEnableAllPlugins);
                        Send(b.Demonbuddy.ForceEnableAllPlugins ? "ForceEnableAll" : "ForceEnableYar");
                        break;
                    }

                    case "CrashTender":
                        if (Settings.Default.UseKickstart && File.Exists(msg))
                        {
                            b.Demonbuddy.CrashTender(msg);
                        }
                        else
                        {
                            b.Demonbuddy.CrashTender();
                        }
                        Send("Roger!");
                        break;

                    case "CheckConnection":
                        ConnectionCheck.CheckValidConnection(true);
                        Send("Roger!");
                        break;

                    case "NewMonsterPowerLevel":
                        Logger.Instance.Write(b, "Sending MonsterPowerLevel: {0}",
                                              b.ProfileSchedule.Current.MonsterPowerLevel);
                        Send("MonsterPower " + (int)b.ProfileSchedule.Current.MonsterPowerLevel);
                        break;

                    case "D3Exit":
                        Send("Shutdown");
                        break;

                    // Unknown command reply
                    default:
                        Send("Unknown command!");
                        Logger.Instance.WriteGlobal("Unknown command recieved: " + msg);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    StatFailed++;
                    Send("Internal server error: " + ex.Message);
                    DebugHelper.Exception(ex);
                }
            }
        private void ReloggerWorker()
        {
            // Check if we are launched by windows RUN
            if (CommandLineArgs.WindowsAutoStart && !_autoStartDone)
            {
                _autoStartDone = true;
                Logger.Instance.WriteGlobal("Windows auto start delaying with {0} seconds", Settings.Default.StartDelay);
                Thread.Sleep((int)Settings.Default.StartDelay * 1000);
                foreach (BotClass bot in BotSettings.Instance.Bots.Where(c => c.IsEnabled))
                {
                    bot.AntiIdle.Reset(freshstart: true); // Reset AntiIdle
                    bot.IsStarted = true;
                    bot.Status = "Auto Start...";
                }
            }
            // Check if we are launched with the autostart
            if (CommandLineArgs.AutoStart && !_autoStartDone)
            {
                _autoStartDone = true;
                foreach (BotClass bot in BotSettings.Instance.Bots.Where(c => c.IsEnabled))
                {
                    bot.AntiIdle.Reset(freshstart: true); // Reset AntiIdle
                    bot.IsStarted = true;
                    bot.Status = "Auto Start...";
                }
            }

            DebugHelper.Write("Relogger Thread Starting!");
            while (true)
            {
                try
                {
                    if (_isStopped)
                        return;

                    // Paused
                    if (Program.Pause)
                    {
                        Thread.Sleep(1000);
                        continue;
                    }

                    List<Process> blizzardErrorProcs =
                         (from p in Process.GetProcessesByName("BlizzardError.exe")
                          select p).ToList();
                    if (blizzardErrorProcs.Any())
                    {
                        try
                        {
                            foreach (var p in blizzardErrorProcs)
                            {
                                Logger.Instance.Write("Killing BlizzardError.exe with PID {0}", p.Id);
                                p.Kill();
                            }

                        }
                        catch (Exception ex)
                        {
                            Logger.Instance.Write("Exception killing BlizzardError.exe: " + ex);
                        }
                    }

                    if (DateTime.UtcNow.Subtract(_lastSaveSettings).TotalSeconds > 10)
                    {
                        _lastSaveSettings = DateTime.UtcNow;
                        Settings.Default.Save();
                        BotSettings.Instance.Save();
                    }

                    // Check / validate internet connection
                    if (!ConnectionCheck.IsConnected || !ConnectionCheck.ValidConnection)
                    {
                        Debug.WriteLine("Internet validation failed looping until success");
                        Thread.Sleep(1000);
                        continue;
                    }

                    foreach (BotClass bot in BotSettings.Instance.Bots.Where(bot => bot != null).ToList())
                    {
                        if (Program.Pause)
                            break;

                        DateTime time = DateTime.UtcNow; // set current time to calculate sleep time at end of loop
                        CurrentBot = bot;
                        //Debug.WriteLine(bot.Name + ":" + ":" + bot.IsRunning);
                        //Debug.WriteLine("State=" + bot.AntiIdle.State);
                        if (bot.IsRunning && bot.IsStarted && !bot.Week.ShouldRun(bot.IsRunning))
                        {
                            // We need to stop
                            Logger.Instance.Write("We are scheduled to stop");
                            bot.Week.NextSchedule(true);
                            bot.IsRunning = false;
                            bot.Demonbuddy.Stop();
                            bot.Diablo.Stop();
                            bot.Status = "Scheduled stop!";
                        }
                        else if (!bot.IsRunning && bot.IsStarted && bot.Week.ShouldRun(bot.IsRunning))
                        {
                            // we need to start
                            Logger.Instance.Write("We are scheduled to start");
                            bot.Week.NextSchedule(false);
                            bot.IsRunning = true;
                            bot.StartTime = DateTime.UtcNow;
                            StartBoth(bot);
                        }
                        else if (!bot.IsStandby && bot.IsRunning)
                        {
                            // Check if process is responding
                            bot.Diablo.CrashCheck();
                            if (bot.AntiIdle.IsInitialized)
                                bot.Demonbuddy.CrashCheck();

                            if (!bot.Diablo.IsRunning)
                            {
                                if (bot.Diablo.Proc != null)
                                    Logger.Instance.Write("Diablo:{0}: Process is not running", bot.Diablo.Proc.Id);
                                //if (bot.Demonbuddy.IsRunning && bot.Demonbuddy.Proc != null)
                                //{
                                //    Logger.Instance.Write("Demonbuddy:{0}: Closing db", bot.Demonbuddy.Proc.Id);
                                //    bot.Demonbuddy.Stop();
                                //}
                                if (bot.Demonbuddy.IsRunning && bot.Demonbuddy.Proc != null)
                                {
                                    Logger.Instance.Write("Demonbuddy:{0}: Waiting for Demonbuddy to self close", bot.Demonbuddy.Proc.Id);
                                }
                                else
                                {
                                    StartBoth(bot);
                                }
                            }
                            else if (!bot.Demonbuddy.IsRunning)
                            {
                                Logger.Instance.Write("Demonbuddy: Process is not running");
                                bot.Demonbuddy.Start();
                            }
                            else if (Settings.Default.AntiIdleStatsDuration > 0 && bot.AntiIdle.State != IdleState.Initialize && General.DateSubtract(bot.AntiIdle.LastStats) >
                                (double)Settings.Default.AntiIdleStatsDuration)
                            {
                                Logger.Instance.Write("We did not recieve any stats during 300 seconds!");
                                bot.Restart();
                            }
                            else if (bot.AntiIdle.IsInitialized)
                            {
                                if (bot.ProfileSchedule.IsDone)
                                {
                                    Logger.Instance.Write("Profile: \"{0}\" Finished!", bot.ProfileSchedule.Current.Name);
                                    bot.AntiIdle.State = IdleState.NewProfile;
                                }
                            }
                        }
                        else
                        {
                            //Logger.Instance.Write("Bot Standby={0} Running={1} D3Running={2} DBRunning={3}", bot.IsStandby, bot.IsRunning, bot.Diablo.IsRunning, bot.Demonbuddy.IsRunning);
                            bot.StartTime = DateTime.UtcNow;
                        }
                        // calculate sleeptime
                        var sleep = (int)(Program.Sleeptime - DateTime.UtcNow.Subtract(time).TotalMilliseconds);
                        if (sleep > 0)
                            Thread.Sleep(sleep);
                    }
                } // try
                catch (InvalidOperationException)
                {
                    // Catch error when bot is edited while in a loop
                    //Logger.Instance.WriteGlobal(iox.Message);
                    continue;
                }
                catch (Exception ex)
                {
                    if (_isStopped)
                        return;
                    Logger.Instance.WriteGlobal("Relogger Crashed! with message {0}", ex.Message);
                    DebugHelper.Exception(ex);
                    Logger.Instance.WriteGlobal("Waiting 10 seconds and try again!");
                    Thread.Sleep(10000);
                    continue;
                }
                Thread.Sleep(1000);
            } // while
        }
        public void LoadSchedule(BotClass bot)
        {
            var loadScheduleThread = new Thread(new ParameterizedThreadStart(ScheduleLoader));

            loadScheduleThread.Start(bot);
        }
Exemple #32
0
        static void Main(string[] args)
        {
            var bot = new BotClass();

            bot.RunAsync().GetAwaiter().GetResult();
        }
Exemple #33
0
 public WizardMain(int index)
 {
     this.index = index;
     bot = BotSettings.Instance.Bots[index];
     InitializeComponent();
 }
Exemple #34
0
            public static Tuple <object[]> checkStatusActivity(BotClass caller, object[,] arrRandomActivity)
            {
                //return parameter: force status change,the status array
                Boolean isWeekday = false;

                if (DateTime.Now.ToString("dddd").ToLower() == "monday" || DateTime.Now.ToString("dddd").ToLower() == "tuesday" ||
                    DateTime.Now.ToString("dddd").ToLower() == "wednesday" || DateTime.Now.ToString("dddd").ToLower() == "thursday" ||
                    DateTime.Now.ToString("dddd").ToLower() == "friday")
                {
                    isWeekday = true;
                }

                //start
                //if (randomizePlayingWith)
                //{
                //    //doremi->hazuki,hazuki->doremi

                //    //random doremi:
                //    int randomPlayingWithDoremi = new Random().Next(0, 5);
                //    if(!Config.Doremi.Status.isPlayingWith &&
                //        randomPlayingWithDoremi == 0)
                //    {
                //        arrPlayingWith.RemoveAt(0);
                //        Config.Doremi.Status.currentActivity = arrPlayingWith[0][0];
                //        Config.Doremi.Status.userStatus = (UserStatus)arrPlayingWith[0, 1];

                //    } else
                //    {

                //    }

                //    //random hazuki:
                //    //random aiko:
                //    //random onpu:
                //    //random momoko:
                //}
                //end

                object[] returnStatus = { "init", "init", "init" };

                Boolean forceChange = false;

                //if (Config.Doremi.Status.isBirthday())
                //{
                //    if(caller == BotClass.Doremi)
                //    {
                //        returnStatus[0] = myBirthdayActivity;
                //        returnStatus[1] = myBirthdayActivityReply;
                //        returnStatus[2] = myBirthdayActivityUserStatus;
                //    } else
                //    {
                //        returnStatus[0] = Config.Doremi.Status.birthdayActivity;
                //        returnStatus[1] = "We're celebrating Doremi birthday today.";
                //        returnStatus[2] = myBirthdayActivityUserStatus;
                //    }
                //    forceChange = true;
                //}

                //if (Config.Hazuki.Status.isBirthday())
                //{
                //    if (caller == BotClass.Hazuki)
                //    {
                //        returnStatus[0] = myBirthdayActivity;
                //        returnStatus[1] = myBirthdayActivityReply;
                //        returnStatus[2] = myBirthdayActivityUserStatus;
                //    }
                //    else
                //    {
                //        returnStatus[0] = Config.Hazuki.Status.birthdayActivity;
                //        returnStatus[1] = "We're celebrating Hazuki birthday today.";
                //        returnStatus[2] = myBirthdayActivityUserStatus;
                //    }
                //    forceChange = true;
                //}

                //if (Config.Aiko.Status.isBirthday())
                //{
                //    if (caller == BotClass.Aiko)
                //    {
                //        returnStatus[0] = myBirthdayActivity;
                //        returnStatus[1] = myBirthdayActivityReply;
                //        returnStatus[2] = myBirthdayActivityUserStatus;
                //    }
                //    else
                //    {
                //        returnStatus[0] = Config.Aiko.Status.birthdayActivity;
                //        returnStatus[1] = "We're celebrating Aiko birthday today.";
                //        returnStatus[2] = myBirthdayActivityUserStatus;
                //    }
                //    forceChange = true;
                //}

                //if (Config.Onpu.Status.isBirthday())
                //{
                //    if (caller == BotClass.Onpu)
                //    {
                //        returnStatus[0] = myBirthdayActivity;
                //        returnStatus[1] = myBirthdayActivityReply;
                //        returnStatus[2] = myBirthdayActivityUserStatus;
                //    }
                //    else
                //    {
                //        returnStatus[0] = Config.Onpu.Status.birthdayActivity;
                //        returnStatus[1] = "We're celebrating Onpu birthday today.";
                //        returnStatus[2] = myBirthdayActivityUserStatus;
                //    }
                //    forceChange = true;
                //}

                //if (Config.Momoko.Status.isBirthday())
                //{
                //    if (caller == BotClass.Momoko)
                //    {
                //        returnStatus[0] = myBirthdayActivity;
                //        returnStatus[1] = myBirthdayActivityReply;
                //        returnStatus[2] = myBirthdayActivityUserStatus;
                //    }
                //    else
                //    {
                //        returnStatus[0] = Config.Momoko.Status.birthdayActivity;
                //        returnStatus[1] = "We're celebrating Momoko birthday today.";
                //        returnStatus[2] = myBirthdayActivityUserStatus;
                //    }
                //    forceChange = true;
                //}


                if (!forceChange)
                {
                    int hourNow = Convert.ToInt32(DateTime.Now.ToString("%H"));
                    if (hourNow >= 22 || hourNow < 4)
                    {
                        returnStatus = statusSleeping;
                    }
                    //else if (isWeekday && hourNow >= 4 && hourNow <= 10)
                    //{
                    //    returnStatus = statusSchool;
                    //}
                    else if (isWeekday && hourNow >= 11 && hourNow <= 12)
                    {
                        returnStatus = statusGlobalMahoDou;
                    }
                    else
                    {
                        //random activity:
                        //,reply,user status

                        Random rnd      = new Random();
                        int    rndIndex = rnd.Next(0, arrRandomActivity.GetLength(0));

                        //original:
                        returnStatus = new object[] { arrRandomActivity[rndIndex, 0],
                                                      arrRandomActivity[rndIndex, 1],
                                                      arrRandomActivity[rndIndex, 2] };
                    }
                }

                return(Tuple.Create(returnStatus));
            }
Exemple #35
0
        private void button1_Click(object sender, EventArgs e)
        {
            // NEXT / finish
            if (_stepCount == FinishCount)
            {
                int result;
                var b = new BotClass();
                var db = new DemonbuddyClass();
                var d = new DiabloClass();
                var ps = new ProfileScheduleClass();
                var w = new Helpers.Bot.WeekSchedule();

                b.Name = _ucDemonbuddy.textBox1.Text;
                b.Description = _ucDemonbuddy.textBox2.Text;

                // Advanced
                b.CreateWindowsUser = _ucAdvanced.checkBox2.Checked;
                b.UseWindowsUser = _ucAdvanced.checkBox1.Checked;
                b.WindowsUserName = _ucAdvanced.textBox1.Text;
                b.WindowsUserPassword = _ucAdvanced.maskedTextBox1.Text;
                b.D3PrefsLocation = _ucAdvanced.textBox3.Text;
                b.UseDiabloClone = _ucAdvanced.checkBox3.Checked;
                b.DiabloCloneLocation = _ucAdvanced.textBox2.Text;

                // Demonbuddy
                db.Location = _ucDemonbuddy.textBox4.Text;
                db.Key = _ucDemonbuddy.textBox3.Text;
                db.CombatRoutine = _ucDemonbuddy.comboBox1.SelectedItem != null
                    ? _ucDemonbuddy.comboBox1.SelectedItem.ToString()
                    : _ucDemonbuddy.comboBox1.Text;
                db.NoFlash = _ucDemonbuddy.checkBox1.Checked;
                db.AutoUpdate = _ucDemonbuddy.checkBox2.Checked;
                db.NoUpdate = _ucDemonbuddy.checkBox3.Checked;
                db.BuddyAuthUsername = _ucDemonbuddy.textBox9.Text;
                db.BuddyAuthPassword = _ucDemonbuddy.maskedTextBox2.Text;
                db.Priority = _ucDemonbuddy.comboBox2.SelectedIndex;
                db.ForceEnableAllPlugins = _ucDemonbuddy.checkBox5.Checked;

                db.ManualPosSize = _ucDemonbuddy.checkBox4.Checked;
                int.TryParse(_ucDemonbuddy.textBox6.Text, out result);
                db.X = result;
                int.TryParse(_ucDemonbuddy.textBox5.Text, out result);
                db.Y = result;
                int.TryParse(_ucDemonbuddy.textBox10.Text, out result);
                db.W = result;
                int.TryParse(_ucDemonbuddy.textBox11.Text, out result);
                db.H = result;

                // Diablo
                d.Username = _ucDiablo.username.Text;
                d.Password = _ucDiablo.password.Text;
                d.Location = _ucDiablo.diablo3Path.Text;
                d.Language = _ucDiablo.language.SelectedItem.ToString();
                d.Region = _ucDiablo.region.SelectedItem.ToString();
                d.UseAuthenticator = _ucDiablo.checkBox1.Checked;
                d.Serial = string.Format("{0}-{1}-{2}-{3}", _ucDiablo.textBox4.Text, _ucDiablo.textBox5.Text,
                    _ucDiablo.textBox7.Text, _ucDiablo.textBox6.Text);
                d.Serial2 = string.Format("{0}{1}{2}{3}", _ucDiablo.textBox4.Text, _ucDiablo.textBox5.Text,
                    _ucDiablo.textBox7.Text, _ucDiablo.textBox6.Text);
                d.RestoreCode = _ucDiablo.textBox8.Text;
                d.Priority = _ucDiablo.processorAffinity.SelectedIndex;
                d.UseIsBoxer = _ucDiablo.useInnerSpace.Checked;
                d.CharacterSet = _ucDiablo.characterSet.Text;
                d.DisplaySlot = _ucDiablo.displaySlot.Text;
                d.NoFrame = _ucDiablo.removeWindowFrame.Checked;

                // Affinity Diablo
                if (d.CpuCount != Environment.ProcessorCount)
                {
                    d.ProcessorAffinity = d.AllProcessors;
                    d.CpuCount = Environment.ProcessorCount;
                }

                if (AffinityDiablo.cpus.Count != d.CpuCount)
                {
                    Logger.Instance.Write(
                        "For whatever reason Diablo and UI see different number of CPUs, affinity disabled");
                }
                else
                {
                    int intProcessorAffinity = 0;
                    for (int i = 0; i < d.CpuCount; i++)
                    {
                        if (AffinityDiablo.cpus[i].Checked)
                            intProcessorAffinity |= (1 << i);
                    }
                    if (intProcessorAffinity == 0)
                        intProcessorAffinity = -1;
                    d.ProcessorAffinity = intProcessorAffinity;
                }
                if (AffinityDiablo != null)
                    AffinityDiablo.Dispose();

                // Affinity Demonbuddy
                if (db.CpuCount != Environment.ProcessorCount)
                {
                    db.ProcessorAffinity = db.AllProcessors;
                    db.CpuCount = Environment.ProcessorCount;
                }

                if (AffinityDemonbuddy.cpus.Count != db.CpuCount)
                {
                    Logger.Instance.Write(
                        "For whatever reason Demonbuddy and UI see different number of CPUs, affinity disabled");
                }
                else
                {
                    int intProcessorAffinity = 0;
                    for (int i = 0; i < db.CpuCount; i++)
                    {
                        if (AffinityDemonbuddy.cpus[i].Checked)
                            intProcessorAffinity |= (1 << i);
                    }
                    if (intProcessorAffinity == 0)
                        intProcessorAffinity = -1;
                    db.ProcessorAffinity = intProcessorAffinity;
                }
                if (AffinityDemonbuddy != null)
                    AffinityDemonbuddy.Dispose();

                d.ManualPosSize = _ucDiablo.manualPositionAndSize.Checked;
                if (d.ManualPosSize)
                {
                    int.TryParse(_ucDiablo.positionX.Text, out result);
                    d.X = result;
                    int.TryParse(_ucDiablo.positionY.Text, out result);
                    d.Y = result;
                    int.TryParse(_ucDiablo.width.Text, out result);
                    d.W = result;
                    int.TryParse(_ucDiablo.height.Text, out result);
                    d.H = result;
                }

                w.GenerateNewSchedule();
                w.Shuffle = _ucWeekSchedule.checkBox1.Checked;
                w.MinRandom = Convert.ToInt32(_ucWeekSchedule.textBox1.Text);
                w.MaxRandom = Convert.ToInt32(_ucWeekSchedule.textBox2.Text);

                ps.Profiles = _ucProfileSchedule.Profiles;
                ps.MaxRandomTime = Convert.ToInt32(_ucProfileSchedule.textBox1.Text);
                ps.MaxRandomRuns = Convert.ToInt32(_ucProfileSchedule.textBox2.Text);
                ps.Random = _ucProfileSchedule.checkBox1.Checked;

                b.Week = w;
                b.Demonbuddy = db;
                b.Diablo = d;
                b.ProfileSchedule = ps;

                if (bot != null && index >= 0)
                {
                    Logger.Instance.WriteGlobal("Editing bot: {0}", b.Name);

                    // Copy some important stuff from old bot

                    b.IsStarted = BotSettings.Instance.Bots[index].IsStarted;
                    b.IsEnabled = BotSettings.Instance.Bots[index].IsEnabled;
                    b.IsRunning = BotSettings.Instance.Bots[index].IsRunning;
                    b.Diablo.Proc = BotSettings.Instance.Bots[index].Diablo.Proc;
                    b.Demonbuddy.Proc = BotSettings.Instance.Bots[index].Demonbuddy.Proc;
                    b.Demonbuddy.MainWindowHandle = BotSettings.Instance.Bots[index].Demonbuddy.MainWindowHandle;
                    b.Diablo.MainWindowHandle = BotSettings.Instance.Bots[index].Diablo.MainWindowHandle;
                    b.AntiIdle = BotSettings.Instance.Bots[index].AntiIdle;
                    b.Week.ForceStart = BotSettings.Instance.Bots[index].Week.ForceStart;
                    b.RunningTime = BotSettings.Instance.Bots[index].RunningTime;

                    BotSettings.Instance.Bots[index] = b;
                }
                else
                {
                    Logger.Instance.WriteGlobal("Adding new bot: {0}", b.Name);
                    BotSettings.Instance.Bots.Add(b);
                }

                BotSettings.Instance.Save();
                shouldClose = true;
                ActiveForm.Close();

                BotSettings.Instance.Save();
                Program.Mainform.UpdateGridView();
                return;
            }

            if (ValidateControl(Controls[_stepCount]))
            {
                Controls[_stepCount].Visible = false; // Hide old
                _stepCount++;
                Controls[_stepCount].Visible = true; // Show new
            }

            if (_stepCount > _mainCount)
                buttonBack.Enabled = true;
            if (_stepCount == FinishCount)
                buttonNext.Text = "Save!";
        }
        public void KillSession(BotClass bot)
        {
            lock (_webClientLock)
            {
                DateTime logintime = bot.Demonbuddy.LoginTime;
                _webClient.Headers["Referer"] = "http://buddyauth.com/User/Sessions";
                var data = new NameValueCollection();
                Session match = GetSessions()
                    .Where(
                        i =>
                            logintime.Subtract(i.time).TotalSeconds < 16 &&
                            logintime.Subtract(i.time).TotalSeconds > -16)
                    .OrderBy(i => logintime.Subtract(i.time).TotalSeconds).FirstOrDefault();

                if (match.id == 0)
                {
                    Logger.Instance.Write(bot, "BuddyAuth: No session found.");
                    return;
                }

                data.Set("selectedSessions[" + match.number + "].Id", Convert.ToString(match.id));
                data.Set("selectedSessions[" + match.number + "].IsChecked", "true");

                try
                {
                    int retry = 3;
                    do
                    {
                        try
                        {
                            _webClient.UploadValues("http://buddyauth.com/User/Sessions", data);
                            Logger.Instance.Write(bot, "BuddyAuth: Session with id: {0} killed! (Time difference: {1})",
                                match.id, logintime.Subtract(match.time).TotalSeconds);
                            return;
                        }
                        catch (WebException wex)
                        {
                            HttpStatusCode code = ((HttpWebResponse) wex.Response).StatusCode;
                            if (code != HttpStatusCode.InternalServerError &&
                                code != HttpStatusCode.BadGateway &&
                                code != HttpStatusCode.ServiceUnavailable &&
                                code != HttpStatusCode.GatewayTimeout &&
                                code != HttpStatusCode.RequestTimeout)
                            {
                                Logger.Instance.Write(bot, "Failed: {0}", wex.Message);
                                return;
                            }

                            Logger.Instance.Write(bot, "Failed: {0} (next retry in 5 seconds) [{1}]", wex.Message,
                                3 - retry + 1);
                            Thread.Sleep(5000);
                        }
                    } while (retry-- > 0);
                }
                catch (Exception ex)
                {
                    DebugHelper.Write(bot, "BuddyAuth session killer failed!");
                    DebugHelper.Exception(ex);
                    return;
                }
                Logger.Instance.Write(bot, "BuddyAuth: No session found.");
            }
        }
        // Dont link this list
        public static void Create(BotClass bot)
        {
            var imp = new Impersonator();
            try
            {
                if (bot.UseWindowsUser)
                    imp.Impersonate(bot.WindowsUserName, "localhost", bot.WindowsUserPassword);

                bot.Status = "Create Diablo Clone";
                string basepath = Path.GetDirectoryName(bot.Diablo.Location);
                string clonepath = Path.Combine(bot.DiabloCloneLocation, "Diablo III");

                // if diablo base path does not exist stop here!
                if (basepath != null && !Directory.Exists(basepath))
                {
                    bot.Stop();
                    throw new Exception("Diablo base directory does not exist!");
                }

                // Check if given language is installed on basepath
                string testpath = Path.Combine(basepath, @"Data_D3\PC\MPQs", General.GetLocale(bot.Diablo.Language));
                if (!Directory.Exists(testpath))
                {
                    bot.Stop();
                    throw new Exception(string.Format("ERROR: {0} language is not installed (path: {1})",
                        bot.Diablo.Language, testpath));
                }

                // if diablo clone does not exist create it
                if (!Directory.Exists(Path.Combine(clonepath, @"Data_D3\PC\MPQs\Cache")))
                {
                    Logger.Instance.Write(bot, "Creating new Diablo Clone");
                    Directory.CreateDirectory(Path.Combine(clonepath, @"Data_D3\PC\MPQs\Cache"));
                }

                // Create Search caches
                var baseFileCache = new FileListCache(basepath);
                var cloneFileCache = new FileListCache(clonepath);

                // Check if all links are made for our clone
                foreach (FileListCache.MyFile p in baseFileCache.FileList)
                {
                    try
                    {
                        if (p.directory && !Directory.Exists(Path.Combine(clonepath.ToLower(), p.Path.ToLower())))
                        {
                            if (!_noLinks.Any(n => General.WildcardMatch(n.Source, p.Path)))
                            {
                                Logger.Instance.Write(bot, "NewLink: {0} -> {1}", Path.Combine(clonepath, p.Path),
                                    Path.Combine(basepath, p.Path));
                                //if (!CreateSymbolicLink( Path.Combine(clonepath,p.Path),  Path.Combine(basepath,p.Path), 1))
                                //  throw new Exception("Failed to create link!");
                                Directory.CreateDirectory(Path.Combine(clonepath, p.Path));
                            }
                            continue;
                        }
                        if (!p.directory && !File.Exists(Path.Combine(clonepath.ToLower(), p.Path.ToLower())))
                        {
                            if (!_noLinks.Any(n => General.WildcardMatch(n.Source, p.Path)))
                            {
                                Logger.Instance.Write(bot, "NewLink: {0} -> {1}", Path.Combine(clonepath, p.Path),
                                    Path.Combine(basepath, p.Path));
                                if (Path.GetExtension(Path.Combine(clonepath, p.Path)).ToLower().Equals(".exe"))
                                {
                                    if (
                                        !CreateHardLink(Path.Combine(clonepath, p.Path), Path.Combine(basepath, p.Path),
                                            IntPtr.Zero))
                                        throw new Exception("Failed to create link!");
                                }
                                else
                                {
                                    if (
                                        !CreateSymbolicLink(Path.Combine(clonepath, p.Path),
                                            Path.Combine(basepath, p.Path), 0))
                                        throw new Exception("Failed to create link!");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }

                // Remove links that have no target
                /*
                foreach (var p in cloneFileCache.FileList)
                {
                    try
                    {
                        if (p.directory && !Directory.Exists(Path.Combine(basepath, p.Path)))
                        {
                            if (!_noLinks.Any(n => General.WildcardMatch(n.Source.ToLower(), p.Path.ToLower())))
                                Console.WriteLine("Delete: {0}", p.Path);
                            continue;
                        }

                        if (!p.directory && !File.Exists(Path.Combine(basepath.ToLower(), p.Path.ToLower())))
                        {
                            if (!_noLinks.Any(n => General.WildcardMatch(n.Source, p.Path)))
                                Console.WriteLine("Delete: {0}", p.Path);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.Write(bot, ex.ToString());
                    }
                }
                 */
            }
            catch (Exception ex)
            {
                bot.Stop();
                DebugHelper.Write(bot, "Failed to create clone!");
                DebugHelper.Exception(ex);
            }
            imp.Dispose();
        }
Exemple #38
0
        public static void ManualPositionWindow(IntPtr handle, int x, int y, int w, int h, BotClass bot = null)
        {
            // Set window position and size
            try
            {
                WinAPI.RECT rct;
                if (WinAPI.GetWindowRect(new HandleRef(bot, handle), out rct))
                {
                    if (w <= 0)
                    {
                        w = rct.Width;
                    }
                    if (h <= 0)
                    {
                        h = rct.Heigth;
                    }

                    Logger.Instance.Write(bot, "ManualPosition window:{0}: X:{1} Y:{2} W:{3} H:{4}", handle, x, y, w, h);
                    if (!WinAPI.SetWindowPos(handle, IntPtr.Zero, x, y, w, h, WinAPI.SetWindowPosFlags.SWP_NOACTIVATE | WinAPI.SetWindowPosFlags.SWP_NOSENDCHANGING))
                    {
                        Logger.Instance.Write(bot, "ManualPosition window:{0}: Failed!", handle);
                    }
                }
                else
                {
                    Logger.Instance.Write(bot, "ManualPosition Failed to get window rectangle");
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.Write(bot, "ManualPosition Error: " + ex);
            }
        }
Exemple #39
0
        private void ReloggerWorker()
        {
            // Check if we are launched by windows RUN
            if (CommandLineArgs.WindowsAutoStart && !_autoStartDone)
            {
                _autoStartDone = true;
                Logger.Instance.WriteGlobal("Windows auto start delaying with {0} seconds", Settings.Default.StartDelay);
                Thread.Sleep((int)Settings.Default.StartDelay * 1000);
                foreach (var bot in BotSettings.Instance.Bots.Where(c => c.IsEnabled))
                {
                    bot.AntiIdle.Reset(freshstart: true); // Reset AntiIdle
                    bot.IsStarted = true;
                    bot.Status    = "Auto Start...";
                }
            }
            // Check if we are launched with the autostart
            if (CommandLineArgs.AutoStart && !_autoStartDone)
            {
                _autoStartDone = true;
                foreach (var bot in BotSettings.Instance.Bots.Where(c => c.IsEnabled))
                {
                    bot.AntiIdle.Reset(freshstart: true); // Reset AntiIdle
                    bot.IsStarted = true;
                    bot.Status    = "Auto Start...";
                }
            }

            Logger.Instance.WriteGlobal("Relogger Thread Starting!");
            while (true)
            {
                try
                {
                    // Paused
                    if (Program.Pause)
                    {
                        Thread.Sleep(1000);
                        continue;
                    }
                    // Check / validate internet connection
                    if (!ConnectionCheck.IsConnected || !ConnectionCheck.ValidConnection)
                    {
                        Debug.WriteLine("Internet validation failed looping until success");
                        Thread.Sleep(1000);
                        continue;
                    }

                    foreach (var bot in BotSettings.Instance.Bots.Where(bot => bot != null))
                    {
                        if (Program.Pause)
                        {
                            break;
                        }

                        var time = DateTime.Now; // set current time to calculate sleep time at end of loop
                        CurrentBot = bot;
                        //Debug.WriteLine(bot.Name + ":" + ":" + bot.IsRunning);
                        //Debug.WriteLine("State=" + bot.AntiIdle.State);
                        if (bot.IsRunning && bot.IsStarted && !bot.Week.ShouldRun(bot.IsRunning))
                        {
                            // We need to stop
                            Logger.Instance.Write("We are scheduled to stop");
                            bot.Week.NextSchedule(true);
                            bot.IsRunning = false;
                            bot.Diablo.Stop();
                            bot.Demonbuddy.Stop();
                            bot.Status = "Scheduled stop!";
                        }
                        else if (!bot.IsRunning && bot.IsStarted && bot.Week.ShouldRun(bot.IsRunning))
                        {
                            // we need to start
                            Logger.Instance.Write("We are scheduled to start");
                            bot.Week.NextSchedule(false);
                            bot.IsRunning = true;
                            bot.StartTime = DateTime.Now;
                            StartBoth(bot);
                        }
                        else if (!bot.IsStandby && bot.IsRunning)
                        {
                            // Check if process is responding
                            bot.Diablo.CrashCheck();
                            if (bot.AntiIdle.IsInitialized)
                            {
                                bot.Demonbuddy.CrashCheck();
                            }

                            if (!bot.Diablo.IsRunning)
                            {
                                Logger.Instance.Write("Diablo:{0}: Process is not running", bot.Diablo.Proc.Id);
                                if (bot.Demonbuddy.IsRunning)
                                {
                                    Logger.Instance.Write("Demonbuddy:{0}: Closing db", bot.Demonbuddy.Proc.Id);
                                    bot.Demonbuddy.Stop();
                                }
                                StartBoth(bot);
                            }
                            else if (!bot.Demonbuddy.IsRunning)
                            {
                                Logger.Instance.Write("Demonbuddy:{0}: Process is not running", bot.Demonbuddy.Proc.Id);
                                bot.Demonbuddy.Start();
                            }
                            else if (bot.AntiIdle.State != IdleState.Initialize && General.DateSubtract(bot.AntiIdle.LastStats) > 120)
                            {
                                Logger.Instance.Write("We did not recieve any stats during 120 seconds!");
                                bot.Restart();
                            }
                            else if (bot.AntiIdle.IsInitialized)
                            {
                                if (bot.ProfileSchedule.IsDone)
                                {
                                    Logger.Instance.Write("Profile: \"{0}\" Finished!", bot.ProfileSchedule.Current.Name);
                                    bot.AntiIdle.State = IdleState.NewProfile;
                                }
                            }
                        } // else if (bot.isRunning)
                        else
                        {
                            bot.StartTime = DateTime.Now;
                        }

                        // calculate sleeptime
                        var sleep = (int)(Program.Sleeptime - DateTime.Now.Subtract(time).TotalMilliseconds);
                        if (sleep > 0)
                        {
                            Thread.Sleep(sleep);
                        }
                    }
                } // try
                catch (InvalidOperationException iox)
                { // Catch error when bot is edited while in a loop
                    //Logger.Instance.WriteGlobal(iox.Message);
                    continue;
                }
                catch (Exception ex)
                {
                    if (_isStopped)
                    {
                        return;
                    }
                    Logger.Instance.WriteGlobal("Relogger Crashed! with message {0}", ex.Message);
                    Logger.Instance.WriteGlobal(ex.StackTrace);
                    Logger.Instance.WriteGlobal("Waiting 10 seconds and try again!");
                    Thread.Sleep(10000);
                    continue;
                }
                Thread.Sleep(1000);
            } // while
        }     // private void reloggerWorker()
        private bool StartBoth(BotClass bot)
        {
            bot.Diablo.Start();
            if (!bot.Diablo.IsRunning)
                return false;

            bot.Demonbuddy.Start();
            if (!bot.Demonbuddy.IsRunning)
                return false;

            bot.Status = "Monitoring";
            return true;
        }
Exemple #41
0
        private void button1_Click(object sender, EventArgs e)
        {
            // NEXT / finish
            if (_stepCount == FinishCount)
            {
                int result;
                var b  = new BotClass();
                var db = new DemonbuddyClass();
                var d  = new DiabloClass();
                var ps = new ProfileScheduleClass();
                var w  = new Helpers.Bot.WeekSchedule();


                b.Name        = _ucDemonbuddy.textBox1.Text;
                b.Description = _ucDemonbuddy.textBox2.Text;

                // Advanced
                b.CreateWindowsUser   = _ucAdvanced.checkBox2.Checked;
                b.UseWindowsUser      = _ucAdvanced.checkBox1.Checked;
                b.WindowsUserName     = _ucAdvanced.textBox1.Text;
                b.WindowsUserPassword = _ucAdvanced.maskedTextBox1.Text;
                b.D3PrefsLocation     = _ucAdvanced.textBox3.Text;
                b.UseDiabloClone      = _ucAdvanced.checkBox3.Checked;
                b.DiabloCloneLocation = _ucAdvanced.textBox2.Text;

                // Demonbuddy
                db.Location      = _ucDemonbuddy.textBox4.Text;
                db.Key           = _ucDemonbuddy.textBox3.Text;
                db.CombatRoutine = _ucDemonbuddy.comboBox1.SelectedItem != null
                    ? _ucDemonbuddy.comboBox1.SelectedItem.ToString()
                    : _ucDemonbuddy.comboBox1.Text;

                db.NoFlash               = _ucDemonbuddy.checkBox1.Checked;
                db.AutoUpdate            = _ucDemonbuddy.checkBox2.Checked;
                db.NoUpdate              = _ucDemonbuddy.checkBox3.Checked;
                db.BuddyAuthUsername     = _ucDemonbuddy.textBox9.Text;
                db.BuddyAuthPassword     = _ucDemonbuddy.maskedTextBox2.Text;
                db.Priority              = _ucDemonbuddy.comboBox2.SelectedIndex;
                db.ForceEnableAllPlugins = _ucDemonbuddy.checkBox5.Checked;


                db.ManualPosSize = _ucDemonbuddy.checkBox4.Checked;
                int.TryParse(_ucDemonbuddy.textBox6.Text, out result);
                db.X = result;
                int.TryParse(_ucDemonbuddy.textBox5.Text, out result);
                db.Y = result;
                int.TryParse(_ucDemonbuddy.textBox10.Text, out result);
                db.W = result;
                int.TryParse(_ucDemonbuddy.textBox11.Text, out result);
                db.H = result;

                // Diablo
                d.Username         = _ucDiablo.textBox3.Text;
                d.Password         = _ucDiablo.maskedTextBox1.Text;
                d.Location         = _ucDiablo.textBox1.Text;
                d.Language         = _ucDiablo.comboBox1.SelectedItem.ToString();
                d.Region           = _ucDiablo.comboBox2.SelectedItem.ToString();
                d.UseAuthenticator = _ucDiablo.checkBox1.Checked;
                d.Serial           = string.Format("{0}-{1}-{2}-{3}", _ucDiablo.textBox4.Text, _ucDiablo.textBox5.Text,
                                                   _ucDiablo.textBox7.Text, _ucDiablo.textBox6.Text);
                d.RestoreCode  = _ucDiablo.textBox8.Text;
                d.Priority     = _ucDiablo.comboBox3.SelectedIndex;
                d.UseIsBoxer   = _ucDiablo.checkBox2.Checked;
                d.CharacterSet = _ucDiablo.textBox13.Text;
                d.DisplaySlot  = _ucDiablo.textBox12.Text;
                d.NoFrame      = _ucDiablo.checkBox4.Checked;

                // Affinity Diablo
                if (d.CpuCount != Environment.ProcessorCount)
                {
                    d.ProcessorAffinity = d.AllProcessors;
                    d.CpuCount          = Environment.ProcessorCount;
                }

                if (AffinityDiablo.cpus.Count != d.CpuCount)
                {
                    Logger.Instance.Write(
                        "For whatever reason Diablo and UI see different number of CPUs, affinity disabled");
                }
                else
                {
                    int intProcessorAffinity = 0;
                    for (int i = 0; i < d.CpuCount; i++)
                    {
                        if (AffinityDiablo.cpus[i].Checked)
                        {
                            intProcessorAffinity |= (1 << i);
                        }
                    }
                    if (intProcessorAffinity == 0)
                    {
                        intProcessorAffinity = -1;
                    }
                    d.ProcessorAffinity = intProcessorAffinity;
                }
                if (AffinityDiablo != null)
                {
                    AffinityDiablo.Dispose();
                }

                // Affinity Demonbuddy
                if (db.CpuCount != Environment.ProcessorCount)
                {
                    db.ProcessorAffinity = db.AllProcessors;
                    db.CpuCount          = Environment.ProcessorCount;
                }

                if (AffinityDemonbuddy.cpus.Count != db.CpuCount)
                {
                    Logger.Instance.Write(
                        "For whatever reason Demonbuddy and UI see different number of CPUs, affinity disabled");
                }
                else
                {
                    int intProcessorAffinity = 0;
                    for (int i = 0; i < db.CpuCount; i++)
                    {
                        if (AffinityDemonbuddy.cpus[i].Checked)
                        {
                            intProcessorAffinity |= (1 << i);
                        }
                    }
                    if (intProcessorAffinity == 0)
                    {
                        intProcessorAffinity = -1;
                    }
                    db.ProcessorAffinity = intProcessorAffinity;
                }
                if (AffinityDemonbuddy != null)
                {
                    AffinityDemonbuddy.Dispose();
                }

                d.ManualPosSize = _ucDiablo.checkBox3.Checked;
                int.TryParse(_ucDiablo.textBox2.Text, out result);
                d.X = result;
                int.TryParse(_ucDiablo.textBox9.Text, out result);
                d.Y = result;
                int.TryParse(_ucDiablo.textBox10.Text, out result);
                d.W = result;
                int.TryParse(_ucDiablo.textBox11.Text, out result);
                d.H = result;

                w.GenerateNewSchedule();
                w.Shuffle   = _ucWeekSchedule.checkBox1.Checked;
                w.MinRandom = Convert.ToInt32(_ucWeekSchedule.textBox1.Text);
                w.MaxRandom = Convert.ToInt32(_ucWeekSchedule.textBox2.Text);

                ps.Profiles      = _ucProfileSchedule.Profiles;
                ps.MaxRandomTime = Convert.ToInt32(_ucProfileSchedule.textBox1.Text);
                ps.MaxRandomRuns = Convert.ToInt32(_ucProfileSchedule.textBox2.Text);
                ps.Random        = _ucProfileSchedule.checkBox1.Checked;

                b.Week            = w;
                b.Demonbuddy      = db;
                b.Diablo          = d;
                b.ProfileSchedule = ps;


                if (bot != null && index >= 0)
                {
                    Logger.Instance.WriteGlobal("Editing bot: {0}", b.Name);

                    // Copy some important stuff from old bot

                    b.IsStarted                   = BotSettings.Instance.Bots[index].IsStarted;
                    b.IsEnabled                   = BotSettings.Instance.Bots[index].IsEnabled;
                    b.IsRunning                   = BotSettings.Instance.Bots[index].IsRunning;
                    b.Diablo.Proc                 = BotSettings.Instance.Bots[index].Diablo.Proc;
                    b.Demonbuddy.Proc             = BotSettings.Instance.Bots[index].Demonbuddy.Proc;
                    b.Demonbuddy.MainWindowHandle = BotSettings.Instance.Bots[index].Demonbuddy.MainWindowHandle;
                    b.Diablo.MainWindowHandle     = BotSettings.Instance.Bots[index].Diablo.MainWindowHandle;
                    b.AntiIdle        = BotSettings.Instance.Bots[index].AntiIdle;
                    b.Week.ForceStart = BotSettings.Instance.Bots[index].Week.ForceStart;
                    b.RunningTime     = BotSettings.Instance.Bots[index].RunningTime;

                    BotSettings.Instance.Bots[index] = b;
                }
                else
                {
                    Logger.Instance.WriteGlobal("Adding new bot: {0}", b.Name);
                    BotSettings.Instance.Bots.Add(b);
                }

                BotSettings.Instance.Save();
                shouldClose = true;
                ActiveForm.Close();

                BotSettings.Instance.Save();
                Program.Mainform.UpdateGridView();
                return;
            }

            if (ValidateControl(Controls[_stepCount]))
            {
                Controls[_stepCount].Visible = false; // Hide old
                _stepCount++;
                Controls[_stepCount].Visible = true;  // Show new
            }

            if (_stepCount > _mainCount)
            {
                button2.Enabled = true;
            }
            if (_stepCount == FinishCount)
            {
                button1.Text = "Save!";
            }
        }
        private void CreateChartStats(BotClass bot, Chart graph, ChartValueType valueType = ChartValueType.Auto)
        {
            if (Program.Mainform != null && graph != null)
            {
                try
                {
                    Program.Mainform.Invoke(new Action(() =>
                    {
                        try
                        {
                            if (bot.IsRunning)
                            {
                                Series serie = graph.Series.FirstOrDefault(x => x.Name == bot.Name);
                                if (serie == null)
                                {
                                    // Add Series
                                    graph.Series.Add(bot.Name);
                                    graph.Series[bot.Name].ChartType = SeriesChartType.FastLine;
                                    graph.Series[bot.Name].Points.Add(0);
                                    graph.Series[bot.Name].YAxisType = AxisType.Primary;
                                    graph.Series[bot.Name].YValueType = valueType;
                                    graph.Series[bot.Name].IsXValueIndexed = false;

                                    graph.Series[bot.Name].Color = Color.Black;
                                    foreach (
                                        Color color in
                                            ChartColors.Where(color => graph.Series.All(x => x.Color != color))
                                        )
                                        graph.Series[bot.Name].Color = color;
                                    graph.Series[bot.Name].Name = bot.Name;
                                }
                            }
                            else
                            {
                                Series serie = graph.Series.FirstOrDefault(x => x.Name == bot.Name);
                                if (serie != null)
                                    graph.Series.Remove(serie);
                            }
                        }
                        catch (Exception ex)
                        {
                            DebugHelper.Exception(ex);
                        }
                    }));
                }
                catch (Exception ex)
                {
                    DebugHelper.Exception(ex);
                }
            }
        }
Exemple #43
0
 public WizardMain(int index)
 {
     this.index = index;
     bot        = BotSettings.Instance.Bots[index];
     InitializeComponent();
 }
Exemple #44
0
        private void ReloggerWorker()
        {
            // Check if we are launched by windows RUN
            if (CommandLineArgs.WindowsAutoStart && !_autoStartDone)
            {
                _autoStartDone = true;
                Logger.Instance.WriteGlobal("Windows auto start delaying with {0} seconds", Settings.Default.StartDelay);
                Thread.Sleep((int)Settings.Default.StartDelay * 1000);
                foreach (BotClass bot in BotSettings.Instance.Bots.Where(c => c.IsEnabled))
                {
                    bot.AntiIdle.Reset(freshstart: true); // Reset AntiIdle
                    bot.IsStarted = true;
                    bot.Status    = "Auto Start...";
                }
            }
            // Check if we are launched with the autostart
            if (CommandLineArgs.AutoStart && !_autoStartDone)
            {
                _autoStartDone = true;
                foreach (BotClass bot in BotSettings.Instance.Bots.Where(c => c.IsEnabled))
                {
                    bot.AntiIdle.Reset(freshstart: true); // Reset AntiIdle
                    bot.IsStarted = true;
                    bot.Status    = "Auto Start...";
                }
            }

            DebugHelper.Write("Relogger Thread Starting!");
            while (true)
            {
                try
                {
                    if (_isStopped)
                    {
                        return;
                    }

                    // Paused
                    if (Program.Pause)
                    {
                        Thread.Sleep(1000);
                        continue;
                    }

                    List <Process> blizzardErrorProcs =
                        (from p in Process.GetProcessesByName("BlizzardError.exe")
                         select p).ToList();
                    if (blizzardErrorProcs.Any())
                    {
                        try
                        {
                            foreach (var p in blizzardErrorProcs)
                            {
                                Logger.Instance.Write("Killing BlizzardError.exe with PID {0}", p.Id);
                                p.Kill();
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Instance.Write("Exception killing BlizzardError.exe: " + ex);
                        }
                    }

                    if (DateTime.UtcNow.Subtract(_lastSaveSettings).TotalSeconds > 10)
                    {
                        _lastSaveSettings = DateTime.UtcNow;
                        Settings.Default.Save();
                        BotSettings.Instance.Save();
                    }

                    // Check / validate internet connection
                    if (!ConnectionCheck.IsConnected || !ConnectionCheck.ValidConnection)
                    {
                        Debug.WriteLine("Internet validation failed looping until success");
                        Thread.Sleep(1000);
                        continue;
                    }

                    foreach (BotClass bot in BotSettings.Instance.Bots.Where(bot => bot != null).ToList())
                    {
                        if (Program.Pause)
                        {
                            break;
                        }

                        DateTime time = DateTime.UtcNow; // set current time to calculate sleep time at end of loop
                        CurrentBot = bot;
                        //Debug.WriteLine(bot.Name + ":" + ":" + bot.IsRunning);
                        //Debug.WriteLine("State=" + bot.AntiIdle.State);
                        if (bot.IsRunning && bot.IsStarted && !bot.Week.ShouldRun(bot.IsRunning))
                        {
                            // We need to stop
                            Logger.Instance.Write("We are scheduled to stop");
                            bot.Week.NextSchedule(true);
                            bot.IsRunning = false;
                            bot.Demonbuddy.Stop();
                            bot.Diablo.Stop();
                            bot.Status = "Scheduled stop!";
                        }
                        else if (!bot.IsRunning && bot.IsStarted && bot.Week.ShouldRun(bot.IsRunning))
                        {
                            // we need to start
                            Logger.Instance.Write("We are scheduled to start");
                            bot.Week.NextSchedule(false);
                            bot.IsRunning = true;
                            bot.StartTime = DateTime.UtcNow;
                            StartBoth(bot);
                        }
                        else if (!bot.IsStandby && bot.IsRunning)
                        {
                            // Check if process is responding
                            bot.Diablo.CrashCheck();
                            if (bot.AntiIdle.IsInitialized)
                            {
                                bot.Demonbuddy.CrashCheck();
                            }

                            if (!bot.Diablo.IsRunning)
                            {
                                if (bot.Diablo.Proc != null)
                                {
                                    Logger.Instance.Write("Diablo:{0}: Process is not running", bot.Diablo.Proc.Id);
                                }
                                //if (bot.Demonbuddy.IsRunning && bot.Demonbuddy.Proc != null)
                                //{
                                //    Logger.Instance.Write("Demonbuddy:{0}: Closing db", bot.Demonbuddy.Proc.Id);
                                //    bot.Demonbuddy.Stop();
                                //}
                                if (bot.Demonbuddy.IsRunning && bot.Demonbuddy.Proc != null)
                                {
                                    Logger.Instance.Write("Demonbuddy:{0}: Waiting for Demonbuddy to self close", bot.Demonbuddy.Proc.Id);
                                }
                                else
                                {
                                    StartBoth(bot);
                                }
                            }
                            else if (!bot.Demonbuddy.IsRunning)
                            {
                                Logger.Instance.Write("Demonbuddy: Process is not running");
                                bot.Demonbuddy.Start();
                            }
                            else if (Settings.Default.AntiIdleStatsDuration > 0 && bot.AntiIdle.State != IdleState.Initialize && General.DateSubtract(bot.AntiIdle.LastStats) >
                                     (double)Settings.Default.AntiIdleStatsDuration)
                            {
                                Logger.Instance.Write("We did not recieve any stats during 300 seconds!");
                                bot.Restart();
                            }
                            else if (bot.AntiIdle.IsInitialized)
                            {
                                if (bot.ProfileSchedule.IsDone)
                                {
                                    Logger.Instance.Write("Profile: \"{0}\" Finished!", bot.ProfileSchedule.Current.Name);
                                    bot.AntiIdle.State = IdleState.NewProfile;
                                }
                            }
                        }
                        else
                        {
                            //Logger.Instance.Write("Bot Standby={0} Running={1} D3Running={2} DBRunning={3}", bot.IsStandby, bot.IsRunning, bot.Diablo.IsRunning, bot.Demonbuddy.IsRunning);
                            bot.StartTime = DateTime.UtcNow;
                        }
                        // calculate sleeptime
                        var sleep = (int)(Program.Sleeptime - DateTime.UtcNow.Subtract(time).TotalMilliseconds);
                        if (sleep > 0)
                        {
                            Thread.Sleep(sleep);
                        }
                    }
                } // try
                catch (InvalidOperationException)
                {
                    // Catch error when bot is edited while in a loop
                    //Logger.Instance.WriteGlobal(iox.Message);
                    continue;
                }
                catch (Exception ex)
                {
                    if (_isStopped)
                    {
                        return;
                    }
                    Logger.Instance.WriteGlobal("Relogger Crashed! with message {0}", ex.Message);
                    DebugHelper.Exception(ex);
                    Logger.Instance.WriteGlobal("Waiting 10 seconds and try again!");
                    Thread.Sleep(10000);
                    continue;
                }
                Thread.Sleep(1000);
            } // while
        }     // private void reloggerWorker()
Exemple #45
0
        public static ProcessStartInfo ImpersonateStartInfo(ProcessStartInfo startinfo, BotClass bot)
        {
            if (bot.UseWindowsUser)
            {
                if (!ExistsAsAdmin(bot.WindowsUserName))
                {
                    if (bot.CreateWindowsUser)
                    {
                        Create(bot.WindowsUserName, bot.WindowsUserPassword, isAdmin: true);
                    }
                    else
                    {
                        Logger.Instance.Write("User Account \"{0}\" does not exist and we are not allowed to create it", bot.WindowsUserName);
                        bot.Stop();
                        return(startinfo);
                    }
                }

                startinfo.UserName = bot.WindowsUserName;
                var encPassword = new SecureString();
                foreach (var c in bot.WindowsUserPassword)
                {
                    encPassword.AppendChar(c);
                }
                startinfo.Password        = encPassword;
                startinfo.UseShellExecute = false;
            }
            return(startinfo);
        }