Example #1
0
        public async Task <GameItem[]> GetPlayerItems(Profile profile)
        {
            List <GameItem> items = new List <GameItem>();

            var request = new RestRequest("kitties?owner_wallet_address=" + profile.ID + "&limit=10&offset=0", Method.GET);

            request.AddDecompressionMethod(DecompressionMethods.None);
            var response = await Client.ExecuteTaskAsync(request).ConfigureAwait(false);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                System.Diagnostics.Debug.Fail("unable to get kitties by owner from " + Client.BaseUrl + ", Request: " + "kitties?owner_wallet_address=" + profile.ID + "&limit=1&offset=0" + ", response: " + response.ErrorMessage + " StatusCode: " + response.StatusCode);
                return(null);
            }

            UserKittiesAPIResult userKitties = JsonConvert.DeserializeObject <UserKittiesAPIResult>(response.Content);

            if (userKitties == null)
            {
                System.Diagnostics.Debug.Fail("unable to parse user kitties response from " + Client.BaseUrl + ", Content: " + response.Content);
                return(null);
            }

            foreach (var kitty in userKitties.kitties)
            {
                if (await validateOwnerOnBC(profile, kitty.id))
                {
                    GameItem gi = new GameItem(Game, "CK", new Metadata(profile.ID, ulong.Parse(kitty.id), "CK_DNA"));
                    gi.State = Encoding.Unicode.GetBytes(kitty.image_url);//this should be dna!
                }
            }

            return(items.ToArray());
        }
Example #2
0
        /// <inheritdoc/>
        public async Task <byte[]> DownloadBytesAsync(byte[] address)
        {
            if (downloadClient != null)
            {
                byte[] bytes = new byte[digestSize + 2];
                bytes[0] = fnCode;
                bytes[1] = digestSize;
                address.CopyTo(bytes, 2);
                //Encoding.Unicode.GetBytes(address, 0, address.Length, bytes, 2);

                string      hash            = Base58CheckEncoding.EncodePlain(bytes);
                RestRequest downloadRequest = new RestRequest("/ipfs/" + hash, Method.GET);
                downloadRequest.AddDecompressionMethod(System.Net.DecompressionMethods.None);

                IRestResponse response = await downloadClient.ExecuteGetTaskAsync(downloadRequest);

                if (response.ErrorException != null)
                {
                    // TODO: throw some kind of custom exception on unsuccessful upload
                    throw new Exception();
                }

                return(response.RawBytes);
            }
            return(null);
        }
Example #3
0
        /// <summary>
        /// Initial Connection to REST API Server (Returns Account data informations when valid)
        /// </summary>
        /// <param name="httpauth">TODO</param>
        /// <returns></returns>
        public IRestResponse <AccountRoot> RequestAccount()
        {
            //Account URI
            _uri = _uriBuilder.BuildUri(RuntimeSettings.YamiStatic.SettingsEx.User).Uri;

            _client = new RestClient(_uri)
            {
                Authenticator    = new HttpBasicAuthenticator(_username, _password),
                Timeout          = (_restTimeout * 1000), //timeouts are in ms, but in config in seconds
                ReadWriteTimeout = (_restTimeout * 1000)
            };

            IRestRequest request = new RestRequest("", Method.POST);

            request.AddDecompressionMethod(_restCompressionLevel);
            IRestResponse <AccountRoot> response = _client.Execute <AccountRoot>(request);

            //When connection cannot be established HttpErrorCode 503 (and not default 0 code)
            if (response.StatusCode == 0)
            {
                response.StatusCode = HttpStatusCode.ServiceUnavailable;
            }
            //TODO: Response is OK, but invalid content (Okay Http response for example)

            _log.LogDebug("Got a RequestAccount response: {0},{1}", response.ResponseStatus, response.StatusCode);
            return(response);
        }
Example #4
0
        /// <summary>
        /// Requests Automated Passenger Counter Data over REST API
        /// </summary>
        /// <param name="httpauth"></param>
        public IRestResponse RequestApcData(string account, string type, DateTime date, string device)
        {
            //Excel Reporting is on other URI Namespace in REST API
            if (type == "application/vnd.ms-excel")
            {
                _uri = _uriBuilder.BuildUri(RuntimeSettings.YamiStatic.SettingsEx.Reports).Uri;
            }
            else
            {
                _uri = _uriBuilder.BuildUri(RuntimeSettings.YamiStatic.SettingsEx.Stops).Uri;
            }

            _client = new RestClient(_uri)
            {
                Authenticator    = new HttpBasicAuthenticator(_username, _password),
                Timeout          = (_restTimeout * 1000), //timeouts are in ms, but in config in seconds
                ReadWriteTimeout = (_restTimeout * 1000)
            };

            IRestRequest request = new RestRequest(account + "?vehicleId=" + device + "&opdate=" + date.ToString("yyyy-MM-dd"), Method.POST);

            request.AddDecompressionMethod(_restCompressionLevel);
            request.AddHeader("Accept", type); //ex. application/json, application/xml or text/csv

            IRestResponse response = _client.Execute(request);

            _log.LogDebug("Got a RequestApcData response: {0},{1},{2}", response.ResponseStatus, response.StatusCode);
            return(response);
        }
Example #5
0
        /// <summary>
        /// Performs a POST request on the specified path.
        /// </summary>
        /// <typeparam name="T">The type of object expected back.</typeparam>
        /// <param name="path">The path to post to.</param>
        /// <param name="body">The body contents to serialize and include.</param>
        /// <param name="isRawBody"><see langword="true" /> if the body should be interpereted as a pre-built JSON string, or <see langword="false" /> if it should be serialized.</param>
        /// <returns></returns>
        protected async Task <T> Post <T>(string path, object body, bool isRawBody = false) where T : class
        {
            var req = new RestRequest(path);

            // Bug in HA or RestSharp if Gzip is enabled, so disable it for now
            req.AddDecompressionMethod(DecompressionMethods.None);
            req.AddHeader("Accept-Encoding", "identity");

            if (body != null)
            {
                if (isRawBody)
                {
                    req.AddParameter("application/json", body.ToString(), ParameterType.RequestBody);
                }
                else
                {
                    req.AddParameter("application/json", JsonConvert.SerializeObject(body), ParameterType.RequestBody);
                }
            }
            var resp = await Client.ExecutePostAsync(req);

            if (!string.IsNullOrWhiteSpace(resp.Content) && (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.Created))
            {
                // Weird case for strings - return as-is
                if (typeof(T).IsAssignableFrom(typeof(string)))
                {
                    return(resp.Content as T);
                }

                return(JsonConvert.DeserializeObject <T>(resp.Content));
            }

            throw new Exception($"Unexpected response code {(int)resp.StatusCode} from Home Assistant API endpoint {path}.");
        }
Example #6
0
        /// <inheritdoc/>
        public async Task <byte[]> DownloadBytesAsync(byte[] address)
        {
            RestRequest downloadRequest = new RestRequest("/bzz:/" + address + "/file", Method.GET);

            downloadRequest.AddDecompressionMethod(System.Net.DecompressionMethods.None);
            return((await client.ExecuteGetTaskAsync <byte[]>(downloadRequest)).Data);
        }
Example #7
0
        private async Task ConnectToGameServer()
        {
            bool isNullOrEmpty = (Game.Url == null) || (Game.Url == "");

            if (!isNullOrEmpty && Uri.IsWellFormedUriString(Game.Url, UriKind.Absolute))
            {
                Client = new RestClient(Game.Url);
                Client.AutomaticDecompression = false;
                //setup a cookie container for automatic cookies handling
                Client.CookieContainer = new System.Net.CookieContainer();

                var request = new RestRequest("", Method.GET);
                request.AddDecompressionMethod(System.Net.DecompressionMethods.None);
                var response = await Client.ExecuteTaskAsync(request).ConfigureAwait(false);

                if (response.ErrorException != null)
                {
                    throw new HoardException(response.ErrorException.ToString());
                }
                return;
            }

            if (!isNullOrEmpty)
            {
                throw new HoardException($"Not a proper game url: {Game.Url}!");
            }
        }
Example #8
0
        /// <summary>
        /// Signin given user profile to the server. Must be done before calling endpoints protected by default challenge based authentication.
        /// </summary>
        /// <param name="profile">Profile ot be singed in</param>
        /// <returns></returns>
        public async Task Signin(Profile profile)
        {
            bool isNullOrEmpty = (Game.Url == null) || (Game.Url == "");

            if (!isNullOrEmpty && Uri.IsWellFormedUriString(Game.Url, UriKind.Absolute))
            {
                Client = new RestClient(Game.Url);
                Client.AutomaticDecompression = false;
                //setup a cookie container for automatic cookies handling
                Client.CookieContainer = new System.Net.CookieContainer();

                //handshake

                //1. GET challenge token
                var request = new RestRequest("authentication/login/", Method.GET);
                request.AddDecompressionMethod(System.Net.DecompressionMethods.None);
                var response = await Client.ExecuteTaskAsync(request).ConfigureAwait(false);

                if (response.ErrorException != null)
                {
                    throw new HoardException(response.ErrorException.ToString());
                }

                string challengeToken = response.Content;
                challengeToken = challengeToken.Substring(2);

                var nonce    = Eth.Utils.Mine(challengeToken, new BigInteger(1) << 496);
                var nonceHex = nonce.ToString("x");

                var    dataBytes = Encoding.ASCII.GetBytes(response.Content.Substring(2) + nonceHex);
                string sig       = await profile.SignMessage(dataBytes).ConfigureAwait(false);

                if (sig == null)
                {
                    throw new HoardException("Cannot sign challenge answer");
                }

                var data = new JObject();
                data.Add("token", response.Content);
                data.Add("nonce", nonceHex.EnsureHexPrefix());
                data.Add("address", profile.ID.ToString());
                data.Add("signature", sig);

                var responseLogin = await PostJson("authentication/login/", data);

                if (responseLogin.StatusCode != System.Net.HttpStatusCode.OK || responseLogin.Content != "Logged in")
                {
                    throw new HoardException($"Failed to log in with response: {responseLogin.Content}!");
                }
                return;
            }

            if (!isNullOrEmpty)
            {
                throw new HoardException($"Not a proper game url: {Game.Url}!");
            }
        }
Example #9
0
        private async Task <string> SendRequestPost(RestClient client, string method, object data)
        {
            var request = new RestRequest(method, Method.POST);

            request.AddDecompressionMethod(System.Net.DecompressionMethods.None);
            request.AddParameter("application/json", data.ToString(), ParameterType.RequestBody);
            var response = await client.ExecuteTaskAsync(request).ConfigureAwait(false);;

            return(response.Content);
        }
Example #10
0
        private async Task <string> GetJson(string url, object data)
        {
            var request = new RestRequest(url, Method.GET);

            request.AddDecompressionMethod(System.Net.DecompressionMethods.None);
            request.AddJsonBody(data);

            var response = await Client.ExecuteTaskAsync(request).ConfigureAwait(false);;

            return(response.Content);
        }
Example #11
0
        private static RestRequest RequestBuilder(string resource, Method method = Method.GET)
        {
            var request = new RestRequest(resource);

            request.AddHeader("androidVersion", "9");
            request.AddHeader("packageId", "41");
            request.AddHeader("channel", "developer-default");
            request.AddHeader("version", "3.0.0");
            request.AddHeader("deviceName", "Google Pixel 2 XL");
            request.AddHeader("platform", "android");
            request.AddHeader("Host", baseUrl);
            request.AddDecompressionMethod(DecompressionMethods.GZip);
            request.Method = method;
            return(request);
        }
Example #12
0
        /// <summary>
        /// Performs a DELETE request on the specified path.
        /// </summary>
        /// <param name="path">The relative API endpoint path.</param>
        protected async Task Delete(string path)
        {
            var req = new RestRequest(path, Method.DELETE);

            // Bug in HA or RestSharp if Gzip is enabled, so disable it for now
            req.AddDecompressionMethod(DecompressionMethods.None);
            req.AddHeader("Accept-Encoding", "identity");

            var resp = await Client.ExecuteAsync(req);

            if (!(resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.NoContent))
            {
                throw new Exception($"Unexpected response code {(int)resp.StatusCode} from Home Assistant API endpoint {path}.");
            }
        }
Example #13
0
        /// <inheritdoc/>
        public async Task <byte[]> UploadAsync(byte[] data)
        {
            RestRequest request = new RestRequest("/bzz:/", Method.POST);

            request.AddDecompressionMethod(System.Net.DecompressionMethods.None);
            request.AddFile("file", data, "file", "application/octet-stream");
            IRestResponse response = await client.ExecutePostTaskAsync(request);

            if (response.ErrorException != null)
            {
                // TODO: throw some kind of custom exception on unsuccessful upload
                throw new ApplicationException();
            }

            return(response.RawBytes);
        }
Example #14
0
        /// <inheritdoc/>
        public async Task <byte[]> UploadAsync(byte[] data)
        {
            if (uploadClient != null)
            {
                RestRequest request = new RestRequest("/api/v0/add", Method.POST);
                request.AddDecompressionMethod(System.Net.DecompressionMethods.None);
                request.AddFile("file", data, "file", "application/octet-stream");

                IRestResponse response = await uploadClient.ExecutePostTaskAsync(request);

                if (response.ErrorException != null)
                {
                    // TODO: throw some kind of custom exception on unsuccessful upload
                    throw new Exception();
                }

                string hash = JsonConvert.DeserializeObject <UploadResponse>(response.Content).Hash;
                return(Base58CheckEncoding.DecodePlain(hash).Skip(2).ToArray());
            }
            return(null);
        }
Example #15
0
        /// <summary>
        /// Make a request to the server using POST method.
        /// </summary>
        /// <param name="url">Request Url</param>
        /// <param name="data">Optional POST params</param>
        /// <returns></returns>
        protected async Task <IRestResponse> PostJson(string url, JObject data)
        {
            var request = new RestRequest(url, Method.POST);

            request.AddDecompressionMethod(System.Net.DecompressionMethods.None);
            request.RequestFormat = DataFormat.Json;

            if (data != null)
            {
                foreach (var item in data)
                {
                    request.AddParameter(item.Key, item.Value, ParameterType.GetOrPost);
                }
            }

            PrepareRequest(request);

            var response = await Client.ExecuteTaskAsync(request).ConfigureAwait(false);;

            return(response);
        }
Example #16
0
        /// <summary>
        /// Performs a GET request on the specified path.
        /// </summary>
        /// <typeparam name="T">The type of data to deserialize and return.</typeparam>
        /// <param name="path">The relative API endpoint path.</param>
        /// <returns>The deserialized data of type <typeparamref name="T" />.</returns>
        protected async Task <T> Get <T>(string path) where T : class
        {
            var req = new RestRequest(path);

            // Bug in HA or RestSharp if Gzip is enabled, so disable it for now
            req.AddDecompressionMethod(DecompressionMethods.None);
            req.AddHeader("Accept-Encoding", "identity");

            var resp = await Client.ExecuteGetAsync(req);

            if (!string.IsNullOrWhiteSpace(resp.Content) && (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.Created))
            {
                // Weird case for strings - return as-is
                if (typeof(T).IsAssignableFrom(typeof(string)))
                {
                    return(resp.Content as T);
                }

                return(JsonConvert.DeserializeObject <T>(resp.Content));
            }

            throw new Exception($"Unexpected response code {(int)resp.StatusCode} from Home Assistant API endpoint {path}.");
        }
        /// <summary>
        /// Creates a new request to the PUBG-web-api for the specified resource with the specified query parameters
        /// </summary>
        protected virtual RestRequest CreateRequest(RestRequestSettings settings)
        {
            RestRequest request = new RestRequest(settings.Resource, settings.HttpMethod, settings.DataFormat);

            request.AddDecompressionMethod(settings.DecompressionMethod);

            if (!(settings.Headers is null) && settings.Headers.Count > 0)
            {
                foreach (KeyValuePair <string, string> pair in settings.Headers)
                {
                    request.AddHeader(pair.Key, pair.Value);
                }
            }

            if (!(settings.QueryParameters is null) && settings.QueryParameters.Count > 0)
            {
                foreach (KeyValuePair <string, string> pair in settings.QueryParameters)
                {
                    request.AddQueryParameter(pair.Key, pair.Value);
                }
            }

            return(request);
        }