Ejemplo n.º 1
0
        public void OnDisabled()
        {
            Logr.Log("Plugin disabled! ");
            Enabled = false;

            BotMain.OnStart                   -= BotMain_OnStart;
            BotMain.OnStop                    -= BotMain_OnStop;
            GameEvents.OnGameLeft             -= GameEvents_OnGameLeft;
            GameEvents.OnGameJoined           -= GameEvents_OnGameJoined;
            GameEvents.OnWorldTransferStart   -= GameEvents_OnWorldTransferStart;
            GameEvents.OnWorldChanged         -= GameEvents_OnWorldChanged;
            TreeHooks.Instance.OnHooksCleared -= OnHooksCleared;

            ServiceBase.Initialized = false;
            SharedComposites.CheckReplaceOutOfGameHook();

            try
            {
                if (ServiceBase.Host != null)
                {
                    ServiceBase.Host.Close();
                }
            }
            catch
            {
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Replaces the bot behavior.
        /// </summary>
        internal static void ReplaceBotBehavior()
        {
            if (!Plugin.Enabled)
            {
                Logr.Log("Plugin not enabled - restoring original BotBehavior");
                RestoreOriginalBotBehavior();
                return;
            }
            if (SimpleFollow.IsFollower)
            {
                return;
            }

            const string hookName = "BotBehavior";

            if (!TreeHooks.Instance.Hooks.ContainsKey(hookName))
            {
                return;
            }

            if (_originalBotBehavior == null)
            {
                _originalBotBehavior = TreeHooks.Instance.Hooks[hookName];
            }

            _leaderBehavior = CreateBehavior();

            Logr.Log("Inserting into BotBehavior hook");
            TreeHooks.Instance.Hooks[hookName].Insert(0, _leaderBehavior);
            _hookReplaced = true;
        }
Ejemplo n.º 3
0
        private static bool ClickTimerRandomNotReady()
        {
            long timeRemaining = clickTimerRandomVal - clickTimer.ElapsedMilliseconds;

            Logr.Log("Pausing bot -  waiting for button timer {0}ms", clickTimerRandomVal);
            return(clickTimer.IsRunning && clickTimer.ElapsedMilliseconds < clickTimerRandomVal);
        }
Ejemplo n.º 4
0
        private static void StartServer()
        {
            try
            {
                var bindAddress = Settings.Instance.BindAddress;
                var serverPort  = Settings.Instance.ServerPort;

                IPGlobalProperties igp = IPGlobalProperties.GetIPGlobalProperties();
                bool isAvailable       =
                    igp.GetActiveTcpConnections().All(tcpi => tcpi.LocalEndPoint.Port != serverPort) &&
                    igp.GetActiveTcpListeners().All(l => l.Port != serverPort);

                // At this point, if isAvailable is true, we can proceed accordingly.
                if (isAvailable)
                {
                    ServerUri = new Uri("http://" + bindAddress + ":" + serverPort);

                    Logr.Log("Initializing Server Service @ {0}", ServerUri.AbsoluteUri);
                    Host = new ServiceHost(typeof(Server), new[] { ServerUri });
                    Host.AddServiceEndpoint(typeof(IFollowService), new BasicHttpBinding(), "Follow");
                    Host.Open();
                    Leader = Message.GetMessage();
                }
            }
            catch (Exception ex)
            {
                Logr.Log("ERROR: Could not initialize follow service. Do you already have a leader started?");
                Logr.Log(ex.ToString());

                Logr.Log("Disabling Plugin and Resetting Game Creation Wait Timers to default");
                Plugin.DisablePlugin();
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Initializes the Follower connection to the Leader
        /// </summary>
        private static void StartClient()
        {
            try
            {
                if (!Initialized && Enabled)
                {
                    int serverPort = Settings.Instance.ServerPort;
                    ServerUri = new Uri(ServerUri.AbsoluteUri.Replace(BasePort.ToString(), serverPort.ToString()));

                    SharedComposites.CheckReplaceOutOfGameHook();

                    Logr.Log("Initializing Client Service connection to {0}", ServerUri.AbsoluteUri + "Follow");

                    BasicHttpBinding binding = new BasicHttpBinding
                    {
                        OpenTimeout  = TimeSpan.FromMilliseconds(5000),
                        SendTimeout  = TimeSpan.FromMilliseconds(5000),
                        CloseTimeout = TimeSpan.FromMilliseconds(5000)
                    };

                    EndpointAddress endPointAddress = new EndpointAddress(ServerUri.AbsoluteUri + "Follow");

                    HttpFactory = new ChannelFactory <IFollowService>(binding, endPointAddress);

                    HttpProxy = HttpFactory.CreateChannel();

                    Initialized = true;
                }
            }
            catch (Exception ex)
            {
                Logr.Log("Exception in ClientInitialize() {0}", ex);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// This is a thread running on the leader bot to watch the current profile behavior, to speed up followers going to the right place at the right time
        /// </summary>
        internal static void BehaviorWatcher()
        {
            try
            {
                if (Enabled && !IsFollower)
                {
                    ProfileBehavior currentBehavior = ProfileManager.CurrentProfileBehavior;
                    if (currentBehavior != null)
                    {
                        if (currentBehavior.GetType().Name.ToLower().Contains("town"))
                        {
                            Leader.IsInTown = true;
                        }
                        if (currentBehavior.GetType().Name.ToLower().Contains("leavegame"))
                        {
                            Leader.IsInGame = false;
                        }

                        // The profile position for look-ahead
                        Leader.ProfilePosition = Message.GetProfilePosition();
                        Leader.ProfileActorSNO = Message.GetProfileActorSNO();
                    }

                    if (BrainBehavior.IsVendoring)
                    {
                        Leader.IsInTown = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Logr.Log("Exception in BehaviorWatcher: {0}", ex);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Leader Out Of Game Coroutine
        /// </summary>
        /// <param name="children">The children.</param>
        /// <returns>Task&lt;System.Boolean&gt;.</returns>
        internal static async Task <bool> LeaderOutOfGameTask()
        {
            LeaderService.LeaderOutOfGameUpdate();
            SimpleFollow.Pulse();

            // Some safety checks
            if (ZetaDia.IsInGame)
            {
                return(true);
            }

            if (ZetaDia.IsLoadingWorld)
            {
                return(true);
            }

            if (!ZetaDia.Service.Hero.IsValid)
            {
                return(true);
            }

            if (!ZetaDia.Service.Platform.IsConnected)
            {
                return(true);
            }

            if (!ZetaDia.Service.IsValid || !ZetaDia.Service.Hero.IsValid)
            {
                return(true);
            }

            // In Party but no followers connected - just wait!
            if (Settings.Instance.WaitForFollowers && Social.IsInParty && Social.IsPartyleader && Social.NumPartyMembers - 1 != SimpleFollow.Followers.Count)
            {
                Logr.Log("Waiting for followers to connect to SimpleFollow server...");
                return(false);
            }
            if (!Social.IsPartyleader)
            {
                Logr.Log("Waiting to become party leader...");
                return(false);
            }

            if (!SimpleFollow.Followers.Any())
            {
                return(true);
            }

            var followersInGame = SimpleFollow.Followers.Where(f => DateTime.UtcNow.Subtract(f.Value.LastTimeInGame).TotalSeconds < 10).ToList();

            if (Social.IsInParty && followersInGame.Any() && !GameUI.PlayGameButton.IsEnabled)
            {
                Logr.Log("Waiting for {0} followers to leave game...", followersInGame.Count());
                await Coroutine.Sleep(500);

                return(false);
            }

            return(true);
        }
Ejemplo n.º 8
0
 internal static void LeaderOutOfGameUpdate()
 {
     Leader = Message.GetMessage();
     if (Settings.Instance.DebugLogging)
     {
         Logr.Debug("Leader OutOfGame: {0}", Leader);
     }
 }
Ejemplo n.º 9
0
        private const int RiftPortalSNO = 345935; // X1_OpenWorld_LootRunPortal

        internal static bool ShouldFollowerOpenRift()
        {
            if (Player.IsGreaterRiftStarted)
            {
                return(false);
            }

            if (ZetaDia.WorldType != Act.OpenWorld)
            {
                return(false);
            }

            if (SimpleFollow.IsLeader)
            {
                // Current profile tag must be OpenRift / QTOpenRiftWrapper
                var currentBehavior = ProfileManager.CurrentProfileBehavior;
                if (currentBehavior != null && !currentBehavior.GetType().Name.Contains("OpenRift"))
                {
                    return(false);
                }

                if (!SimpleFollow.Followers.Any())
                {
                    return(false);
                }

                if (!SimpleFollow.Followers.Any(f => f.Value.HasRiftKeys))
                {
                    return(false);
                }
            }

            // In regular rift quests
            if (ConditionParser.IsActiveQuestAndStep(337492, 1) ||
                ConditionParser.IsActiveQuestAndStep(337492, 3) ||
                ConditionParser.IsActiveQuestAndStep(337492, 13) ||
                ConditionParser.IsActiveQuestAndStep(337492, 16))
            {
                return(false);
            }

            var portals = ZetaDia.Actors.GetActorsOfType <GizmoPortal>(true).Where(p => p.ActorSNO == RiftPortalSNO).ToList();

            if (portals.Any())
            {
                return(false);
            }

            var allFollowersConnected = SimpleFollow.Followers.Count == Social.NumPartyMembers - 1;

            Logr.Debug("Follower Count={0}, NumPartyMembers={1}", SimpleFollow.Followers.Count, Social.NumPartyMembers);
            Logr.Debug("HighestTeamRiftKey={0} HighestLevelTieredRiftKey={1}", SimpleFollow.Leader.HighestTeamRiftKey, SimpleFollow.Leader.HighestLevelTieredRiftKey);

            var result = allFollowersConnected && SimpleFollow.Leader.HighestTeamRiftKey <= SimpleFollow.Leader.HighestLevelTieredRiftKey;

            Logr.Debug("RequestFollowerOpenRift?={0}", result);
            return(result);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Initializes the specified minimum date.
        /// </summary>
        /// <param name="minDate">The minimum date.</param>
        /// <param name="maxDate">The maximum date.</param>
        /// <param name="highlightedDaysOfWeek">The highlighted days of week.</param>
        /// <returns>FluentInitializer.</returns>
        /// <exception cref="Java.Lang.IllegalArgumentException">
        /// minDate and maxDate must be non-zero.  +
        ///                 Debug(minDate, maxDate)
        /// or
        /// minDate must be before maxDate.  +
        ///                 Debug(minDate, maxDate)
        /// </exception>
        public EFluentInitializer Init(DateTime minDate, DateTime maxDate, DayOfWeek[] highlightedDaysOfWeek)
        {
            if (minDate == DateTime.MinValue || maxDate == DateTime.MinValue)
            {
                throw new IllegalArgumentException("minDate and maxDate must be non-zero. " +
                                                   Debug(minDate, maxDate));
            }
            if (minDate.CompareTo(maxDate) > 0)
            {
                throw new IllegalArgumentException("minDate must be before maxDate. " +
                                                   Debug(minDate, maxDate));
            }

            HighlighDaysOfWeeks(highlightedDaysOfWeek);

            Mode = SelectionMode.Single;
            //Clear out any previously selected dates/cells.
            SelectedCals.Clear();
            SelectedCells.Clear();
            _highlightedCals.Clear();
            _highlightedCells.Clear();

            //Clear previous state.
            Cells.Clear();
            Months.Clear();
            MinDate = minDate;
            MaxDate = maxDate;
            MinDate = SetMidnight(MinDate);
            MaxDate = SetMidnight(MaxDate);

            // maxDate is exclusive: bump back to the previous day so if maxDate is the first of a month,
            // We don't accidentally include that month in the view.
            if (MaxDate.Day == 1)
            {
                MaxDate = MaxDate.AddMinutes(-1);
            }

            //Now iterate between minCal and maxCal and build up our list of months to show.
            _monthCounter = MinDate;
            int maxMonth = MaxDate.Month;
            int maxYear  = MaxDate.Year;

            while ((_monthCounter.Month <= maxMonth ||
                    _monthCounter.Year < maxYear) &&
                   _monthCounter.Year < maxYear + 1)
            {
                var month = new MonthDescriptor(_monthCounter.Month, _monthCounter.Year, _monthCounter,
                                                _monthCounter.ToString(MonthNameFormat), _styleDescriptor);
                Cells.Add(GetMonthCells(month, _monthCounter));
                Logr.D("Adding month {0}", month);
                Months.Add(month);
                _monthCounter = _monthCounter.AddMonths(1);
            }

            ValidateAndUpdate();
            return(new EFluentInitializer(this));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Restores the original bot behavior.
        /// </summary>
        internal static void RestoreOriginalBotBehavior()
        {
            const string hookName = "BotBehavior";

            if (_originalBotBehavior != null && TreeHooks.Instance.Hooks.ContainsKey(hookName) && _hookReplaced)
            {
                Logr.Log("Replacing {0} hook to original", hookName);
                TreeHooks.Instance.ReplaceHook(hookName, new Sequence(_originalBotBehavior.ToArray()));
                _hookReplaced = false;
            }
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Called when [measure].
 /// </summary>
 /// <param name="widthMeasureSpec">horizontal space requirements as imposed by the parent.
 /// The requirements are encoded with
 /// <c><see cref="T:Android.Views.View+MeasureSpec" /></c>.</param>
 /// <param name="heightMeasureSpec">vertical space requirements as imposed by the parent.
 /// The requirements are encoded with
 /// <c><see cref="T:Android.Views.View+MeasureSpec" /></c>.</param>
 /// <exception cref="System.InvalidOperationException">Must have at least one month to display. Did you forget to call Init()?</exception>
 /// <since version="Added in API level 1" />
 /// <altmember cref="P:Android.Views.View.MeasuredWidth" />
 /// <altmember cref="P:Android.Views.View.MeasuredHeight" />
 /// <altmember cref="M:Android.Views.View.SetMeasuredDimension(System.Int32, System.Int32)" />
 /// <altmember cref="M:Android.Views.View.get_SuggestedMinimumHeight" />
 /// <altmember cref="M:Android.Views.View.get_SuggestedMinimumWidth" />
 /// <altmember cref="M:Android.Views.View.MeasureSpec.GetMode(System.Int32)" />
 /// <altmember cref="M:Android.Views.View.MeasureSpec.GetSize(System.Int32)" />
 /// <remarks><para tool="javadoc-to-mdoc" />
 /// <para tool="javadoc-to-mdoc">
 /// Measure the view and its content to determine the measured width and the
 /// measured height. This method is invoked by <c><see cref="M:Android.Views.View.Measure(System.Int32, System.Int32)" /></c> and
 /// should be overriden by subclasses to provide accurate and efficient
 /// measurement of their contents.
 /// </para>
 /// <para tool="javadoc-to-mdoc">
 ///   <i>CONTRACT:</i> When overriding this method, you
 /// <i>must</i> call <c><see cref="M:Android.Views.View.SetMeasuredDimension(System.Int32, System.Int32)" /></c> to store the
 /// measured width and height of this view. Failure to do so will trigger an
 /// <c>IllegalStateException</c>, thrown by
 /// <c><see cref="M:Android.Views.View.Measure(System.Int32, System.Int32)" /></c>. Calling the superclass'
 /// <c><see cref="M:Android.Views.View.OnMeasure(System.Int32, System.Int32)" /></c> is a valid use.
 /// </para>
 /// <para tool="javadoc-to-mdoc">
 /// The base class implementation of measure defaults to the background size,
 /// unless a larger size is allowed by the MeasureSpec. Subclasses should
 /// override <c><see cref="M:Android.Views.View.OnMeasure(System.Int32, System.Int32)" /></c> to provide better measurements of
 /// their content.
 /// </para>
 /// <para tool="javadoc-to-mdoc">
 /// If this method is overridden, it is the subclass's responsibility to make
 /// sure the measured height and width are at least the view's minimum height
 /// and width (<c><see cref="M:Android.Views.View.get_SuggestedMinimumHeight" /></c> and
 /// <c><see cref="M:Android.Views.View.get_SuggestedMinimumWidth" /></c>).
 /// </para>
 /// <para tool="javadoc-to-mdoc">
 ///   <format type="text/html">
 ///     <a href="http://developer.android.com/reference/android/view/View.html#onMeasure(int, int)" target="_blank">[Android Documentation]</a>
 ///   </format>
 /// </para></remarks>
 protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
 {
     if (Months.Count == 0)
     {
         throw new InvalidOperationException(
                   "Must have at least one month to display. Did you forget to call Init()?");
     }
     Logr.D("PickerView.OnMeasure w={0} h={1}", MeasureSpec.ToString(widthMeasureSpec),
            MeasureSpec.ToString(heightMeasureSpec));
     base.OnMeasure(widthMeasureSpec, heightMeasureSpec);
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Handles bot-start
        /// </summary>
        /// <param name="bot"></param>
        private void BotMain_OnStart(IBot bot)
        {
            LeaderComposite.ReplaceBotBehavior();
            if (Enabled)
            {
                Logr.Log("Bot Starting");
                SharedComposites.OutOfGameHookReplaced = false;
                SharedComposites.CheckReplaceOutOfGameHook();
                LeaderService.LeaderOutOfGameUpdate();

                ServiceBase.Communicate();
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Gets the month cells.
        /// </summary>
        /// <param name="month">The month.</param>
        /// <param name="startCal">The start cal.</param>
        /// <returns>List&lt;List&lt;MonthCellDescriptor&gt;&gt;.</returns>
        internal List <List <MonthCellDescriptor> > GetMonthCells(MonthDescriptor month, DateTime startCal)
        {
            var cells          = new List <List <MonthCellDescriptor> >();
            var cal            = new DateTime(startCal.Year, startCal.Month, 1);
            var firstDayOfWeek = (int)cal.DayOfWeek;

            cal = cal.AddDays((int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek - firstDayOfWeek);

            var minSelectedCal = GetMinDate(SelectedCals);
            var maxSelectedCal = GetMaxDate(SelectedCals);

            while ((cal.Month < month.Month + 1 || cal.Year < month.Year) &&
                   cal.Year <= month.Year)
            {
                Logr.D("Building week row starting at {0}", cal);
                var weekCells = new List <MonthCellDescriptor>();
                cells.Add(weekCells);
                for (int i = 0; i < 7; i++)
                {
                    var  date           = cal;
                    bool isCurrentMonth = cal.Month == month.Month;
                    bool isSelected     = isCurrentMonth && ContatinsDate(SelectedCals, cal);
                    bool isSelectable   = isCurrentMonth && IsBetweenDates(cal, MinDate, MaxDate);
                    bool isToday        = IsSameDate(cal, Today);
                    bool isHighlighted  = ContatinsDate(_highlightedCals, cal) || _hlighlightedDaysOfWeek[(int)cal.DayOfWeek];
                    int  value          = cal.Day;

                    var rangeState = RangeState.None;
                    if (SelectedCals.Count > 1)
                    {
                        if (IsSameDate(minSelectedCal, cal))
                        {
                            rangeState = RangeState.First;
                        }
                        else if (IsSameDate(maxSelectedCal, cal))
                        {
                            rangeState = RangeState.Last;
                        }
                        else if (IsBetweenDates(cal, minSelectedCal, maxSelectedCal))
                        {
                            rangeState = RangeState.Middle;
                        }
                    }

                    weekCells.Add(new MonthCellDescriptor(date, isCurrentMonth, isSelectable, isSelected,
                                                          isToday, isHighlighted, value, rangeState, _styleDescriptor));
                    cal = cal.AddDays(1);
                }
            }
            return(cells);
        }
Ejemplo n.º 15
0
 /// <summary>
 /// This method is processed by the leader (e.g. followers invoke it, the leader receives it and executes the body below)
 /// </summary>
 /// <param name="message"></param>
 /// <returns></returns>
 public Message GetUpdate()
 {
     try
     {
         Message m = SimpleFollow.Leader;
         //Logging.Write(m.ToString());
         return(m);
     }
     catch (Exception ex)
     {
         Logr.Log("Exception in GetUpdate() {0}", ex);
         return(new Message());
     }
 }
Ejemplo n.º 16
0
        public static void Pulse()
        {
            try
            {
                LeaderService.CleanExpiredFollowers();
                ServiceBase.Communicate();

                LeaderService.PulseInbox();

                SharedComposites.CheckReplaceOutOfGameHook();
            }
            catch (Exception ex)
            {
                Logr.Log("Exception thrown on Pulse: {0}", ex.ToString());
            }

            GameUI.SafeCheckClickButtons();
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Leaders the in game task.
        /// </summary>
        /// <param name="children">The children.</param>
        /// <returns>Task&lt;System.Boolean&gt;.</returns>
        internal static async Task <bool> LeaderInGameTask()
        {
            if (ValidCombatCheck() && AnyFollowersInCombat())
            {
                SimpleFollow.Pulse();
                Logr.Log("A friend is in combat - to the rescue!");

                ZetaDia.Me.TeleportToPlayerByIndex(SimpleFollow.Followers.FirstOrDefault(f => f.Value.IsInCombat).Value.CPlayerIndex);
                await Coroutine.Sleep(200);

                await Coroutine.Yield();
            }

            // In Party but no followers connected - just wait!
            while (Settings.Instance.WaitForFollowers && ValidCheck() && Social.NumPartyMembers - 1 != SimpleFollow.Followers.Count)
            {
                SimpleFollow.Pulse();
                Logr.Log("Waiting for party members to connect to SimpleFollow server...");
                await Coroutine.Yield();
            }

            while (Settings.Instance.WaitForFollowers && ValidCheck() && !AllFollowersInGame())
            {
                SimpleFollow.Pulse();
                Logr.Log("Waiting for party members to join same game...");
                await Coroutine.Yield();
            }

            while (Settings.Instance.WaitForFollowers && ValidCheck() && AnyFollowersNotInTown())
            {
                SimpleFollow.Pulse();
                Logr.Log("Waiting for party members to come to town...");
                await Coroutine.Yield();
            }

            /* Wait for followers to open greater rift
             * while (ValidCheck() && ShouldFollowerOpenRift())
             * {
             *  SimpleFollow.Pulse();
             *  Logr.Log("Waiting for follower to open rift...");
             *  await Coroutine.Yield();
             * }*/
            return(false);
        }
Ejemplo n.º 18
0
        public void OnEnabled()
        {
            Logr.Log("Plugin v{0} Enabled", Version);
            Enabled = true;

            BotMain.OnStart                   += BotMain_OnStart;
            BotMain.OnStop                    += BotMain_OnStop;
            GameEvents.OnGameLeft             += GameEvents_OnGameLeft;
            GameEvents.OnGameJoined           += GameEvents_OnGameJoined;
            GameEvents.OnWorldTransferStart   += GameEvents_OnWorldTransferStart;
            GameEvents.OnWorldChanged         += GameEvents_OnWorldChanged;
            TreeHooks.Instance.OnHooksCleared += OnHooksCleared;

            SharedComposites.OutOfGameHookReplaced = false;
            SharedComposites.CheckReplaceOutOfGameHook();
            LeaderService.LeaderOutOfGameUpdate();

            ServiceBase.Communicate();
        }
Ejemplo n.º 19
0
 public void OpenSocialWindow()
 {
     if (DateTime.UtcNow.Subtract(lastOpenedSocialWindow).TotalMilliseconds <= 500)
     {
         return;
     }
     // only click social button to open social window if window is not visible
     if (!IsSocialWindowOpen)
     {
         GameUI.SafeClick(SocialFlyoutButton, ClickDelay.NoDelay, "Social Flyout Button", 500);
         GameUI.SafeClick(ToggleSocialButton, ClickDelay.NoDelay, "Social Window", 500);
         lastOpenedSocialWindow = DateTime.UtcNow;
         recheckInvites         = true;
         return;
     }
     if (IsSocialWindowOpen && !GameUI.ElementIsVisible(AddFriendButton, "Add Friend Button"))
     {
         Logr.Log("Unable to open social window!");
     }
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Pulsing this will update both the follower and leader messages.
 /// </summary>
 internal static void Communicate()
 {
     if (Enabled)
     {
         if (!IsFollower)
         {
             LeaderService.BehaviorWatcher();
             LeaderService.ServerUpdate();
         }
         else
         {
             FollowerService.AsyncClientUpdate();
         }
     }
     else
     {
         Logr.Log("Error - Main pulsed but plugin is disabled!");
         SharedComposites.CheckReplaceOutOfGameHook();
     }
 }
Ejemplo n.º 21
0
        internal static void CheckReplaceOutOfGameHook()
        {
            // Plugin was diabled, replace hook to original
            if (!SimpleFollow.Enabled)
            {
                if (_originalOutOfGameComposites != null)
                {
                    Logr.Log("Replacing OutOfGame hook to original");
                    TreeHooks.Instance.ReplaceHook("OutOfGame", new PrioritySelector(_originalOutOfGameComposites.ToArray()));
                }
                _outOfGameHookReplaced = false;
                return;
            }

            if (ProfileManager.CurrentProfile != null)
            {
                if (SimpleFollow.IsFollower && !_outOfGameHookReplaced)
                {
                    Logr.Log("Replacing OutOfGame hook with Follower Behavior");
                    StoreOriginalOutOfGameComposite();
                    _followerBehavior = FollowerComposite.CreateBehavior();
                    TreeHooks.Instance.ReplaceHook("OutOfGame", _followerBehavior);
                    _outOfGameHookReplaced = true;
                }
                else if (!SimpleFollow.IsFollower && !_outOfGameHookReplaced)
                {
                    Logr.Log("Replacing OutOfGame hook with Leader Behavior");
                    if (SimpleFollow.Enabled)
                    {
                        StoreOriginalOutOfGameComposite();

                        if (_originalOutOfGameComposites != null)
                        {
                            // Reference the leader composite (since we're no longer a follower)
                            TreeHooks.Instance.ReplaceHook("OutOfGame", LeaderComposite.CreateOutOfGameBehavior(_originalOutOfGameComposites));
                            _outOfGameHookReplaced = true;
                        }
                    }
                }
            }
        }
Ejemplo n.º 22
0
        public static Window GetDisplayWindow()
        {
            try
            {
                if (_configWindow == null)
                {
                    _configWindow = new Window();
                }

                string assemblyPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                string xamlPath     = Path.Combine(assemblyPath, "Plugins", "SimpleFollow", "UI", "Config.xaml");

                string xamlContent = File.ReadAllText(xamlPath);

                // This hooks up our object with our UserControl DataBinding
                _configWindow.DataContext = Settings.Instance;

                UserControl mainControl = (UserControl)XamlReader.Load(new MemoryStream(Encoding.UTF8.GetBytes(xamlContent)));
                _configWindow.Content    = mainControl;
                _configWindow.Width      = 300;
                _configWindow.Height     = 360;
                _configWindow.MinWidth   = 300;
                _configWindow.MinHeight  = 360;
                _configWindow.ResizeMode = ResizeMode.CanResizeWithGrip;

                _configWindow.Title = "SimpleFollow";

                _configWindow.Closed     += ConfigWindow_Closed;
                Application.Current.Exit += ConfigWindow_Closed;

                return(_configWindow);
            }
            catch (Exception ex)
            {
                Logr.Error("Unable to open Config window: " + ex);
            }
            return(null);
        }
Ejemplo n.º 23
0
        public void Update()
        {
            if (DateTime.UtcNow.Subtract(LastUpdate).TotalMilliseconds < Settings.Instance.UpdateInterval)
            {
                return;
            }

            LastUpdate = DateTime.UtcNow;
            IsInGame   = ZetaDia.IsInGame;

            if (!ZetaDia.IsInGame || ZetaDia.IsLoadingWorld || !ZetaDia.Me.IsValid)
            {
                return;
            }

            ACDGuid                        = ZetaDia.Me.ACDGuid;
            HitpointsCurrent               = ZetaDia.Me.HitpointsCurrent;
            HitpointsCurrentPct            = ZetaDia.Me.HitpointsCurrentPct;
            HitpointsMaxTotal              = ZetaDia.Me.HitpointsMaxTotal;
            Position                       = ZetaDia.Me.Position;
            CurrentLevelAreaId             = LevelAreaId;
            CurrentWorldId                 = ZetaDia.CurrentWorldId;
            CurrentDynamicWorldId          = ZetaDia.CurrentWorldDynamicId;
            IsInTown                       = ZetaDia.IsInTown;
            IsVendoring                    = BrainBehavior.IsVendoring;
            IsParticipatingInTieredLootRun = ZetaDia.Me.IsParticipatingInTieredLootRun;
            InTieredLootRunLevel           = ZetaDia.Me.InTieredLootRunLevel;

            if (_lastLogMessage != ToString())
            {
                _lastLogMessage = ToString();
                if (Settings.Instance.DebugLogging)
                {
                    Logr.Debug("Updated {0}", ToString());
                }
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Clicks a UI Element after a random interval.
        /// </summary>
        /// <param name="uiElement"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        internal static bool SafeClick(UIElement uiElement, ClickDelay delayOption, string name = "", int postClickThreadSleepDuration = 0, bool fireWorldTransferStart = false)
        {
            try
            {
                if (DateTime.UtcNow.Subtract(_lastClick).TotalMilliseconds < 500)
                {
                    return(false);
                }

                if (ElementIsVisible(uiElement, name))
                {
                    if (!String.IsNullOrEmpty(name))
                    {
                        Logr.Debug("{0} button is visible", name);
                    }
                    else
                    {
                        Logr.Debug("{0}={1} is visible", uiElement.Hash, uiElement.Name);
                    }

                    if (!clickTimer.IsRunning && delayOption == ClickDelay.Delay)
                    {
                        clickTimer.Start();
                        SetClickTimerRandomVal();
                    }
                    else if ((ClickTimerRandomReady() && ElementIsVisible(uiElement, name)) || delayOption == ClickDelay.NoDelay)
                    {
                        if (!String.IsNullOrEmpty(name))
                        {
                            Logr.Log("Clicking {0} button", name);
                        }
                        else
                        {
                            Logr.Log("Clicking {0}={1}", uiElement.Hash, uiElement.Name);
                        }

                        // sleep plugins for a bit
                        if (ZetaDia.IsInGame && fireWorldTransferStart)
                        {
                            GameEvents.FireWorldTransferStart();
                        }

                        _lastClick = DateTime.UtcNow;
                        uiElement.Click();
                        //BotMain.PauseFor(TimeSpan.FromMilliseconds(ClickThreadSleepInterval));

                        //if (postClickThreadSleepDuration > 0)
                        //    BotMain.PauseFor(TimeSpan.FromMilliseconds(postClickThreadSleepDuration));

                        clickTimer.Reset();
                    }
                    else
                    {
                        Logr.Debug("Pausing bot, waiting for {0}={1}", uiElement.Hash, uiElement.Name);
                        BotMain.PauseWhile(ClickTimerRandomNotReady, 0, ClickTimerTimeout);
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                Logr.Log("Error clicking UI button {0}: " + ex.ToString(), name);
                return(false);
            }
        }
Ejemplo n.º 25
0
 private static void SetClickTimerRandomVal()
 {
     clickTimerRandomVal = clickDelayRnd.Next(1250, 2250);
     Logr.Log("Random timer set to {0}ms", clickTimerRandomVal);
 }
Ejemplo n.º 26
0
        private static void SetQuestToolsOptionsFromLeader()
        {
            bool questToolsSettingsChanged = false;

            if (Leader.RiftKeyPriority == null || Leader.MinimumGemChance == 0f || Leader.LimitRiftLevel == 0 || Leader.TrialRiftMaxLevel == 0)
            {
                return;
            }
            string thingsThatChanged = "";

            // Force followers to use leader's rift key priority
            if (!QuestToolsSettings.Instance.RiftKeyPriority.SequenceEqual(Leader.RiftKeyPriority))
            {
                QuestToolsSettings.Instance.RiftKeyPriority = Leader.RiftKeyPriority;
                questToolsSettingsChanged = true;
                thingsThatChanged        += "RiftKeyPriority,";
                thingsThatChanged         = Leader.RiftKeyPriority.Aggregate(thingsThatChanged, (current, k) => current + (k + "-"));
                thingsThatChanged        += " ";
                thingsThatChanged         = QuestToolsSettings.Instance.RiftKeyPriority.Aggregate(thingsThatChanged, (current, k) => current + (k + "-"));
            }

            if (QuestToolsSettings.Instance.UseHighestKeystone != Leader.UseHighestKeystone)
            {
                QuestToolsSettings.Instance.UseHighestKeystone = Leader.UseHighestKeystone;
                questToolsSettingsChanged = true;
                thingsThatChanged        += "UseHighestKeystone,";
            }

            if (QuestToolsSettings.Instance.MinimumGemChance != Leader.MinimumGemChance)
            {
                QuestToolsSettings.Instance.MinimumGemChance = Leader.MinimumGemChance;
                questToolsSettingsChanged = true;
                thingsThatChanged        += "MinimumGemChance,";
            }

            if (QuestToolsSettings.Instance.EnableLimitRiftLevel != Leader.EnableLimitRiftLevel)
            {
                QuestToolsSettings.Instance.EnableLimitRiftLevel = Leader.EnableLimitRiftLevel;
                questToolsSettingsChanged = true;
                thingsThatChanged        += "EnableLimitRiftLevel,";
            }

            if (QuestToolsSettings.Instance.LimitRiftLevel != Leader.LimitRiftLevel)
            {
                QuestToolsSettings.Instance.LimitRiftLevel = Leader.LimitRiftLevel;
                questToolsSettingsChanged = true;
                thingsThatChanged        += "LimitRiftLevel,";
            }

            if (QuestToolsSettings.Instance.EnableTrialRiftMaxLevel != Leader.EnableTrialRiftMaxLevel)
            {
                QuestToolsSettings.Instance.EnableTrialRiftMaxLevel = Leader.EnableTrialRiftMaxLevel;
                questToolsSettingsChanged = true;
                thingsThatChanged        += "EnableTrialRiftMaxLevel,";
            }

            if (QuestToolsSettings.Instance.TrialRiftMaxLevel != Leader.TrialRiftMaxLevel)
            {
                QuestToolsSettings.Instance.TrialRiftMaxLevel = Leader.TrialRiftMaxLevel;
                questToolsSettingsChanged = true;
                thingsThatChanged        += "TrialRiftMaxLevel,";
            }

            if (questToolsSettingsChanged)
            {
                Logr.Log("Updated QuestTools Settings From Leader: " + thingsThatChanged);
                QuestToolsSettings.Instance.Save();
            }
        }
Ejemplo n.º 27
0
        internal static void PulseInbox()
        {
            // Process Messages
            Queue <Message> messages = new Queue <Message>();

            try
            {
                lock (Inbox)
                    while (Inbox.ToList().Any())
                    {
                        Message msg;
                        if (Inbox.TryDequeue(out msg) && msg != null)
                        {
                            messages.Enqueue(msg);
                        }
                    }
            }
            catch (Exception ex)
            {
                Logr.Log(ex.ToString());
            }

            CleanExpiredFollowers();

            while (messages.ToList().Any())
            {
                var message = messages.Dequeue();

                if (message == null)
                {
                    continue;
                }

                try
                {
                    if (message.BattleTagHash != 0)
                    {
                        if (Followers.ContainsKey(message.BattleTagHash))
                        {
                            Followers[message.BattleTagHash] = message;
                        }
                        else
                        {
                            Followers.Add(message.BattleTagHash, message);
                        }
                    }

                    if (Settings.Instance.DebugLogging)
                    {
                        Logr.Debug("Received follower message: {0}", message);
                    }

                    if (!message.IsInParty && !message.IsInGame && Leader.IsInGame)
                    {
                        Logr.Debug("Inviting {0} ({1}) to the party - Not in game. IsInGame={2} IsInParty={3} NumPartyMembers={4}",
                                   message.ActorClass, message.BattleTagHash, message.IsInGame, message.IsInParty, message.NumPartymembers);
                        Social.Instance.CheckInvites();
                        continue;
                    }

                    if (!message.IsInParty && (message.GameId.FactoryId == 0 && message.GameId.High == 0 && message.GameId.Low == 0) && !Leader.IsInGame)
                    {
                        Logr.Debug("Inviting {0} ({1}) to the party - Needs Invite. IsInGame={2} IsInParty={3} NumPartyMembers={4}",
                                   message.ActorClass, message.BattleTagHash, message.IsInGame, message.IsInParty, message.NumPartymembers);
                        Social.Instance.CheckInvites();
                        continue;
                    }

                    if (!Leader.GameId.Equals(message.GameId))
                    {
                        Logr.Debug("Inviting {0} ({1}) to the party - Incorrect Game. IsInGame={2} IsInParty={3} NumPartyMembers={4}",
                                   message.ActorClass, message.BattleTagHash, message.IsInGame, message.IsInParty, message.NumPartymembers);
                        Social.Instance.CheckInvites();
                        continue;
                    }

                    if (Leader.GameId.Equals(message.GameId))
                    {
                        Social.Instance.CheckCloseSocialWindow();
                        continue;
                    }

                    Logr.Log("Message response: invalid/unknown state");
                }
                catch (Exception ex)
                {
                    Logr.Log("Exception receiving update from client!");
                    Logr.Log(ex.ToString());
                    return;
                }
            }
        }
Ejemplo n.º 28
0
        internal void CheckInvites()
        {
            if (!BotMain.IsRunning)
            {
                return;
            }

            if (ZetaDia.IsLoadingWorld)
            {
                return;
            }

            if (ZetaDia.Me != null && !ZetaDia.Me.IsValid)
            {
                return;
            }

            if (ZetaDia.IsInGame && ZetaDia.Me != null && ZetaDia.Me.IsValid && ZetaDia.Me.IsDead)
            {
                return;
            }

            if (GameUI.ElementIsVisible(GameUI.BattleNetOK, "BattleNetOK"))
            {
                GameUI.SafeCheckClickButtons();
                return;
            }

            const int recheckDuration = 500;

            if (!recheckInvites && DateTime.UtcNow.Subtract(lastInviteCheck).TotalMilliseconds < recheckDuration)
            {
                return;
            }

            lastInviteCheck = DateTime.UtcNow;

            if (ZetaDia.Service.Party.IsPartyFull)
            {
                recheckInvites = false;
                if (IsSocialWindowOpen)
                {
                    CloseSocialWindow();
                }
                return;
            }

            // Start inviting
            if (!IsSocialWindowOpen)
            {
                Logr.Debug("Opening Social Window");
                OpenSocialWindow();
                return;
            }

            if (IsSocialWindowOpen)
            {
                if (Settings.Instance.InviteFriend1 && GameUI.ElementIsVisible(Friend1InviteButton, "Friend 1 Invite"))
                {
                    GameUI.SafeClick(Friend1InviteButton, ClickDelay.NoDelay, "Friend 1 Invite", 750);
                    recheckInvites = true;
                    return;
                }
                if (Settings.Instance.InviteFriend2 && GameUI.ElementIsVisible(Friend2InviteButton, "Friend 2 Invite"))
                {
                    GameUI.SafeClick(Friend2InviteButton, ClickDelay.NoDelay, "Friend 2 Invite", 750);
                    recheckInvites = true;
                    return;
                }
                if (Settings.Instance.InviteFriend3 && GameUI.ElementIsVisible(Friend3InviteButton, "Friend 3 Invite"))
                {
                    GameUI.SafeClick(Friend3InviteButton, ClickDelay.NoDelay, "Friend 3 Invite", 750);
                    recheckInvites = true;
                    return;
                }
                if (Settings.Instance.InviteFriend3 && GameUI.ElementIsVisible(Friend3AlternateInviteButton, "Friend 3 Alternate Invite"))
                {
                    GameUI.SafeClick(Friend3AlternateInviteButton, ClickDelay.NoDelay, "Friend 3 Invite", 750);
                    recheckInvites = true;
                    return;
                }
                if (Settings.Instance.InviteFriend4 && GameUI.ElementIsVisible(Friend4InviteButton, "Friend 4 Invite"))
                {
                    GameUI.SafeClick(Friend4InviteButton, ClickDelay.NoDelay, "Friend 4 Invite", 750);
                    recheckInvites = true;
                    return;
                }
                if (Settings.Instance.InviteFriend4 && GameUI.ElementIsVisible(Friend4AlternateInviteButton, "Friend 4 Alternate Invite"))
                {
                    GameUI.SafeClick(Friend4AlternateInviteButton, ClickDelay.NoDelay, "Friend 4 Alternate Invite", 750);
                    recheckInvites = true;
                    return;
                }
                Logr.Debug("No more invites possible");
                recheckInvites = false;
                CloseSocialWindow();
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Called by followers through FollowTag->Communicate()
        /// </summary>
        private static void ClientUpdate()
        {
            if (Enabled)
            {
                _updateRunning = true;
                try
                {
                    if (Host != null && Host.State == CommunicationState.Opened)
                    {
                        Logr.Log("Shutting down Server Service");
                        Host.Close();
                        Host = null;
                    }
                }
                catch (Exception ex)
                {
                    Logr.Error("Error shutting down server service: " + ex);
                }

                StartClient();

                try
                {
                    if (Initialized && Leader.GetMillisecondsSinceLastUpdate() >= 250)
                    {
                        // Get the leader message and store it
                        Leader = HttpProxy.GetUpdate();

                        // Send our follower message to the leader
                        HttpProxy.SendUpdate(_lastMessage);


                        if (LastLeaderUpdateMessage == null || LastLeaderUpdateMessage != Leader)
                        {
                            LastLeaderUpdateMessage = Leader;

                            SetQuestToolsOptionsFromLeader();

                            if (Settings.Instance.DebugLogging)
                            {
                                Logr.Debug("Leader {0}", Leader.ToString());
                            }
                        }
                    }
                }
                catch (EndpointNotFoundException ex)
                {
                    Logr.Error("Error 201: Could not get an update from the leader using {0}. Is the leader running? ({1})", HttpFactory.Endpoint.Address.Uri.AbsoluteUri, ex.Message);
                    Initialized = false;
                }
                catch (CommunicationException ex)
                {
                    Logr.Error("Error 202: Could not get an update from the leader using {0}. Is the leader running? ({1})", HttpFactory.Endpoint.Address.Uri.AbsoluteUri, ex.Message);
                    Initialized = false;
                }
                catch (Exception ex)
                {
                    Logr.Error("Error 203: Could not get an update from the leader using {0}. Is the leader running?", HttpFactory.Endpoint.Address.Uri.AbsoluteUri);
                    Initialized = false;
                    Logr.Log(ex.ToString());
                }
                _updateRunning = false;
            }
        }
Ejemplo n.º 30
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.calendar_picker);

            var nextYear = DateTime.Now.AddYears(1);

            var calendar = FindViewById <CalendarPickerView>(Resource.Id.calendar_view);

            calendar.Init(DateTime.Now, nextYear)
            .InMode(CalendarPickerView.SelectionMode.Single)
            .WithSelectedDate(DateTime.Now)
            .WithHighlightedDate(DateTime.Now.AddDays(2));

            calendar.OnDateSelected +=
                (s, e) => Toast.MakeText(this, e.SelectedDate.ToShortDateString(), ToastLength.Short).Show();

            var btnSingle = FindViewById <Button>(Resource.Id.button_single);
            var btnMulti  = FindViewById <Button>(Resource.Id.button_multi);
            var btnRange  = FindViewById <Button>(Resource.Id.button_range);
            var btnDialog = FindViewById <Button>(Resource.Id.button_dialog);

            btnSingle.Click += (s, e) =>
            {
                btnSingle.Enabled = false;
                btnMulti.Enabled  = true;
                btnRange.Enabled  = true;

                calendar.Init(DateTime.Now, nextYear)
                .InMode(CalendarPickerView.SelectionMode.Single)
                .WithSelectedDate(DateTime.Now);
            };

            btnMulti.Click += (s, e) =>
            {
                btnSingle.Enabled = true;
                btnMulti.Enabled  = false;
                btnRange.Enabled  = true;

                var dates = new List <DateTime>();
                for (int i = 0; i < 5; i++)
                {
                    dates.Add(DateTime.Now.AddDays(3 * i));
                }
                calendar.Init(DateTime.Now, nextYear)
                .InMode(CalendarPickerView.SelectionMode.Multi)
                .WithSelectedDates(dates);
            };

            btnRange.Click += (s, e) =>
            {
                btnSingle.Enabled = true;
                btnMulti.Enabled  = true;
                btnRange.Enabled  = false;

                var dates = new List <DateTime>()
                {
                    DateTime.Now.AddDays(3), DateTime.Now.AddDays(5)
                };
                calendar.Init(DateTime.Now, nextYear)
                .InMode(CalendarPickerView.SelectionMode.Range)
                .WithSelectedDates(dates);
            };

            btnDialog.Click += (s, e) =>
            {
                var dialogView =
                    (CalendarPickerView)LayoutInflater.Inflate(Resource.Layout.dialog, null, false);
                dialogView.Init(DateTime.Now, nextYear);
                new AlertDialog.Builder(this).SetTitle("I'm a dialog!")
                .SetView(dialogView)
                .SetNeutralButton("Dismiss",
                                  (sender, args) => { }).Create().Show();
            };

            FindViewById <Button>(Resource.Id.done_button).Click += (s, o) =>
            {
                calendar = FindViewById <CalendarPickerView>(Resource.Id.calendar_view);
                Logr.D(TAG, "Selected time in millis: " + calendar.SelectedDate);
                string toast = "Selected: " + calendar.SelectedDate;
                Toast.MakeText(this, toast, ToastLength.Short).Show();
            };
        }