コード例 #1
0
ファイル: ShipUiModule.cs プロジェクト: WahlbergRu/Sanderling
 public ShipUiModule(
     Int64 id,
     PropertyGenTimespanInt64 <Accumulation.IShipUiModuleAndContext> instant)
     : base(id, instant)
 {
     HistoryLengthMax = 2;
 }
コード例 #2
0
ファイル: ShipUiModule.cs プロジェクト: WahlbergRu/Sanderling
        protected override void Accumulated(PropertyGenTimespanInt64 <Accumulation.IShipUiModuleAndContext> instant, Parse.IMemoryMeasurement shared)
        {
            base.Accumulated(instant, shared);

            var ModuleButtonTooltip = shared?.ModuleButtonTooltip;

            if ((instant?.Value?.Module?.HiliteVisible ?? false) &&
                (instant?.Value?.Location).HasValue &&
                null != ModuleButtonTooltip)
            {
                var TooltipWithTimespan = ModuleButtonTooltip.WithTimespanInt64(instant);

                var PreviousTooltip = ListTooltip?.LastOrDefault();

                ListTooltip.Enqueue(TooltipWithTimespan);
                ListTooltip.ListeKürzeBegin(4);

                var TooltipLast = TooltipWithTimespan;

                var PreviousInstant = InstantWithAgeStepCount(1);

                if ((PreviousInstant?.Value?.Module?.HiliteVisible ?? false) &&
                    PreviousInstant?.Value?.Module?.ModuleButtonIconTexture?.Id == instant?.Value?.Module?.ModuleButtonIconTexture?.Id &&
                    PreviousTooltip?.Begin == PreviousInstant?.Begin)
                {
                    //	It seems that data read from module tooltips is corrupted frequently.
                    //	To alleviate this problem, tooltips in consecutive measurements are compared and a heuristic is applied to guess which one is the best to pick to be kept.
                    //	To benefit from this, a script generates multiple measurements while a tooltip is open for the module.
                    TooltipLast = new[] { TooltipLast, PreviousTooltip }.BestRead(inst => inst?.Value);
                }

                this.TooltipLast = TooltipLast;
            }
        }
コード例 #3
0
ファイル: Entity.cs プロジェクト: theroadninja/Sanderling
 public EntityScoring(
     Int64 id,
     PropertyGenTimespanInt64 <AccumulatedT> instant)
     :
     base(id, instant)
 {
 }
コード例 #4
0
        void BotMotion(
            FromProcessMeasurement <IMemoryMeasurement> memoryMeasurement,
            IEnumerable <Bot.MotionRecommendation> sequenceMotion)
        {
            var processId = memoryMeasurement?.ProcessId;

            if (!processId.HasValue || null == sequenceMotion || sequenceMotion.IsNullOrEmpty())
            {
                return;
            }
            var process = System.Diagnostics.Process.GetProcessById(processId.Value);

            var listMotionResult = new List <Bot.MotionResult>();
            var startTime        = GetTimeStopwatch();

            botLock.WhenLockIsAvailableEnter(300, () =>
            {
                var motor = new WindowMotor(process.MainWindowHandle);

                foreach (var motion in sequenceMotion)
                {
                    var motionResult =
                        motor.ActSequenceMotion(motion.MotionParam.AsSequenceMotion(memoryMeasurement?.Value));

                    listMotionResult.Add(new Bot.MotionResult
                    {
                        Id      = motion.Id,
                        Success = motionResult?.Success ?? false,
                    });
                }
            }, "MotionExecution");
            BotStepLastMotionResult = new PropertyGenTimespanInt64 <Bot.MotionResult[]>(listMotionResult.ToArray(), startTime, GetTimeStopwatch());

            Thread.Sleep(sequenceMotion.Max(sm => sm.DelayAfterMs ?? FromMotionToMeasurementDelayMilli));
        }
コード例 #5
0
ファイル: LicenseClient.cs プロジェクト: Fulborg/A-Bot
 public PropertyGenTimespanInt64 <HttpExchangeReport <TRequest, TResponse> > HttpExchangeLocked <TRequest, TResponse>(string uriComponent, TRequest request, bool deflate = false) where TResponse : class
 {
     lock (Lock)
     {
         long timeContinuousMilli = TimesourceConfig.StaticConfig.TimeContinuousMilli;
         PropertyGenTimespanInt64 <HttpExchangeReport <TRequest, TResponse> > propertyGenTimespanInt = null;
         string         text           = UriPlusComponent(uriComponent);
         TResponse      response       = null;
         Exception      exception      = null;
         HttpStatusCode?httpStatusCode = null;
         try
         {
             string            sessionId        = null;
             IRequestInSession requestInSession = request as IRequestInSession;
             if (requestInSession != null)
             {
                 sessionId = requestInSession.SessionIdAsString();
             }
             try
             {
                 WebClient.Timeout   = Timeout;
                 WebClient.SessionId = sessionId;
                 byte[] bytes = Encoding.UTF8.GetBytes(request.SerializeToString());
                 Func <string, byte[], byte[]> func = deflate ? new Func <string, byte[], byte[]>(UploadDataDeflate) : new Func <string, byte[], byte[]>(UploadData);
                 byte[] array = func(text, bytes);
                 if (array.IsNullOrEmpty())
                 {
                     throw new ArgumentException("Response empty");
                 }
                 response       = ((array != null) ? array.DeserializeFromUtf8 <TResponse>() : null);
                 httpStatusCode = HttpStatusCode.OK;
             }
             catch (WebException ex)
             {
                 httpStatusCode = (ex?.Response as HttpWebResponse)?.StatusCode;
                 exception      = ex;
             }
             catch (Exception ex2)
             {
                 exception = ex2;
             }
         }
         finally
         {
             long timeContinuousMilli2 = TimesourceConfig.StaticConfig.TimeContinuousMilli;
             propertyGenTimespanInt = new PropertyGenTimespanInt64 <HttpExchangeReport <TRequest, TResponse> >(new HttpExchangeReport <TRequest, TResponse>(request, response, text, exception, httpStatusCode), timeContinuousMilli, timeContinuousMilli2);
             HttpExchangeLast       = propertyGenTimespanInt.CastToHttpExchange();
             PropertyGenTimespanInt64 <IHttpExchangeReport> propertyGenTimespanInt2 = propertyGenTimespanInt.CastToHttpExchange();
             if (propertyGenTimespanInt.Value.HttpExchangeSuccess() ?? false)
             {
                 HttpExchangeSuccessfulLast = propertyGenTimespanInt2;
             }
             else
             {
                 HttpExchangeFailedLast = propertyGenTimespanInt2;
             }
         }
         return(propertyGenTimespanInt);
     }
 }
コード例 #6
0
        void BotConfigLoad()
        {
            // Wait for configMutex before loading config
            App.configMutex.WaitOne();

            Exception exception      = null;
            string    configString   = null;
            var       configFilePath = AssemblyDirectoryPath.PathToFilesysChild(BotConfigFileName);

            try
            {
                using (var fileStream = new FileStream(configFilePath, FileMode.Open, FileAccess.Read))
                    configString = new StreamReader(fileStream).ReadToEnd();
            }
            catch (Exception e)
            {
                exception = e;
            }

            BotConfigLoaded = new PropertyGenTimespanInt64 <KeyValuePair <Exception, StringAtPath> >(new KeyValuePair <Exception, StringAtPath>(
                                                                                                         exception,
                                                                                                         new StringAtPath {
                Path = configFilePath, String = configString
            }), GetTimeStopwatch());

            App.configMutex.ReleaseMutex();
        }
コード例 #7
0
 public EntityScoring(
     Int64 Id,
     PropertyGenTimespanInt64 <AccumulatedT> Instant)
     :
     base(Id, Instant)
 {
 }
コード例 #8
0
        public BotStepResult Step(BotStepInput input)
        {
            var beginTimeMilli = GetTimeMilli();

            StepLastInput = input;

            Exception exception = null;

            var listMotion = new List <MotionRecommendation>();

            IBotTask[][] outputListTaskPath = null;

            try
            {
                MemorizeStepInput(input);

                outputListTaskPath = StepOutputListTaskPath()?.ToArray();

                foreach (var moduleToggle in outputListTaskPath.ConcatNullable().OfType <ModuleToggleTask>().Select(moduleToggleTask => moduleToggleTask?.module).WhereNotDefault())
                {
                    ToggleLastStepIndexFromModule[moduleToggle] = stepIndex;
                }

                foreach (var taskPath in outputListTaskPath.EmptyIfNull())
                {
                    var taskMotionParam = taskPath?.LastOrDefault()?.Motion;

                    if (null == taskMotionParam)
                    {
                        continue;
                    }

                    listMotion.Add(new MotionRecommendation
                    {
                        Id          = motionId++,
                        MotionParam = taskMotionParam,
                    });
                }
            }
            catch (Exception e)
            {
                exception = e;
            }

            var stepResult = new BotStepResult
            {
                Exception          = exception,
                ListMotion         = listMotion?.ToArrayIfNotEmpty(),
                OutputListTaskPath = outputListTaskPath,
            };

            MemorizeStepResult(stepResult);

            StepLastResult = new PropertyGenTimespanInt64 <BotStepResult>(stepResult, beginTimeMilli, GetTimeMilli());

            ++stepIndex;

            return(stepResult);
        }
コード例 #9
0
ファイル: Entity.cs プロジェクト: theroadninja/Sanderling
 public EntityWithHistory(
     Int64 id,
     PropertyGenTimespanInt64 <AccumulatedT> instant,
     SharedT shared = default(SharedT))
     :
     base(id)
 {
     Accumulate(instant, shared);
 }
コード例 #10
0
ファイル: Bot.cs プロジェクト: Fulborg/A-Bot
        public BotStepResult Step(BotStepInput input)
        {
            var beginTimeMilli = GetTimeMilli();

            StepLastInput = input;

            Exception exception = null;

            var listMotion = new List <MotionRecommendation>();

            IBotTask[][] outputListTaskPath = null;

            try
            {
                MemorizeStepInput(input);

                outputListTaskPath = ((IBotTask) new BotTask(null)
                {
                    Component = strategy.GetTasks(this)
                })
                                     ?.EnumeratePathToNodeFromTreeDFirst(node => node?.Component)
                                     ?.Where(taskPath => (taskPath?.LastOrDefault()).ShouldBeIncludedInStepOutput())
                                     ?.TakeSubsequenceWhileUnwantedInferenceRuledOut()
                                     ?.ToArray();

                foreach (var moduleToggle in outputListTaskPath.ConcatNullable().OfType <ModuleToggleTask>()
                         .Select(moduleToggleTask => moduleToggleTask?.module).WhereNotDefault())
                {
                    ToggleLastStepIndexFromModule[moduleToggle] = stepIndex;
                }

                foreach (var effect in outputListTaskPath.EmptyIfNull().SelectMany(taskPath =>
                                                                                   (taskPath?.LastOrDefault()?.ApplicableEffects()).EmptyIfNull()))
                {
                    listMotion.Add(effect);
                }
            }
            catch (Exception e)
            {
                exception = e;
            }

            var stepResult = new BotStepResult
            {
                Exception          = exception,
                ListMotion         = listMotion?.ToArrayIfNotEmpty(),
                OutputListTaskPath = outputListTaskPath,
            };

            MemorizeStepResult(stepResult);

            StepLastResult = new PropertyGenTimespanInt64 <BotStepResult>(stepResult, beginTimeMilli, GetTimeMilli());

            ++stepIndex;

            return(stepResult);
        }
コード例 #11
0
 public void Reset()
 {
     lock (@lock)
     {
         CyclicExchangeStop();
         LicenseClient             = null;
         InterfaceAppManagerAtTime = null;
     }
 }
コード例 #12
0
 public EntityWithHistory(
     Int64 Id,
     PropertyGenTimespanInt64 <AccumulatedT> Instant,
     SharedT Shared = default(SharedT))
     :
     base(Id)
 {
     Accumulate(Instant, Shared);
 }
コード例 #13
0
 public static string RenderBotStepToUIText(this PropertyGenTimespanInt64 <BotStepResult> stepResultAtTimeMilli)
 {
     return(null == stepResultAtTimeMilli
                         ? null
                         : stepResultAtTimeMilli?.Value?.OutputListTaskPath?.Count() + " leaves " +
            TimeAgeMilliToUIText(Bot.Bot.GetTimeMilli() - stepResultAtTimeMilli?.Begin) +
            Environment.NewLine +
            RenderBotStepToUIText(stepResultAtTimeMilli.Value));
 }
コード例 #14
0
        void BotMotion(
            FromProcessMeasurement <IMemoryMeasurement> memoryMeasurement,
            IEnumerable <Bot.MotionRecommendation> sequenceMotion)
        {
            var processId = memoryMeasurement?.ProcessId;

            if (!processId.HasValue || null == sequenceMotion)
            {
                return;
            }

            var process = System.Diagnostics.Process.GetProcessById(processId.Value);

            if (null == process)
            {
                return;
            }

            var startTime = GetTimeStopwatch();

            BotEngine.WinApi.User32.SetForegroundWindow(process.MainWindowHandle);

            var PreviousForegroundWindowHandle = BotEngine.WinApi.User32.GetForegroundWindow();

            if (PreviousForegroundWindowHandle != process.MainWindowHandle)
            {
                Thread.Sleep(100);
                PreviousForegroundWindowHandle = BotEngine.WinApi.User32.GetForegroundWindow();
                if (PreviousForegroundWindowHandle != process.MainWindowHandle)
                {
                    return;
                }
            }

            var motor = new WindowMotor(process.MainWindowHandle);

            var listMotionResult = new List <Bot.MotionResult>();

            foreach (var motion in sequenceMotion.EmptyIfNull())
            {
                var motionResult = motor.ActSequenceMotion(motion.MotionParam.AsSequenceMotion(memoryMeasurement?.Value));

                listMotionResult.Add(new Bot.MotionResult
                {
                    Id      = motion.Id,
                    Success = motionResult?.Success ?? false,
                });
            }

            BotStepLastMotionResult = new PropertyGenTimespanInt64 <Bot.MotionResult[]>(listMotionResult.ToArray(), startTime, GetTimeStopwatch());
        }
コード例 #15
0
        void LicenseClientExchange()
        {
            lock (LicenseClientLock)
            {
                var Time = Bib3.Glob.StopwatchZaitMiliSictInt();

                var LicenseClientExchangeStartedLastAge = Time - LicenseClientExchangeStartedLastTime;

                if (LicenseClientExchangeStartedLastAge < LicenseClientExchangeDistanceMin)
                {
                    return;
                }

                if (null == LicenseClient)
                {
                    LicenseClient = new PropertyGenTimespanInt64 <LicenseClient>(new LicenseClient(), Time, Time);

                    SensorServerDispatcher = new SimpleSensorServerDispatcher()
                    {
                        LicenseClient    = LicenseClient.Value,
                        SensorAppManager = SensorAppManager,
                    };
                }

                LicenseClient.Value.ServerAddress = LicenseClientConfigControl?.ApiVersionAddress();

                var EveOnlineClientProcessId = this.EveOnlineClientProcessId;

                LicenseClientExchangeStartedLastTime = Time;

                Task.Run(() =>
                {
                    var LicenseClient = this.LicenseClient;

                    if (null == LicenseClient?.Value)
                    {
                        return;
                    }

                    LicenseClient.Value.Timeout = 4000;

                    SensorServerDispatcher.Exchange(
                        EveOnlineClientProcessId,
                        RequestedMeasurementTime ?? Int64.MaxValue,
                        CallbackMeasurementMemoryNew);
                });
            }
        }
コード例 #16
0
ファイル: ExeMain.xaml.cs プロジェクト: josevill00/guy
        BrowserProcessCreation BrowserProcessCreate(string reason)
        {
            var creation = new BrowserProcessCreation(AppInterface, Dispatcher.Invoke(BrowserProcessConfigCreate), BrowserStartUrl)
            {
                Reason = reason,
            };

            BrowserProcessCreationLast = new PropertyGenTimespanInt64 <BrowserProcessCreation>(creation, Bib3.Glob.StopwatchZaitMiliSictInt());

            LogEntryWrite(new LogEntry
            {
                BrowserProcessCreated = creation,
            });

            return(creation);
        }
コード例 #17
0
        private void BotMotion(
            FromProcessMeasurement <IMemoryMeasurement> memoryMeasurement,
            IEnumerable <MotionRecommendation> sequenceMotion)
        {
            var processId = memoryMeasurement?.ProcessId;

            if (!processId.HasValue || null == sequenceMotion)
            {
                return;
            }

            var process = Process.GetProcessById(processId.Value);

            if (null == process)
            {
                return;
            }

            var startTime = GetTimeStopwatch();

            var motor = new WindowMotor(process.MainWindowHandle);

            var listMotionResult = new List <MotionResult>();

            foreach (var motion in sequenceMotion.EmptyIfNull())
            {
                var motionResult =
                    motor.ActSequenceMotion(motion.MotionParam.AsSequenceMotion(memoryMeasurement?.Value));

                listMotionResult.Add(new MotionResult
                {
                    Id      = motion.Id,
                    Success = motionResult?.Success ?? false
                });
            }

            BotStepLastMotionResult =
                new PropertyGenTimespanInt64 <MotionResult[]>(listMotionResult.ToArray(), startTime, GetTimeStopwatch());

            Thread.Sleep(FromMotionToMeasurementDelayMilli);
        }
コード例 #18
0
ファイル: Haupt.xaml.cs プロジェクト: sUmcont/Optimat.EO
        private void MemoryMeasurementSimulationEnableButton_Drop(object sender, DragEventArgs e)
        {
            Bib3.FCL.GBS.Extension.CatchNaacMessageBoxException(() =>
            {
                var filePathAndContent = e?.LaadeMengeDataiInhaltAusDropFileDrop()?.FirstOrDefault();

                var fileContentUTF8 = Encoding.UTF8.GetString(filePathAndContent?.Value);

                var setRoot = Bib3.RefNezDiferenz.Extension.ListeWurzelDeserialisiireVonJson(fileContentUTF8);

                var root = setRoot?.FirstOrDefault();

                var memoryMeasurement =
                    root as Sanderling.Interface.MemoryStruct.IMemoryMeasurement ??
                    (root as FromProcessMeasurement <Sanderling.Interface.MemoryStruct.IMemoryMeasurement>)?.Value;

                MemoryMeasurementSimulationValue = new PropertyGenTimespanInt64 <Sanderling.Interface.MemoryStruct.IMemoryMeasurement>(memoryMeasurement, Bib3.Glob.StopwatchZaitMiliSictInt());
            });

            MemoryMeasurementSimulationUIUpdate();
        }
コード例 #19
0
ファイル: Entity.cs プロジェクト: theroadninja/Sanderling
        public void Accumulate(
            PropertyGenTimespanInt64 <AccumulatedT> instant,
            SharedT other = default(SharedT))
        {
            if (null == instant)
            {
                return;
            }

            ++AccumulatedCount;

            HistoryListStep.Enqueue(instant);
            HistoryListStep.ListeKürzeBegin(HistoryLengthMax);

            LastInstant = instant;

            if (!object.Equals(default(AccumulatedT), instant.Value))
            {
                NotDefaultLastInstant = instant;
            }

            Accumulated(instant, other);
        }
コード例 #20
0
ファイル: LicenseClient.cs プロジェクト: Fulborg/A-Bot
        public PropertyGenTimespanInt64 <HttpExchangeReport <FromClientToServerMessage, FromServerToClientMessage> > ExchangePayload(FromClientToServerMessage request)
        {
            request.ProofOfWork = AuthRequest.ProofOfWorkConstruct(4000);
            PropertyGenTimespanInt64 <HttpExchangeReport <AuthRequest, AuthResponse> > exchangeAuthLast = ExchangeAuthLast;

            request.SessionId = ((exchangeAuthLast == null) ? null : exchangeAuthLast.Value?.Response?.SessionId);
            return(ExchangePayloadLast = HttpExchangeLocked <FromClientToServerMessage, FromServerToClientMessage>("payload", request, deflate: true));
        }
コード例 #21
0
 static public string RenderBotStepToUIText(this PropertyGenTimespanInt64 <BotStepResult> stepResultAtTimeMilli) =>
 null == stepResultAtTimeMilli ? null :
 TimeAgeMilliToUIText(Bot.Bot.GetTimeMilli() - stepResultAtTimeMilli?.Begin) +
 Environment.NewLine +
 RenderBotStepToUIText(stepResultAtTimeMilli.Value);
コード例 #22
0
ファイル: Entity.cs プロジェクト: theroadninja/Sanderling
 virtual protected void Accumulated(
     PropertyGenTimespanInt64 <AccumulatedT> instant,
     SharedT shared)
 {
 }
コード例 #23
0
ファイル: Haupt.xaml.cs プロジェクト: sUmcont/Optimat.EO
 private void MemoryMeasurementSimulationDisableButton_Click(object sender, RoutedEventArgs e)
 {
     MemoryMeasurementSimulationValue = null;
     MemoryMeasurementSimulationUIUpdate();
 }
コード例 #24
0
 public ExchangeReport Exchange(LicenseClientConfig licenseClientConfig, int?skipIfNotNeededForSessionKeepAliveSafetyMarginMilli)
 {
     lock (@lock)
     {
         PropertyGenTimespanInt64 <HttpExchangeReport <AuthRequest, AuthResponse> > authExchange = null;
         PropertyGenTimespanInt64 <HttpExchangeReport <FromClientToServerMessage, FromServerToClientMessage> > propertyGenTimespanInt = null;
         LicenseClientConfig obj = licenseClientConfig ?? LicenseClientConfig;
         licenseClientConfig = obj;
         LicenseClientConfig = obj;
         LicenseClient licenseClient = LicenseClient ?? (LicenseClient = new LicenseClient());
         if (licenseClientConfig != null)
         {
             licenseClient.ServerAddress = licenseClientConfig?.ApiVersionAddress;
             licenseClient.Request       = licenseClientConfig?.Request;
         }
         if (SessionContinue)
         {
             IRateLimitStateInt exchangePayloadRateLimit = ExchangePayloadRateLimit;
             long timeMilli = GetTimeMilli();
             var  obj2      = licenseClient?.ExchangeAuthLast?.Value?.Response?.RequestTimeDistanceMaxMilli -
                              skipIfNotNeededForSessionKeepAliveSafetyMarginMilli;
             if (!exchangePayloadRateLimit.AttemptPass(timeMilli, Math.Max(1000, obj2 ?? 0)))
             {
                 return(null);
             }
             object obj3;
             if (licenseClient == null)
             {
                 obj3 = null;
             }
             else
             {
                 PropertyGenTimespanInt64 <HttpExchangeReport <AuthRequest, AuthResponse> > exchangeAuthLast2 = licenseClient.ExchangeAuthLast;
                 obj3 = exchangeAuthLast2?.Value?.Response?.SessionId;
             }
             string sessionId = (string)obj3;
             FromClientToServerMessage request = new FromClientToServerMessage
             {
                 SessionId = sessionId,
                 Interface = InterfaceAppManager?.ToServer(),
                 Time      = GetTimeMilli()
             };
             propertyGenTimespanInt = licenseClient?.ExchangePayload(request);
             FromServerToClientMessage fromServerToClientMessage = propertyGenTimespanInt?.Value?.Response;
             if (fromServerToClientMessage != null)
             {
                 InterfaceAppManager?.FromServer(fromServerToClientMessage.Interface);
             }
         }
         else if (licenseClient?.AuthCompleted ?? false)
         {
             long?obj4;
             if (licenseClient == null)
             {
                 obj4 = null;
             }
             else
             {
                 PropertyGenTimespanInt64 <HttpExchangeReport <AuthRequest, AuthResponse> > exchangeAuthLast3 = licenseClient.ExchangeAuthLast;
                 obj4 = ((exchangeAuthLast3 != null) ? new long?(exchangeAuthLast3.End) : null);
             }
             long?num = obj4;
             PropertyGenTimespanInt64 <InterfaceAppManager> interfaceAppManagerAtTime = InterfaceAppManagerAtTime;
             if (!(num < ((interfaceAppManagerAtTime != null) ? new long?(interfaceAppManagerAtTime.Begin) : null)))
             {
                 InterfaceAppManagerAtTime = new PropertyGenTimespanInt64 <InterfaceAppManager>(new InterfaceAppManager(InterfaceAppDomainSetupType, InterfaceAppDomainSetupTypeLoadFromMainModule), GetTimeMilli());
             }
         }
         else
         {
             int    exchangeAuthTimeDistanceMinMilli = ExchangeAuthTimeDistanceMinMilli;
             object authResponse;
             if (licenseClient == null)
             {
                 authResponse = null;
             }
             else
             {
                 PropertyGenTimespanInt64 <HttpExchangeReport <AuthRequest, AuthResponse> > exchangeAuthLast4 = licenseClient.ExchangeAuthLast;
                 authResponse = ((exchangeAuthLast4 == null) ? null : exchangeAuthLast4.Value?.Response);
             }
             int num2 = Math.Max(exchangeAuthTimeDistanceMinMilli, AuthTimeDistanceRecommended((AuthResponse)authResponse) ?? 0);
             if (ExchangeAuthRateLimit.AttemptPass(GetTimeMilli(), num2))
             {
                 authExchange = licenseClient?.ExchangeAuth();
             }
         }
         return(new ExchangeReport
         {
             AuthExchange = authExchange,
             PayloadExchange = propertyGenTimespanInt
         });
     }
 }
コード例 #25
0
        public BotStepReport Step(
            Int64 time,
            BrowserService browserService)
        {
            lock (Lock)
            {
                var report = new BotStepReport();

                var timeCal = report.StartTimeCal = DateTime.Now;

                var breakDurationRemaining = BreakEndTimeCal - DateTime.Now;

                try
                {
                    if (0 < breakDurationRemaining?.TotalSeconds)
                    {
                        return(report);
                    }

                    report.BreakActiveNot = true;

                    var browser = browserService?.BrowserProcessCreatedLast?.Invoke()?.BrowserConnection;

                    var browserDocument = browser?.Document?.Result;

                    report.browserDocumentAvailable = null != browserDocument;

                    if (null == browserDocument)
                    {
                        throw new ArgumentNullException("browserDocument");
                    }

                    {
                        //	GetElementFromXPath(Dom.VillageDropDownControllerXPath) failed for some users without reason being discovered yet.
                        //	Test whether GetElementFromXPath yields any element at all.

                        var anyElementFromGetElementFromXPath = browserDocument?.GetElementFromXPath("//*");

                        if (null == anyElementFromGetElementFromXPath)
                        {
                            throw new ArgumentNullException("AnyElementFromGetElementFromXPath");
                        }
                    }

                    report.AnyElementFromGetElementFromXPathSucceeded = true;

                    var villageDropDownControllerElem =
                        browserDocument.GetElementFromXPath(Dom.VillageDropDownControllerXPath)?.Result;

                    if (null == villageDropDownControllerElem)
                    {
                        throw new ArgumentNullException("VillageDropDownControllerElem");
                    }

                    var villageDropDownInfoEval =
                        villageDropDownControllerElem?.JavascriptCallFunction(Dom.JsGetInfoFromVillageDropDownControllerElement);

                    var villageDropDownInfoEvalError = villageDropDownInfoEval?.Error?.ToString();

                    if (0 < villageDropDownInfoEvalError?.Length)
                    {
                        throw new Exception("VillageDropDownInfoEvalError: " + villageDropDownInfoEvalError);
                    }

                    var villageDropDownInfoSerial = villageDropDownInfoEval?.Result?.value?.ToString();

                    if (null == villageDropDownInfoSerial)
                    {
                        throw new ArgumentNullException("VillageDropDownInfoSerial");
                    }

                    var villageDropDownInfo = villageDropDownInfoSerial?.FromVillageDropDownControllerInfoParse();

                    report.VillageSelected = villageDropDownInfo?.selectedVillageData;

                    var villageSelectedId = report.VillageSelected?.villageId;

                    if (null == villageSelectedId)
                    {
                        throw new ArgumentNullException("VillageSelectedId");
                    }

                    var locationHref = browserDocument?.locationHref;

                    if (locationHref.RegexMatchSuccessIgnoreCase(TwStruct.Static.GameEnterUrlIndicatorRegexPattern))
                    {
                        GameEnterUrlMeasurementLast = new PropertyGenTimespanInt64 <string>(locationHref, time);
                    }

                    var farmEnableSetVillageId = report.FarmEnableSetVillageId =
                        villageDropDownInfo?.villagesParsed?.Values()?.Select(village => village?.data?.villageId)?.WhereNotNullSelectValue()
                        ?.Where(villageId => !(time - UnitCountSufficientNotLastTimeFromVillageId?.TryGetValueNullable(villageId) < 1000 * 60 * 3))
                        ?.ToArray();

                    var reportHandlingPlannedFromReportId = new Func <Int64, ReportHandlingPlanned>(reportId => this.ReportHandlingPlannedFromReportId(reportId, farmEnableSetVillageId));

                    var listReportToOpen =
                        (ReportSummaryFromId.Values?.OrderByDescending(reportSummary => reportSummary?.time_created ?? 0))
                        ?.Where(reportSummary => reportHandlingPlannedFromReportId(reportSummary.id ?? -1)?.Open ?? false)
                        ?.ToArray();

                    var measurementOutgoingUnitsLastTime =
                        MeasurementOutgoingUnitsLastFromVillageId.TryGetValueOrDefault(villageSelectedId.Value)?.End;

                    var measurementOutgoingUnitsLastAge = time - measurementOutgoingUnitsLastTime;

                    var measureListReportDue = !(measurementOutgoingUnitsLastTime < MeasurementListReportLastTime);

                    if (!(measurementOutgoingUnitsLastAge < 1000 * 60) &&
                        (!(measurementOutgoingUnitsLastAge < 1000 * 60 * 5) ||
                         (!(0 < listReportToOpen?.Length) && !measureListReportDue)))
                    {
                        var unitListControllerElem =
                            browserDocument.GetElementFromXPath(Dom.ListUnitControllerXPath)?.Result;

                        var measureListMovement = report.MeasureListMovement = new BotStepMeasureListMovement();

                        if (null != unitListControllerElem)
                        {
                            var unitListInfoEval =
                                unitListControllerElem.JavascriptCallFunction(Dom.JsGetInfoFromUnitListControllerElement);

                            var unitListInfoEvalSerial = unitListInfoEval?.Result?.value?.ToString();

                            if (null == unitListInfoEvalSerial)
                            {
                                throw new ArgumentNullException("UnitListInfoEvalSerial");
                            }

                            var unitListInfo = unitListInfoEvalSerial.DeserializeFromString <UnitListControllerInfo>();

                            var villageId = unitListInfo?.villageId;

                            if (villageId.HasValue && null != unitListInfo?.outgoingArmies)
                            {
                                MeasurementOutgoingUnitsLastFromVillageId[villageId.Value] =
                                    new Bib3.PropertyGenTimespanInt64 <UnitListControllerCommand[]>(unitListInfo?.outgoingArmies, time);
                            }

                            return(report);
                        }

                        var openUnitsElem = browserDocument.GetElementFromXPath(Dom.openUnitsXPath)?.Result;

                        if (null == openUnitsElem)
                        {
                            throw new ArgumentNullException("openUnitsElem");
                        }

                        openUnitsElem.click();

                        return(report);
                    }

                    var openListReportElem = browserDocument.GetElementFromXPath(Dom.openListReportXPath)?.Result;

                    if (measureListReportDue)
                    {
                        var measureListReport = report.MeasureListReport = new BotStepMeasureListReportSummary
                        {
                            ListReportCount = 0,
                        };

                        var listPageAttempt = measureListReport.ListPageAttempt = new List <BotStepMeasureListReportSummaryPageAttempt>();

                        var listReportControllerElem =
                            browserDocument.GetElementFromXPath(Dom.ListReportControllerXPath)?.Result;

                        if (null != listReportControllerElem)
                        {
                            var paginationSetButtonSetLimit =
                                browserDocument?.GetListElementFromXPath(Dom.ListReportControllerXPath + Dom.PaginationSetLimitButtonXPath)?.Result?.ToArray();

                            var paginationButtonSetLimit =
                                paginationSetButtonSetLimit?.OrderByDescending(button => button?.innerText?.RegexMatchIfSuccess(@"\d+")?.Value?.TryParseInt() ?? -1)?.FirstOrDefault();

                            paginationButtonSetLimit?.click();
                            Thread.Sleep(1444);

                            while (true)
                            {
                                var pageAttemptFailedCount = listPageAttempt.Count(page => !(page.Success ?? false));

                                if (1 < pageAttemptFailedCount)
                                {
                                    break;
                                }

                                var pageAttemptReport = new BotStepMeasureListReportSummaryPageAttempt();

                                var pageIndex =
                                    (listPageAttempt
                                     .Where(pageAttempt => pageAttempt?.Success ?? false)
                                     .Select(pageAttempt => pageAttempt.PageIndex)
                                     .WhereNotDefault()
                                     .LastOrDefault() + 1) ?? 0;

                                pageAttemptReport.PageIndex = pageIndex;

                                try
                                {
                                    if (0 < pageIndex)
                                    {
                                        var pageId = pageIndex + 1;

                                        var loadPageButton =
                                            browserDocument?.GetElementFromXPath(Dom.ListReportControllerXPath + Dom.ReportPageLoadButtonXPathFromPageId(pageId))?.Result;

                                        loadPageButton?.click();

                                        Thread.Sleep(1444);
                                    }

                                    var listReportSummaryEval =
                                        listReportControllerElem.JavascriptCallFunction(Dom.JsGetListReportSummaryFromControllerElement);

                                    var listReportSummarySerial = listReportSummaryEval?.Result?.value?.ToString();

                                    var listReportSummary =
                                        listReportSummarySerial.DeserializeFromString <ReportListReportSummary[]>()
                                        ?.OrderBy(reportSummary => reportSummary?.time_created)
                                        ?.ToArray();

                                    pageAttemptReport.ReportIdNewCount         =
                                        pageAttemptReport.ReportIdOverlapCount = 0;

                                    foreach (var reportSummary in listReportSummary.EmptyIfNull())
                                    {
                                        var reportId = reportSummary.id;

                                        if (!(reportId.HasValue && reportSummary.IsGoodEnoughForMemorization()))
                                        {
                                            continue;
                                        }

                                        if (ReportSummaryFromId.ContainsKey(reportId.Value))
                                        {
                                            ++pageAttemptReport.ReportIdOverlapCount;
                                            continue;
                                        }

                                        ++pageAttemptReport.ReportIdNewCount;

                                        ReportSummaryFromId[reportId.Value] = reportSummary;
                                    }

                                    measureListReport.ListReportCount += pageAttemptReport.ReportIdNewCount;

                                    pageAttemptReport.Success = 0 < pageAttemptReport.ReportIdNewCount;
                                }
                                finally
                                {
                                    listPageAttempt.Add(pageAttemptReport);

                                    if (pageAttemptReport.Success ?? false)
                                    {
                                        ++pageIndex;
                                    }
                                }
                            }

                            MeasurementListReportLastTime = time;

                            return(report);
                        }

                        openListReportElem.click();

                        return(report);
                    }

                    foreach (var reportSummary in listReportToOpen.EmptyIfNull())
                    {
                        var reportId = reportSummary.id;

                        var reportHandlingPlanned = reportHandlingPlannedFromReportId(reportId ?? -1);

                        var openReportReport = report.OpenReport = new BotStepOpenReport
                        {
                            ReportSummary         = reportSummary,
                            ReportHandlingPlanned = reportHandlingPlanned,
                        };

                        var listReportControllerElem =
                            browserDocument.GetElementFromXPath(Dom.ListReportControllerXPath)?.Result;

                        if (null == listReportControllerElem)
                        {
                            openReportReport.OpenListReport = true;

                            openListReportElem?.click();

                            Thread.Sleep(1111);

                            listReportControllerElem =
                                browserDocument.GetElementFromXPath(Dom.ListReportControllerXPath)?.Result;
                        }

                        if (null == listReportControllerElem)
                        {
                            throw new ArgumentNullException("ListReportControllerElem");
                        }

                        listReportControllerElem.JavascriptCallFunction(reportId.Value.JsFunctionShowReportWithIdOnReportsController());

                        Thread.Sleep(1111);

                        var reportControllerElem =
                            browserDocument.GetElementFromXPath(Dom.ReportControllerXPath)?.Result;

                        var reportDetailEval =
                            reportControllerElem.JavascriptCallFunction(Dom.JsGetReportDetailFromControllerElement);

                        var reportDetailSerial = reportDetailEval?.Result?.value?.ToString();

                        var reportDetail =
                            reportDetailSerial.DeserializeFromString <ReportControllerReport>();

                        ReportDetailFromId[reportId.Value] = new PropertyGenTimespanInt64 <ReportControllerReport>(reportDetail, time);

                        openReportReport.ReportHandlingPlanned = reportHandlingPlanned =
                            reportHandlingPlannedFromReportId(reportId.Value);

                        var reportAttUnits =
                            reportDetail?.ReportAttack?.attUnits?.SubsetPropertyInt()?.ToArray();

                        if (!(0 < reportAttUnits?.Values()?.Sum()))
                        {
                            return(report);
                        }

                        var targetVillageId = reportHandlingPlanned?.TargetVillageId;

                        if (!(reportHandlingPlanned?.AttackAgain ?? false) || !targetVillageId.HasValue)
                        {
                            return(report);
                        }

                        var attackAgainReport = openReportReport.AttackAgain = new BotStepAttack();

                        var attVillageId = reportDetail?.ReportAttack?.attVillageId;

                        if (!(report.VillageSelected?.villageId == attVillageId))
                        {
                            attackAgainReport.VillageSwitchTo = attVillageId;
                            villageDropDownControllerElem.JavascriptCallFunction(Dom.JsFunctionVillageSelectOnVillageDropDownController(attVillageId.Value));
                            return(report);
                        }

                        reportControllerElem.JavascriptCallFunction(Dom.JsAttackAgainFromReportControllerElement);

                        Thread.Sleep(1111);

                        var modalCustomArmyControllerElem =
                            browserDocument.GetElementFromXPath(Dom.ModalCustomArmyControllerXPath)?.Result;

                        var availableUnitsSerial =
                            modalCustomArmyControllerElem.JavascriptCallFunction(Dom.JsGetAvailableUnitsFromControllerElement)?.Result?.value?.ToString();

                        var availableUnits =
                            attackAgainReport.AvailableUnits = availableUnitsSerial.DeserializeFromString <JObject>().SubsetPropertyInt()?.ToArray();

                        var lackingUnits = attackAgainReport.LackingUnits =
                            reportAttUnits
                            ?.Select(attUnit => new KeyValuePair <string, Int64>(
                                         attUnit.Key, attUnit.Value - availableUnits?.ValueFromKeyOrDefault(attUnit.Key) ?? 0))
                            ?.Where(lacking => 0 < lacking.Value)
                            ?.OrderByDescending(lacking => lacking.Value)
                            ?.ToArray();

                        if (0 < lackingUnits?.Values()?.Sum())
                        {
                            UnitCountSufficientNotLastTimeFromVillageId[villageSelectedId.Value] = time;
                            return(report);
                        }

                        attackAgainReport.UnitCountSufficient = true;

                        var sendArmyButtonElement = browserDocument.GetElementFromXPath("//*[@ng-click=\"sendArmy('attack')\"]")?.Result;

                        ArmySentLastTimeFromTargetVillageId[targetVillageId.Value] = time;
                        Statistics.AttackSentCount++;

                        sendArmyButtonElement?.click();

                        attackAgainReport.Completed = true;

                        return(report);
                    }

                    report.BreakStartReason = "no more reports to open";
                }
                catch (Exception Exception)
                {
                    report.Exception = Exception;
                }
                finally
                {
                    if (report.BreakActiveNot)
                    {
                        report.BrowserUsageFailed = !report.AnyElementFromGetElementFromXPathSucceeded;
                        ListStepBrowserUsageFailed.Enqueue(new PropertyGenTimespanInt64 <bool>(report.BrowserUsageFailed, time));
                        ListStepBrowserUsageFailed.ListeKürzeBegin(ListStepBrowserUsageFailedRetainLength);
                    }

                    var browserAge = DateTime.Now - browserService?.BrowserProcessCreatedLast?.Invoke()?.StartTimeCal;

                    var requestBrowserProcessStartByAge =
                        !(browserAge?.TotalSeconds < BrowserRestartAge) &&
                        breakDurationRemaining?.TotalSeconds < 15;

                    report.RequestBrowserProcessStart =
                        ListStepBrowserUsageFailedRetainLength <= ListStepBrowserUsageFailed.Count &&
                        ListStepBrowserUsageFailed.Count / 2 < ListStepBrowserUsageFailed.Count(failed => failed.Value) ?
                        "Browser usage failed" : (requestBrowserProcessStartByAge ? ("browser age " + browserAge?.ToString()) : null);

                    Statistics.ReportSummaryReadCount = ReportSummaryFromId.Count;
                    Statistics.ReportDetailReadCount  = ReportDetailFromId.Count;
                    Statistics.AttackSentVillageCount = ArmySentLastTimeFromTargetVillageId.Count;

                    report.Statistics = Statistics;

                    if (0 < report.BreakStartReason?.Length)
                    {
                        MeasurementOutgoingUnitsLastFromVillageId.Clear();
                        UnitCountSufficientNotLastTimeFromVillageId.Clear();

                        report.BreakEndTimeCal = BreakEndTimeCal = DateTime.Now + TimeSpan.FromSeconds(
                            new Random((int)Bib3.Glob.StopwatchZaitMiliSictInt()).Next().SictUmgebrocen(BreakDurationMin, BreakDurationMax));
                    }

                    var stepLastReportAtTime = new PropertyGenTimespanInt64 <BotStepReport>(report, time);

                    StepLastReport = stepLastReportAtTime;

                    if (report.BreakActiveNot)
                    {
                        StepBeforeBreakLastReport = stepLastReportAtTime;
                        Statistics.BotStepCount++;
                    }
                }

                return(report);
            }
        }
コード例 #26
0
ファイル: App.Interface.cs プロジェクト: grachevko/Sanderling
		void LicenseClientExchange()
		{
			lock (LicenseClientLock)
			{
				var Time = Bib3.Glob.StopwatchZaitMiliSictInt();

				var LicenseClientExchangeStartedLastAge = Time - LicenseClientExchangeStartedLastTime;

				if (LicenseClientExchangeStartedLastAge < LicenseClientExchangeDistanceMin)
				{
					return;
				}

				if (null == LicenseClient)
				{
					LicenseClient = new PropertyGenTimespanInt64<LicenseClient>(new LicenseClient(), Time, Time);

					SensorServerDispatcher = new SimpleSensorServerDispatcher()
					{
						LicenseClient = LicenseClient.Value,
						SensorAppManager = SensorAppManager,
					};
				}

				LicenseClient.Value.ServerAddress = LicenseClientConfigControl?.ApiVersionAddress();

				var EveOnlineClientProcessId = this.EveOnlineClientProcessId;

				LicenseClientExchangeStartedLastTime = Time;

				Task.Run(() =>
				{
					var LicenseClient = this.LicenseClient;

					if (null == LicenseClient?.Value)
					{
						return;
					}

					LicenseClient.Value.Timeout = 4000;

					SensorServerDispatcher.Exchange(
						EveOnlineClientProcessId,
						RequestedMeasurementTime ?? Int64.MaxValue,
						CallbackMeasurementMemoryNew);
				});
			}
		}