public void GetCommonResponse()
        {
            int    status    = 200;
            string code      = "ThisIsCode";
            string message   = "ThisIsMessage";
            string requestId = "ThisIsRequestId";

            // Mock RegionIds
            ISet <String> regionIds = new HashSet <String>();

            regionIds.Add("cn-hangzhou");

            // Mock productDomains
            List <ProductDomain> productDomains = new List <ProductDomain>()
            {
            };
            ProductDomain productDomain = new ProductDomain("Ess", "ess.aliyuncs.com");

            productDomains.Add(productDomain);

            // Mock endpoint
            Endpoint endpoint = new Endpoint("cn-hangzhou", regionIds, productDomains);

            // Mock endpoints
            List <Endpoint> endpoints = new List <Endpoint>()
            {
            };

            endpoints.Add(endpoint);

            // Mock response
            HttpResponse response = new HttpResponse();

            byte[] content = Encoding.GetEncoding("UTF-8").GetBytes("{\"Code\":\"" + code + "\",\"Message\":\"" + message + "\",\"RequestId\":\"" + requestId + "\"}");
            response.ContentType = FormatType.JSON;
            response.Content     = content;
            response.Status      = status;

            // Mock credential
            Credential credential = new Credential(AKID, AKSE);

            // Mock Profile
            var mockProfile = new Mock <IClientProfile>();

            mockProfile.Setup(foo => foo.GetCredential()).Returns(credential);
            IClientProfile profile = mockProfile.Object;

            // Mock DefaultAcsClient
            var mockDefaultAcsClient = new Mock <DefaultAcsClient>(profile);

            mockDefaultAcsClient.Setup(foo => foo.DoAction(
                                           It.IsAny <AcsRequest <CommonResponse> >(),
                                           It.IsAny <bool>(),
                                           It.IsAny <int>(),
                                           It.IsAny <string>(),
                                           It.IsAny <AlibabaCloudCredentials>(),
                                           It.IsAny <Signer>(),
                                           It.IsAny <FormatType>(),
                                           It.IsAny <List <Endpoint> >()
                                           )).Returns(response);
            DefaultAcsClient instance = mockDefaultAcsClient.Object;
            // DefaultAcsClient instance = this.MockDefaultAcsClient();

            // Mock AcsResquest
            CommonRequest request = new CommonRequest();

            request.RegionId             = "cn-hangzhou";
            request.Product              = "Ess";
            request.LocationProduct      = "ess";
            request.LocationEndpointType = "openAPI";

            CommonResponse commonResponse = instance.GetCommonResponse(request);

            Assert.NotNull(commonResponse);
            Assert.Equal(200, commonResponse.HttpStatus);
        }
        //LegalScreen = 0,
        //AvatarSelection = 1,
        //AccountCreation = 2,
        //PokemonCapture = 3,
        //NameSelection = 4,
        //PokemonBerry = 5,
        //UseItem = 6,
        //FirstTimeExperienceComplete = 7,
        //PokestopTutorial = 8,
        //GymTutorial = 9

        /*
         * On first connection before any move you must do 0,1,3,4 & 7
         *
         */

        public bool MarkTutorialAsDone(TutorialState State, PokemonGo.RocketAPI.Client client, PokemonId firstPokemon = PokemonId.Charmander)
        {
            MarkTutorialCompleteResponse TutorialResponse = null;
            SetAvatarResponse            AvatarResponse   = null;
            bool SuccessFlag = false;

            switch (State)
            {
            /* 0 */
            case TutorialState.LegalScreen:
                RandomHelper.RandomSleep(4000, 7000);
                TutorialResponse = client.Misc.AceptLegalScreen().Result;
                client.Player.GetPlayer();
                SuccessFlag = TutorialResponse.Success;
                break;

            /* 1 */
            case TutorialState.AvatarSelection:
                // All MAX values will be used to get a random value
                // RandormNumber never returns max value.
                AvatarSettings.Load();
                var playerAvatar = new PlayerAvatar();
                playerAvatar.Skin     = AvatarSettings.skin == 4 ? RandomHelper.RandomNumber(0, 4) : AvatarSettings.skin;
                playerAvatar.Backpack = AvatarSettings.backpack == 3 ? RandomHelper.RandomNumber(0, 3) : AvatarSettings.backpack;
                playerAvatar.Eyes     = AvatarSettings.eyes == 4 ? RandomHelper.RandomNumber(0, 4) : AvatarSettings.eyes;
                playerAvatar.Shoes    = AvatarSettings.shoes == 3 ? RandomHelper.RandomNumber(0, 3) : AvatarSettings.shoes;
                playerAvatar.Hat      = AvatarSettings.hat == 3 ? RandomHelper.RandomNumber(0, 3) : AvatarSettings.hat;
                playerAvatar.Pants    = AvatarSettings.pants == 3 ? RandomHelper.RandomNumber(0, 3) : AvatarSettings.pants;
                playerAvatar.Hair     = AvatarSettings.hair == 6 ? RandomHelper.RandomNumber(0, 6) : AvatarSettings.hair;
                playerAvatar.Shirt    = AvatarSettings.shirt == 3 ? RandomHelper.RandomNumber(0, 3) : AvatarSettings.shirt;
                playerAvatar.Avatar   = AvatarSettings.Gender == 2 ? RandomHelper.RandomNumber(0, 2) : AvatarSettings.Gender;

                // TODO Add this new configurable avatar options to tutorial configuration window
                // currently will use 0 for all value not loaded
                //playerAvatar.AvatarNecklace = AvatarSettings.necklace = ...
                //playerAvatar.AvatarBelt = AvatarSettings.belt == ...
                //playerAvatar.AvatarSocks = AvatarSettings.socks == ...
                //playerAvatar.AvatarGloves = AvatarSettings.gloves == ...
                //playerAvatar.AvatarGlasses = AvatarSettings.glasses == ...

                RandomHelper.RandomSleep(8000, 14500);
                AvatarResponse = client.Player.SetAvatar(playerAvatar).Result;

                client.Player.ListAvatarCustomizations(playerAvatar.Avatar == 0 ? PlayerAvatarType.PlayerAvatarMale:PlayerAvatarType.PlayerAvatarFemale, null, null, 0, 0);

                RandomHelper.RandomSleep(1000, 1700);
                TutorialResponse = client.Misc.MarkTutorialComplete(new RepeatedField <TutorialState>()
                {
                    TutorialState.AvatarSelection
                }).Result;

                client.Player.GetPlayerProfile();
                SuccessFlag = TutorialResponse.Success;
                break;

            /* 2 */
            case TutorialState.AccountCreation:
                // Need to check how to implement, meanwhile...
                TutorialResponse = client.Misc.MarkTutorialComplete(new RepeatedField <TutorialState>()
                {
                    TutorialState.AccountCreation
                }).Result;
                SuccessFlag = TutorialResponse.Success;
                break;

            /* 3 */
            case TutorialState.PokemonCapture:
                if (AvatarSettings.starter == PokemonId.Missingno)
                {
                    // Selected random pokemon
                    var rnd = new Random().Next(0, 4);
                    switch (rnd)
                    {
                    case 0:
                        AvatarSettings.starter = PokemonId.Bulbasaur;
                        break;

                    case 1:
                        AvatarSettings.starter = PokemonId.Charmander;
                        break;

                    case 2:
                        AvatarSettings.starter = PokemonId.Squirtle;
                        break;

                    default:
                        AvatarSettings.starter = PokemonId.Pikachu;
                        break;
                    }
                }

                /*
                 * batch.getDownloadURLs([
                 *  this.state.assets.getFullIdFromId('1a3c2816-65fa-4b97-90eb-0b301c064b7a'),
                 *  this.state.assets.getFullIdFromId('aa8f7687-a022-4773-b900-3a8c170e9aea'),
                 *  this.state.assets.getFullIdFromId('e89109b0-9a54-40fe-8431-12f7826c8194'),
                 * ]);*/
                CommonRequest.GetDownloadUrlsRequest(client);     // Not fully implemented, you need to send the ID's

                RandomHelper.RandomSleep(10000, 13000);
                var encounterResponse = client.Encounter.EncounterTutorialComplete(AvatarSettings.starter);
                if (encounterResponse.Result == EncounterTutorialCompleteResponse.Types.Result.ErrorInvalidPokemon)
                {
                    encounterResponse = client.Encounter.EncounterTutorialComplete(PokemonId.Charmander);
                }
                SuccessFlag = (encounterResponse.Result == EncounterTutorialCompleteResponse.Types.Result.Success);

                client.Player.GetPlayerProfile();

                // TODO: check if this is really needed or the "TutorialState.PokemonCapture" flag is done by the above call.
                if (!client.Player.PlayerResponse.PlayerData.TutorialState.Contains(TutorialState.PokemonCapture))
                {
                    TutorialResponse = client.Misc.MarkTutorialComplete(new RepeatedField <TutorialState>()
                    {
                        TutorialState.PokemonCapture
                    }).Result;
                    SuccessFlag = TutorialResponse.Success;
                }
                break;

            /* 4 */
            case TutorialState.NameSelection:
                SuccessFlag = false;
                string suggestedName = client.Username;
                ClaimCodenameResponse.Types.Status status = ClaimCodenameResponse.Types.Status.CodenameNotValid;
                for (int i = 0; i < 100; i++)
                {
                    suggestedName = AvatarSettings.nicknamePrefix + suggestedName + (i == 0 ? "" : i.ToString()) + AvatarSettings.nicknameSufix;
                    RandomHelper.RandomSleep(7000, 13500);
                    status = client.Misc.ClaimCodename(suggestedName).Status;
                    if (status == ClaimCodenameResponse.Types.Status.Success)
                    {
                        break;
                    }
                    else if (status == ClaimCodenameResponse.Types.Status.CurrentOwner || status == ClaimCodenameResponse.Types.Status.CodenameChangeNotAllowed)
                    {
                        break;
                    }
                }

                client.Player.GetPlayer();

                TutorialResponse = client.Misc.MarkTutorialComplete(new RepeatedField <TutorialState>()
                {
                    TutorialState.NameSelection
                }).Result;
                SuccessFlag = TutorialResponse.Success;

                break;

            /* 5 */
            case TutorialState.PokemonBerry:
                TutorialResponse = client.Misc.MarkTutorialComplete(new RepeatedField <TutorialState>()
                {
                    TutorialState.PokemonBerry
                }).Result;
                SuccessFlag = TutorialResponse.Success;
                break;

            /* 6 */
            case TutorialState.UseItem:
                // Need to check how to implement, meanwhile...
                TutorialResponse = client.Misc.MarkTutorialComplete(new RepeatedField <TutorialState>()
                {
                    TutorialState.UseItem
                }).Result;
                SuccessFlag = TutorialResponse.Success;
                break;

            /* 7 */
            case TutorialState.FirstTimeExperienceComplete:
                RandomHelper.RandomSleep(3500, 6000);
                TutorialResponse = client.Misc.MarkTutorialComplete(new RepeatedField <TutorialState>()
                {
                    TutorialState.FirstTimeExperienceComplete
                }).Result;
                SuccessFlag = TutorialResponse.Success;
                break;

            /* 8 */
            case TutorialState.PokestopTutorial:
                TutorialResponse = client.Misc.MarkTutorialComplete(new RepeatedField <TutorialState>()
                {
                    TutorialState.PokestopTutorial
                }).Result;
                SuccessFlag = TutorialResponse.Success;
                break;

            /* 9 */
            case TutorialState.GymTutorial:
                TutorialResponse = client.Misc.MarkTutorialComplete(new RepeatedField <TutorialState>()
                {
                    TutorialState.GymTutorial
                }).Result;
                SuccessFlag = TutorialResponse.Success;
                break;
            }

            if (SuccessFlag)
            {
                Logger.Info("[TUTORIAL] " + (int)State + "- " + State + " set DONE");
            }
            else
            {
                Logger.Warning("[TUTORIAL] " + (int)State + "- " + Enum.GetName(typeof(EncounterTutorialCompleteResponse.Types), State) + " set FAILED. Reason: " + TutorialResponse.Success);
            }

            RandomHelper.RandomDelay(5000).Wait();
            return(SuccessFlag);
        }
 protected override object Evaluate(CommonRequest request)
 {
     return(new TheIssueOfUrbanManagement());
 }
示例#4
0
        protected override object Evaluate(CommonRequest request)
        {
            if (string.IsNullOrEmpty(request?.data))
            {
                return new CommonOutputT <string>
                       {
                           success = false,
                           data    = null,
                           message = "参数错误"
                       }
            }
            ;
            var user = JsonConvert.DeserializeObject <UserInformation>(request.data);

            if (string.IsNullOrEmpty(user?.UILoginName))
            {
                return(new CommonOutputT <string>
                {
                    success = false,
                    data = null,
                    message = "参数错误"
                });
            }
            if (!CheckMultiLogin(user.UILoginName))
            {
                return(new CommonOutputT <string>
                {
                    success = false,
                    data = null,
                    message = "非法登录"
                });
            }
            if (Sessions.ContainsKey(nameof(UserInformation)) && Sessions.ContainsKey("token"))
            {
                return(new CommonOutputT <string>
                {
                    success = true,
                    data = Sessions["token"].ToString(),
                    message = "登录成功"
                });
            }
            using (var c = new DefaultContext())
            {
                var one = c.UserInformation.FirstOrDefault(u => u.UILoginName == user.UILoginName);
                if (one == null)
                {
                    FailedLogin(user.UILoginName);
                    return(new CommonOutputT <string>
                    {
                        success = false,
                        data = null,
                        message = "请注册"
                    });
                }
                if (one.UIPassword != user.UIPassword)
                {
                    FailedLogin(user.UILoginName);
                    return(new CommonOutputT <string>
                    {
                        success = false,
                        data = null,
                        message = "非法的用户凭据"
                    });
                }

                var token = Guid.NewGuid().ToString();
                BuildSession(token, one);
                using (var ctx = new DefaultContext())
                {
                    ctx.LoginRecord.Add(new LoginRecord
                    {
                        CreateBy      = "LoginEvaluator",
                        UpdateBy      = "LoginEvaluator",
                        CreateOn      = DateTime.Now,
                        UpdateOn      = DateTime.Now,
                        id            = Guid.NewGuid().ToString(),
                        IsDeleted     = 0,
                        LRLoginName   = user.UILoginName,
                        LRLoginTime   = DateTime.Now,
                        TransactionID = Guid.NewGuid().ToString(),
                        VersionNo     = 0
                    });
                    ctx.SaveChanges();
                }
                return(new CommonOutputT <string>
                {
                    success = true,
                    data = token,
                    message = "登录成功"
                });
            }
        }
    }
示例#5
0
        /// <summary>
        /// 处理请求FD业务API
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public CommonResponse CommonHttpHandle(CommonRequest request)
        {
            var res = new CommonResponse("0");

            res.Ips = request.Ips;
            try
            {
                if (!HttpWhiteListHepler.Instance.Validate(request.Endpoint, request.HttpMethod))
                {
                    res.Code = ErrorCode.REQUESTNOTSUPPORTED_ERROR;
                    return(res);
                }
                var fusionDirector = FusionDirectorWorker.Instance.FindByIP(request.Ips[0]);
                if (fusionDirector == null)
                {
                    res.Code = ErrorCode.NET_FD_NOFOUND;
                    return(res);
                }
                // IsCrtExist();
                // TrustCertificate();
                SetCertificateValidation();
                HttpResponseMessage response = new HttpResponseMessage();

                using (HttpClient httpClient = new HttpClient())
                {
                    byte[] bytes   = System.Text.Encoding.UTF8.GetBytes(fusionDirector.LoginAccount + ":" + fusionDirector.LoginPwd);
                    var    authStr = "Basic " + Convert.ToBase64String(bytes);
                    httpClient.DefaultRequestHeaders.Add("Authorization", authStr);
                    var remoteUrl = "https://" + fusionDirector.HostIP + ":" + fusionDirector.Port + "/redfish/v1" + request.Endpoint;
                    switch (request.HttpMethod)
                    {
                    case "GET":
                        response = httpClient.GetAsync(remoteUrl).Result;
                        break;

                    case "POST":
                        var content = new StringContent(request.Data.ToString(), Encoding.UTF8, "application/json");
                        response = httpClient.PostAsync(remoteUrl, content).Result;
                        break;

                    case "DELETE":
                        response = httpClient.DeleteAsync(remoteUrl).Result;
                        break;

                    case "PATCH":
                        var requestMessage = new HttpRequestMessage(new HttpMethod("PATCH"), remoteUrl)
                        {
                            Content = new StringContent(request.Data.ToString(), Encoding.UTF8, "application/json")
                        };
                        response = httpClient.SendAsync(requestMessage).Result;
                        break;

                    default:
                        res.Code = ErrorCode.REQUESTNOTSUPPORTED_ERROR;
                        return(res);
                    }
                    var statusCode = ((int)response.StatusCode).ToString();
                    var task       = response.Headers.FirstOrDefault(x => x.Key == "Task").Value;
                    if (task != null)
                    {
                        res.Headers = new
                        {
                            Task = task
                        };
                    }
                    res.Description = response.Headers.Date.Value.LocalDateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    var resultStr = response.Content.ReadAsStringAsync().Result;
                    LogUtil.HWLogger.API.Info("URL:" + remoteUrl + "HttpMethod:" + request.HttpMethod + " Api Result:" + resultStr);
                    JsonSerializerSettings setting = new JsonSerializerSettings();
                    JsonConvert.DefaultSettings = new Func <JsonSerializerSettings>(() =>
                    {
                        //日期类型默认格式化处理
                        setting.DateFormatHandling = DateFormatHandling.IsoDateFormat;
                        //setting.DateFormatString = "yyyy-MM-ddTHH:mm:ssz";
                        return(setting);
                    });
                    res.Data.Add(new Item()
                    {
                        Ip   = fusionDirector.HostIP,
                        Code = statusCode,
                        Data = JsonConvert.DeserializeObject(resultStr, setting)
                    });
                    if (!statusCode.StartsWith("2"))
                    {
                        throw new Exception(statusCode);
                    }
                }
            }
            catch (CryptographicException ex)
            {
                LogUtil.HWLogger.UI.Error("CommonHttpHandle failed: cert error:", ex);
                res.Code        = ErrorCode.CERT_ERROR;
                res.Description = ex.Message;
            }
            catch (AggregateException ex)
            {
                LogUtil.HWLogger.API.Error("CommonHttpHandle Error", ex);
                throw HandleException(ex);
            }
            catch (Exception ex)
            {
                LogUtil.HWLogger.API.Error("CommonHttpHandle Error", ex);
                res.Code        = "-1";
                res.Description = ex.Message;
            }
            return(res);
        }
 protected override object Evaluate(CommonRequest request)
 {
     return(new SanitationProblemTracking());
 }
示例#7
0
        public bool VerifyFavourTicket(string ticketCode, string memLoginID)
        {
            var ticket = CommonRequest.ApiVerifyFavourTicket(memLoginID, ticketCode);

            return(ticket != null);
        }
 protected override object Evaluate(CommonRequest request)
 {
     return(new QuestionReturnVisit());
 }
 protected override object Evaluate(CommonRequest request)
 {
     return(new HumanFlowMonitoring());
 }
示例#10
0
        public object Get(decimal shopingCartPrice)
        {
            var result = CommonRequest.ApiGetPromotionByPrice(shopingCartPrice);

            return(result);
        }
示例#11
0
 public async Task FireRequestBlockTwo()
 {
     await FireRequestBlock(CommonRequest.GetGetAssetDigestMessageRequest(Client)).ConfigureAwait(false);
 }
示例#12
0
 protected override object Evaluate(CommonRequest request)
 {
     return(new OrganizationalManagement());
 }
示例#13
0
        public override Task <SearchResponse> Search(CommonRequest request, ServerCallContext context)
        {
            var searchText = request.SearchText.Trim();

            var response = new SearchResponse
            {
                Id        = 0,
                Title     = "no data found",
                SarchText = searchText,
                Url       = "/notfound",
                Status    = "no"
            };

            //search block by hash
            try
            {
                var block = Blockchain.GetBlockByHash(searchText);
                if (block is not null && block.Hash is not null)
                {
                    response = new SearchResponse
                    {
                        Id        = 1,
                        Title     = "search found block by hash",
                        SarchText = searchText,
                        Url       = "/block/hash/" + searchText,
                        Status    = "ok"
                    };
                    return(Task.FromResult(response));
                }
            }
            catch
            {
                Console.WriteLine("no block by hash");
            }

            // search block by height
            try
            {
                var height = int.Parse(searchText);
                var block  = Blockchain.GetBlockByHeight(height);
                if (block is not null && block.Hash is not null)
                {
                    response = new SearchResponse
                    {
                        Id        = 2,
                        Title     = "search found block by height",
                        SarchText = searchText,
                        Url       = "/block/height/" + searchText,
                        Status    = "ok"
                    };
                    return(Task.FromResult(response));
                }
            }
            catch
            {
                Console.WriteLine("no block by height");
            }


            //search tnxs by hash
            try
            {
                var txn = Transaction.GetTxnByHash(searchText);
                if (txn is not null && txn.Hash is not null)
                {
                    response = new SearchResponse
                    {
                        Id        = 3,
                        Title     = "Found transaction",
                        SarchText = searchText,
                        Url       = "/txn/" + searchText,
                        Status    = "ok"
                    };
                    return(Task.FromResult(response));
                }
            }
            catch
            {
                Console.WriteLine("no txn by hash");
            }


            // get Account
            try
            {
                // 1. get one transaction by address
                var txn = Transaction.GetOneTxnByAddress(searchText);
                if (txn is not null && txn.Hash is not null)
                {
                    response = new SearchResponse
                    {
                        Id        = 4,
                        Title     = "search found one address ",
                        SarchText = searchText,
                        Url       = "/address/" + searchText,
                        Status    = "ok"
                    };
                    return(Task.FromResult(response));
                }
            }
            catch
            {
                Console.WriteLine("Error when search by account");
            }


            return(Task.FromResult(response));
        }
示例#14
0
             DownloadSettingsResponse, GetBuddyWalkedResponse> > GetMapObjects(bool forceRequest = false)
        {
            // In case we did last _minSecondsBetweenMapCalls before, we return the cached response
            if (_lastGetMapRequest.AddSeconds(_minSecondsBetweenMapCalls).Ticks > DateTime.UtcNow.Ticks && !forceRequest)
            {
                return(_cachedGetMapResponse);
            }

            #region Messages

            var getMapObjectsMessage = new GetMapObjectsMessage
            {
                CellId           = { S2Helper.GetNearbyCellIds(Client.CurrentLongitude, Client.CurrentLatitude) },
                SinceTimestampMs = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
                Latitude         = Client.CurrentLatitude,
                Longitude        = Client.CurrentLongitude
            };

            var getHatchedEggsMessage = new GetHatchedEggsMessage();

            var getInventoryMessage = new GetInventoryMessage
            {
                LastTimestampMs = Client.InventoryLastUpdateTimestamp
            };

            var checkAwardedBadgesMessage = new CheckAwardedBadgesMessage();

            var downloadSettingsMessage = new DownloadSettingsMessage
            {
                Hash = Client.SettingsHash
            };

            #endregion

            var getMapObjectsRequest = new Request
            {
                RequestType    = RequestType.GetMapObjects,
                RequestMessage = getMapObjectsMessage.ToByteString()
            };

            var request = GetRequestBuilder().GetRequestEnvelope(CommonRequest.FillRequest(getMapObjectsRequest, Client));

            Tuple <GetMapObjectsResponse, CheckChallengeResponse, GetHatchedEggsResponse, GetInventoryResponse, CheckAwardedBadgesResponse, DownloadSettingsResponse, GetBuddyWalkedResponse> _getMapObjectsResponse =
                await
                PostProtoPayload
                <Request, GetMapObjectsResponse, CheckChallengeResponse, GetHatchedEggsResponse, GetInventoryResponse,
                 CheckAwardedBadgesResponse, DownloadSettingsResponse, GetBuddyWalkedResponse>(request).ConfigureAwait(false);

            GetInventoryResponse getInventoryResponse = _getMapObjectsResponse.Item4;
            CommonRequest.ProcessGetInventoryResponse(Client, getInventoryResponse);

            DownloadSettingsResponse downloadSettingsResponse = _getMapObjectsResponse.Item6;
            CommonRequest.ProcessDownloadSettingsResponse(Client, downloadSettingsResponse);

            CheckChallengeResponse checkChallengeResponse = _getMapObjectsResponse.Item2;
            CommonRequest.ProcessCheckChallengeResponse(Client, checkChallengeResponse);

            // Here we refresh last time this request was done and cache
            _lastGetMapRequest    = DateTime.UtcNow;
            _cachedGetMapResponse = _getMapObjectsResponse;

            return(_getMapObjectsResponse);
        }
示例#15
0
        private static async Task <ResponseEnvelope> PerformRemoteProcedureCall <TRequest>(this System.Net.Http.HttpClient client,
                                                                                           Client apiClient,
                                                                                           RequestEnvelope requestEnvelope) where TRequest : IMessage <TRequest>
        {
            // Check killswitch from url before making API calls.
            if (!apiClient.Settings.UseLegacyAPI)
            {
                if (apiClient.CheckCurrentVersionOutdated())
                {
                    throw new MinimumClientVersionException(apiClient.CurrentApiEmulationVersion, apiClient.MinimumClientVersion);
                }
            }

            //Encode payload and put in envelop, then send
            var data   = requestEnvelope.ToByteString();
            var result = await client.PostAsync(apiClient.ApiUrl, new ByteArrayContent(data.ToByteArray())).ConfigureAwait(false);

            //Decode message
            var responseData = await result.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

            var codedStream = new CodedInputStream(responseData);
            ResponseEnvelope serverResponse = new ResponseEnvelope();

            serverResponse.MergeFrom(codedStream);

            // Process Platform8Response
            CommonRequest.ProcessPlatform8Response(apiClient, serverResponse);

            if (!string.IsNullOrEmpty(serverResponse.ApiUrl))
            {
                apiClient.ApiUrl = "https://" + serverResponse.ApiUrl + "/rpc";
            }

            if (serverResponse.AuthTicket != null)
            {
                if (serverResponse.AuthTicket.ExpireTimestampMs > (ulong)Utils.GetTime(true))
                {
                    apiClient.AuthTicket = serverResponse.AuthTicket;
                }
                else
                {
                    // Expired auth ticket.
                    apiClient.AuthTicket = null;
                }
            }

            switch (serverResponse.StatusCode)
            {
            case ResponseEnvelope.Types.StatusCode.InvalidAuthToken:
                await apiClient.RequestBuilder.RegenerateRequestEnvelopeWithNewAccessToken(requestEnvelope).ConfigureAwait(false);

                return(await PerformRemoteProcedureCall <TRequest>(client, apiClient, requestEnvelope).ConfigureAwait(false));

            case ResponseEnvelope.Types.StatusCode.Redirect:
                // 53 means that the api_endpoint was not correctly set, should be at this point, though, so redo the request
                return(await PerformRemoteProcedureCall <TRequest>(client, apiClient, requestEnvelope).ConfigureAwait(false));

            case ResponseEnvelope.Types.StatusCode.BadRequest:
                // Your account may be banned! please try from the official client.
                throw new APIBadRequestException("BAD REQUEST \r\n" + JsonConvert.SerializeObject(requestEnvelope));

            case ResponseEnvelope.Types.StatusCode.Unknown:
                break;

            case ResponseEnvelope.Types.StatusCode.Ok:
                break;

            case ResponseEnvelope.Types.StatusCode.OkRpcUrlInResponse:
                break;

            case ResponseEnvelope.Types.StatusCode.InvalidRequest:
                break;

            case ResponseEnvelope.Types.StatusCode.InvalidPlatformRequest:
                break;

            case ResponseEnvelope.Types.StatusCode.SessionInvalidated:
                throw new SessionInvalidatedException("SESSION INVALIDATED EXCEPTION");

            default:
                throw new ArgumentOutOfRangeException();
            }
            return(serverResponse);
        }
示例#16
0
        /// <summary>
        /// 发送短信验证码
        /// </summary>
        /// <param name="moblile"></param>
        /// <param name="type"></param>
        /// <param name="data">默认#拼接参数</param>
        /// <returns></returns>
        public StateCode GetSMSCode(string moblile, int type, string data = "")
        {
            string code    = StringHelper.CreateRandomCode(4);
            bool   is_test = ConfigManage.AppSettings <bool>("AppSettings:IsTestSendSms");

            if (is_test)
            {
                code = "8888";
            }

            StateCode state = SendSms(moblile, code, type);

            if (StateCode.State_200 == state && !is_test)
            {
                IClientProfile   profile = DefaultProfile.GetProfile("default", ConfigManage.AppSettings <string>("AppSettings:SMSKey"), ConfigManage.AppSettings <string>("AppSettings:SMSKeySecret"));
                DefaultAcsClient client  = new DefaultAcsClient(profile);
                CommonRequest    request = new CommonRequest();
                request.Method  = MethodType.POST;
                request.Domain  = "dysmsapi.aliyuncs.com";
                request.Version = "2017-05-25";
                request.Action  = "SendSms";
                request.AddQueryParameters("PhoneNumbers", moblile);
                request.AddQueryParameters("SignName", "微狐信息科技");
                // request.Protocol = ProtocolType.HTTP;

                if (type == (int)SendSmsType.Register)
                {
                    //注册
                    request.AddQueryParameters("TemplateCode", ConfigManage.AppSettings <string>("AppSettings:SMSTmpRegister"));
                    request.AddQueryParameters("TemplateParam", JsonConvert.SerializeObject(new { code, product = "微狐信息科技" }));
                }
                else if (type == (int)SendSmsType.ForgetPsw)
                {
                    //忘记密码
                    request.AddQueryParameters("TemplateCode", ConfigManage.AppSettings <string>("AppSettings:SMSTmpForgetPsw"));
                    request.AddQueryParameters("TemplateParam", JsonConvert.SerializeObject(new { code, product = "微狐信息科技" }));
                }
                else if (type == (int)SendSmsType.BindNewMobile)
                {
                    //绑定新手机号
                    request.AddQueryParameters("TemplateCode", ConfigManage.AppSettings <string>("AppSettings:SMSTmpBindNewMob"));
                    request.AddQueryParameters("TemplateParam", JsonConvert.SerializeObject(new { code, product = "微狐信息科技" }));
                }

                try
                {
                    CommonResponse response = client.GetCommonResponse(request);
                    Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
                }
                catch (ServerException e)
                {
                    state = StateCode.State_500;
                    Console.WriteLine(e);
                }
                catch (ClientException e)
                {
                    state = StateCode.State_500;
                    Console.WriteLine(e);
                }
            }

            return(state);
        }
示例#17
0
 protected override object Evaluate(CommonRequest request)
 {
     return(new ThePartyStyleAndCleanGovernment());
 }
示例#18
0
 protected override object Evaluate(CommonRequest request)
 {
     return(new SocialSecurityManagement());
 }
示例#19
0
 public VerifyChallengeResponse VerifyChallenge(string token)
 {
     return(PostProtoPayload <Request, VerifyChallengeResponse>(RequestType.VerifyChallenge, CommonRequest.GetVerifyChallenge(token)));
 }
示例#20
0
 public GameTwist_End_To_End_Steps(Settings settings, SeleniumContext _seleniumContext, CommonRequest _commonRequest, SeleniumCommonPg _seleniumCommonPg)
 {
     _settings        = settings;
     seleniumContext  = _seleniumContext;
     commonRequest    = _commonRequest;
     seleniumCommonPg = _seleniumCommonPg;
 }
示例#21
0
 protected override object Evaluate(CommonRequest request)
 {
     return(new SanitationIssue());
 }
示例#22
0
 protected override object Evaluate(CommonRequest request)
 {
     return(new LatestNews());
 }
示例#23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="force">For thread wait until next api call available to use</param>
        /// <param name="updateCache">Allow update cache, in some case we don't want update cache, snipe pokemon is an example</param>
        /// <returns></returns>
        public async Task <GetMapObjectsResponse> GetMapObjects(bool force = false, bool updateCache = true)
        {
            if (force)
            {
                var t = GetMilisSecondUntilRefreshMapAvail();
                //wait until get map available
                if (t > 0)
                {
                    await Task.Delay(t).ConfigureAwait(false);
                }
            }
            if (!CanRefreshMap())
            {
                return(force ? await GetMapObjects(force, updateCache).ConfigureAwait(false) : LastGetMapObjectResponse);

                // If we cannot refresh the map, return the cached response.
            }

            var lat = Client.CurrentLatitude;
            var lon = Client.CurrentLongitude;

            var getMapObjectsMessage = new GetMapObjectsMessage
            {
                CellId           = { S2Helper.GetNearbyCellIds(lon, lat) },
                SinceTimestampMs = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
                Latitude         = lat,
                Longitude        = lon
            };

            var getMapObjectsRequest = new Request
            {
                RequestType    = RequestType.GetMapObjects,
                RequestMessage = getMapObjectsMessage.ToByteString()
            };

            var request = await GetRequestBuilder().GetRequestEnvelope(CommonRequest.FillRequest(getMapObjectsRequest, Client)).ConfigureAwait(false);

            Tuple <GetMapObjectsResponse, CheckChallengeResponse, GetHatchedEggsResponse, GetHoloInventoryResponse, CheckAwardedBadgesResponse, DownloadSettingsResponse, GetBuddyWalkedResponse> response =
                await
                PostProtoPayload
                <Request, GetMapObjectsResponse, CheckChallengeResponse, GetHatchedEggsResponse, GetHoloInventoryResponse,
                 CheckAwardedBadgesResponse, DownloadSettingsResponse, GetBuddyWalkedResponse>(request).ConfigureAwait(false);

            GetHoloInventoryResponse getHoloInventoryResponse = response.Item4;

            CommonRequest.ProcessGetHoloInventoryResponse(Client, getHoloInventoryResponse);

            DownloadSettingsResponse downloadSettingsResponse = response.Item6;

            CommonRequest.ProcessDownloadSettingsResponse(Client, downloadSettingsResponse);

            CheckChallengeResponse checkChallengeResponse = response.Item2;

            CommonRequest.ProcessCheckChallengeResponse(Client, checkChallengeResponse);

            LastRpcMapObjectsRequestMs = Util.TimeUtil.GetCurrentTimestampInMilliseconds();

            var numCells                  = response.Item1.MapCells.Count;
            var numCellsWithForts         = response.Item1.MapCells.Count(x => x.Forts.Count > 0);
            var numCellsWithNearbyPokemon = response.Item1.MapCells.Count(x => x.NearbyPokemons.Count > 0);
            var numCellsWithWildPokemon   = response.Item1.MapCells.Count(x => x.WildPokemons.Count > 0);

            // Only cache good responses
            if (updateCache &&
                numCells > 0 &&
                (numCellsWithForts > 0 ||
                 numCellsWithNearbyPokemon > 0 ||
                 numCellsWithWildPokemon > 0))
            {
                // Good map response since we got at least a fort or pokemon in our cells.
                LastGetMapObjectResponse           = response.Item1;
                LastGeoCoordinateMapObjectsRequest = new GeoCoordinate(lat, lon);
            }

            if (updateCache && LastGetMapObjectResponse == null)
            {
                LastGetMapObjectResponse = response.Item1;
            }

            return(response.Item1);
        }
        protected override object Evaluate(CommonRequest request)
        {
            if (Sessions.Count == 0)
            {
                return(new
                {
                    success = false,
                    message = "请登录"
                });
            }
            var user = Sessions[nameof(UserInformation)] as UserInformation;

            if (user == null)
            {
                return(new
                {
                    success = false,
                    message = "请登录"
                });
            }
            using (var ctx = new XiangXiEntities())
            {
                var s      = request.data;
                var entity = JsonConvert.DeserializeObject <TheIssueOfUrbanManagement>(s);
                // 行级排他锁开始
                var transactionId = Guid.NewGuid().ToString();
                var isnew         = entity.id == null;
                if (!isnew)
                {
                    var one = ctx.TheIssueOfUrbanManagement.FirstOrDefault(p => p.id == entity.id);
                    if (one == null)
                    {
                        return new
                               {
                                   success = false,
                                   message = "编辑错误,未找到ID"
                               }
                    }
                    ;
                    if (one.VersionNo != entity.VersionNo)
                    {
                        return new
                               {
                                   success = false,
                                   message = "发生数据写冲突"
                               }
                    }
                    ;
                    one.VersionNo++;
                    one.TransactionID = transactionId;
                    ctx.TheIssueOfUrbanManagement.AddOrUpdate(one);
                    ctx.SaveChanges();
                    entity.VersionNo = one.VersionNo;
                }

                entity.id       = entity.id ?? Guid.NewGuid().ToString();
                entity.CreateBy = entity.CreateBy ?? user?.UILoginName ?? "未登录用户";
                entity.UpdateBy = user?.UILoginName ?? "未登录用户";
                var now = DateTime.Now;
                entity.CreateOn      = entity.CreateOn ?? now;
                entity.TransactionID = transactionId;
                entity.UpdateOn      = now;
                entity.IsDeleted     = 0;
                ctx.TheIssueOfUrbanManagement.AddOrUpdate(entity);
                ctx.SaveChanges();
                // 行级排他锁结束
                return(new
                {
                    success = true,
                    message = "操作成功"
                });
            }
        }
    }
示例#25
0
 protected override object Evaluate(CommonRequest request)
 {
     return(new GridManagement());
 }
示例#26
0
        private async Task FireRequestBlock(Request request)
        {
            var requests = CommonRequest.FillRequest(request, Client);

            var serverRequest  = GetRequestBuilder().GetRequestEnvelope(requests, true);
            var serverResponse = await PostProto <Request>(serverRequest);

            if (!string.IsNullOrEmpty(serverResponse.ApiUrl))
            {
                Client.ApiUrl = "https://" + serverResponse.ApiUrl + "/rpc";
            }

            if (serverResponse.AuthTicket != null)
            {
                Client.AuthTicket = serverResponse.AuthTicket;
            }

            switch (serverResponse.StatusCode)
            {
            case ResponseEnvelope.Types.StatusCode.InvalidAuthToken:
                Client.AuthToken = null;
                throw new AccessTokenExpiredException();

            case ResponseEnvelope.Types.StatusCode.Redirect:
                // 53 means that the api_endpoint was not correctly set, should be at this point, though, so redo the request
                await FireRequestBlock(request);

                return;

            case ResponseEnvelope.Types.StatusCode.BadRequest:
                // Your account may be banned! please try from the official client.
                throw new LoginFailedException("Your account may be banned! please try from the official client.");

            case ResponseEnvelope.Types.StatusCode.Unknown:
                break;

            case ResponseEnvelope.Types.StatusCode.Ok:
                break;

            case ResponseEnvelope.Types.StatusCode.OkRpcUrlInResponse:
                break;

            case ResponseEnvelope.Types.StatusCode.InvalidRequest:
                break;

            case ResponseEnvelope.Types.StatusCode.InvalidPlatformRequest:
                break;

            case ResponseEnvelope.Types.StatusCode.SessionInvalidated:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            var responses = serverResponse.Returns;

            if (responses != null)
            {
                var checkChallengeResponse = new CheckChallengeResponse();
                if (2 <= responses.Count)
                {
                    checkChallengeResponse.MergeFrom(responses[1]);

                    CommonRequest.ProcessCheckChallengeResponse(Client, checkChallengeResponse);
                }

                var getInventoryResponse = new GetInventoryResponse();
                if (4 <= responses.Count)
                {
                    getInventoryResponse.MergeFrom(responses[3]);

                    CommonRequest.ProcessGetInventoryResponse(Client, getInventoryResponse);
                }

                var downloadSettingsResponse = new DownloadSettingsResponse();
                if (6 <= responses.Count)
                {
                    downloadSettingsResponse.MergeFrom(responses[5]);

                    CommonRequest.ProcessDownloadSettingsResponse(Client, downloadSettingsResponse);
                }
            }
        }
示例#27
0
        //[RestAuthenticationAttribute]
        public IEnumerable <SearchTagDataObject> getUserSearchTagsList(CommonRequest request)
        {
            BLUtils utils = new BLUtils();

            return(utils.GetCompanyVehicleTags(5, 10290, true, false).DataTableToList <SearchTagDataObject>());
        }
示例#28
0
 public async Task FireRequestBlockTwo()
 {
     await FireRequestBlock(CommonRequest.GetGetAssetDigestMessageRequest(Client));
 }
示例#29
0
        //[RestAuthenticationAttribute]
        public IEnumerable <GenericLookupTableItemInfo> getUserFuelSuppliers(CommonRequest request)
        {
            BLLookupTable lookupTable = new BLLookupTable();

            return(lookupTable.GetCompanyGenericTable(53, 5));
        }
 public void Instance()
 {
     CommonRequest instance = new CommonRequest();
 }
 public void SendVibration(string fromJid, string toJid)
 {
     if (ValidationUtil.Jid(fromJid) && ValidationUtil.Jid(toJid))
     {
         CommonRequest request = new CommonRequest();
         request.from_jid = fromJid;
         request.to_jid = toJid;
         request.type = 1;
         this.connection.Send(PacketType.COMMON, request);
     }
 }