Exemple #1
0
 static void Main(string[] args)
 {
     Console.WriteLine("Hello World!");
     AsyncHttpClient client    = new AsyncHttpClient();
     var             result    = client.Url($"http://ftrace.baidu.com/webCms/ums/queryUms?from=cuid&&cuid=0000032F6875678A93A7106191ADF834|505733030667568").Get();//.Result;
     var             resultStr = result.Result.GetString();
 }
        public static BasicAuthMiddleware Add(AsyncHttpClient client)
        {
            BasicAuthMiddleware ret = new BasicAuthMiddleware();

            client.Middleware.Add(ret);
            return(ret);
        }
Exemple #3
0
        public void Callback()
        {
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            var             request         = new HttpRequest();

            request.Uri = new Uri("http://www.w3school.com.cn");
            var html = asyncHttpClient.GetString(request);

            TestContext.WriteLine(html);
            var count     = 0;
            var testCount = 100;

            for (int i = 0; i < testCount; i++)
            {
                asyncHttpClient.Execute(request, (res) =>
                {
                    res.BodyStream.ReadAsString((str) =>
                    {
                        TestContext.WriteLine("thread id:" + Thread.CurrentThread.ManagedThreadId);

                        lock (this)
                        {
                            count++;
                        }
                    });
                });
            }

            while (count != testCount)
            {
                Thread.Sleep(10);
            }
        }
Exemple #4
0
        public async Task Get(string host, string id, string flag, int vuln)
        {
            var httpClient = new AsyncHttpClient(GetBaseHttpUri(host));

            var parts = id.Split(new[] { ':' }, 2);

            var b64Name = parts[0];
            var key     = Encoding.ASCII.GetString(Convert.FromBase64String(parts[1]));

            var result = await httpClient.DoRequestAsync(WebRequestMethods.Http.Get, GetRelative, new WebHeaderCollection { { "X-SG1-Name", b64Name }, { "X-SG1-Key", key } }, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"get {GetRelative} failed");
            }

            if (!ProtoBufHelper.TryDeserialize(result.Body, out Transmission transmission))
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {GetRelative} response");
            }

            if (transmission.Name != b64Name)
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {GetRelative} response");
            }

            if (ConvertHelper.TryFromBase64String(transmission.Entropy) != flag)
            {
                throw new CheckerException(ExitCode.CORRUPT, "no entropy found");
            }
        }
Exemple #5
0
        public async Task Check(string host)
        {
            var client = new AsyncHttpClient(GetBaseUri(host), true);

            var result = await client.DoRequestAsync(HttpMethod.Get, "/", null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), "get / failed");
            }

            await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);

            var query = "?query=" + WebUtility.UrlEncode(RndText.RandomWord(RndUtil.GetInt(2, 10)));

            result = await client.DoRequestAsync(HttpMethod.Get, ApiNotesSearch + query, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiNotesSearch} failed");
            }

            var notes = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <List <Note> >(result.BodyAsString));

            if (notes == default)
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiNotesSearch} response");
            }

            await Console.Error.WriteLineAsync($"found '{notes.Count}' notes by query '{query}'").ConfigureAwait(false);
        }
Exemple #6
0
        private static void verifyPayment(Payment payment)
        {
            string     resultString = "".ToString();
            JSONObject jsonObject   = new JSONObject();

            jsonObject.Put("payload", payment.Payload);

            string verifystring = (string)jsonObject;
            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Content-Type", "application/json; charset=UTF-8");
            headers.Add(merchantApiHeaderKeyForApiSecretKey, merchantApiSecretKey);
            //
            AsyncHttpClient.Post(merchantServerUrl + VERIFY, headers, verifystring, new HttpResponseCallback
            {
                Success = (response) =>
                {
                    Java.Lang.String mString      = new Java.Lang.String(response, Charset.ForName("UTF-8"));
                    JSONObject jsonVerifyResponse = new JSONObject((string)mString);
                    Java.Lang.String authResponse = new Java.Lang.String(jsonVerifyResponse.GetString("authResponse"));
                    if (authResponse.EqualsIgnoreCase(payment.GetPaymentStatus().ToString()))
                    {
                        resultString = "Payment is " + payment.GetPaymentStatus().ToString().ToLower() + " and verified.";
                    }
                    else
                    {
                        resultString = "Failed to verify payment.";
                    }
                },
                Failure = (th) =>
                {
                    Toast.MakeText(context, resultString, ToastLength.Long).Show();
                }
            });
        }
        public static async Task <IRandomAccessStream> GetStreamFromUri(this Uri uri, CancellationToken cancellationToken)
        {
            switch (uri.Scheme)
            {
            case "ms-appx":
            case "ms-appdata":
            {
                var file = await StorageFile.GetFileFromApplicationUriAsync(uri);

                return(await file.OpenAsync(FileAccessMode.Read).AsTask(cancellationToken).ConfigureAwait(false));
            }

            case "ms-resource":
            {
                var rm        = ResourceManager.Current;
                var context   = ResourceContext.GetForCurrentView();
                var candidate = rm.MainResourceMap.GetValue(uri.LocalPath, context);
                if (candidate != null && candidate.IsMatch)
                {
                    var file = await candidate.GetValueAsFileAsync();

                    return(await file.OpenAsync(FileAccessMode.Read).AsTask(cancellationToken).ConfigureAwait(false));
                }
                throw new Exception("Resource not found");
            }

            case "file":
            {
                var file = await StorageFile.GetFileFromPathAsync(uri.LocalPath);

                return(await file.OpenAsync(FileAccessMode.Read).AsTask(cancellationToken).ConfigureAwait(false));
            }

            default:
            {
                try
                {
                    RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromUri(uri);
                    return(await streamRef.OpenReadAsync().AsTask(cancellationToken).ConfigureAwait(false));
                }
                catch (Exception ex)
                {
                    try
                    {
                        AsyncHttpClient httpClient = new AsyncHttpClient();
                        var             rsp        = await httpClient.Uri(uri).Get();

                        return(await rsp.GetRandomStream());
                    }
                    catch (Exception hex)
                    {
                        return(null);
                    }
                }
            }
            }
        }
Exemple #8
0
        public async Task <string> Upload(Uri uri)
        {
            string          guid            = GuidHelper.Gen().ToString();
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            var             result          = await asyncHttpClient.DefaultUserAgent().Referer(uri.AbsoluteUri).Uri(uri).Get();

            string fileExtension = "png";

            return(await Upload(guid.ToString() + "." + fileExtension, result.GetBytes()));
        }
Exemple #9
0
        public async Task Check(string host)
        {
            var httpClient = new AsyncHttpClient(GetBaseHttpUri(host));

            var result = await httpClient.DoRequestAsync(WebRequestMethods.Http.Get, "/", null, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), "get / failed");
            }
        }
Exemple #10
0
        public async Task <string> Upload(Uri uri)
        {
            Guid            guid            = Guid.NewGuid();
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            var             result          = await asyncHttpClient
                                              .UserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
                                              .Referer(uri.AbsoluteUri).Uri(uri).Get();

            string fileExtension = "png";

            return(await Upload(guid.ToString() + "." + fileExtension, result.GetBytes()));
        }
        private void verifyPayment(Payment payment)
        {
            JSONObject jsonObject = new JSONObject();

            try
            {
                jsonObject.Put("payload", payment.Payload);
            }
            catch (JSONException e)
            {
                Toast.MakeText(this, "Failed to verify payment.", ToastLength.Long).Show();
                return;
            }
            String verifyString = jsonObject.ToString();

            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Content-Type", "application/json; charset=UTF-8");
            headers.Add(merchantApiHeaderKeyForApiSecretKey, merchantApiSecretKey);
            String resultString = "";


            AsyncHttpClient.Post(merchantServerUrl + VERIFY, headers, verifyString, new HttpResponseCallback
            {
                Success = (response) =>
                {
                    try
                    {
                        JSONObject jsonVerifyResponse = new JSONObject((string)new Java.Lang.String(response, Charset.ForName("UTF-8")));
                        String authResponse           = jsonVerifyResponse.GetString("authResponse");
                        if (authResponse.Equals(payment.GetPaymentStatus().ToString()))
                        {
                            resultString = "Payment is " + payment.GetPaymentStatus().ToString().ToLower() + " and verified.";
                        }
                        else
                        {
                            resultString = "Failed to verify payment.";
                        }
                    }
                    catch (JSONException e)
                    {
                        resultString = "Failed to verify payment.";
                    }
                    Toast.MakeText(this, resultString, ToastLength.Long).Show();
                },

                Failure = (e) =>
                {
                    Toast.MakeText(this, resultString, ToastLength.Long).Show();
                }
            });
        }
        private static void Main(string[] args)
        {
            JsonRpcSerializer serializer = new JsonRpcSerializer();

            AsyncHttpClient client = new AsyncHttpClient(serializer);
            client.BaseUri = new Uri("http://Suffix:8080/jsonrpc");
            AudioLibraryClient libraryClient = new AudioLibraryClient(client, serializer);
            PlayerClient playerClient = new PlayerClient(client, serializer);
            //XbmcServerClient serverClient = new XbmcServerClient(client);
            PlaylistClient playlist = new PlaylistClient(client, serializer);
            FilesClient files = new FilesClient(client, serializer);

            XbmcPlayer player = new XbmcPlayer { Id = 0 };
            //playerClient.PlayPause(ResultAction, player);
            PlayerProperties props = playerClient.GetProperties(player).Result;

            IEnumerable<Playlist> playlists = playlist.GetPlaylists().Result;

            IMediaItemList<MediaDetailsBase> items = playlist.GetItems(playlists.First()).Result;

            var artists = libraryClient.GetArtists(null, null, ArtistFields.All, 0, 50, SortMethods.Album, Orders.Ascending).Result;

            var fs = files.GetMusicPlaylists().Result;

            //player.GetItem(ResultAction);
            //player.GetProperties(Result);
            //player.Seek(ResultAction, 10);

            //library.GetAlbums(ResultAction, 214, null, null, 2, null);
            //library.GetArtists(ResultAction);
            //library.GetSongs(ResultAction, null, null, null);
            //library.GetSong(ResultAction, 6695, null);
            //library.GetAlbum(ResultAction, 470, null);
            //library.GetArtist(ResultAction, 215, null);

            //player.OpenAlbum(ResultAction, 469);

            //server.Introspect(ResultAction);
            //server.ToggleMute(ResultAction);
            //server.Ping(ResultAction);
            //server.GetVersion(ResultAction);

            //playlist.Remove(ResultAction, new Playlist { Id = 0 }, 1);
            //playlist.Add(ResultAction, new Playlist { Id = 0 }, new Album { Id = 470 });
            //playlist.GetItems(ResultAction, new Playlist { Id = 0 });
            //playlist.GetPlaylists(ResultAction);

            Console.ReadLine();
        }
Exemple #13
0
        public async Task Get(string host, string id, string flag, int vuln)
        {
            var parts = id.Split(':');

            if (parts.Length != 3)
            {
                throw new Exception($"Invalid flag id '{id}'");
            }

            var login  = parts[0];
            var pass   = parts[1];
            var cookie = Encoding.UTF8.GetString(Convert.FromBase64String(parts[2]));

            var client = new AsyncHttpClient(GetBaseUri(host), true);

            var result = await client.DoRequestAsync(HttpMethod.Get, ApiScoreboard, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiScoreboard} failed");
            }

            var solutions = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <List <Solution> >(result.BodyAsString));

            if (solutions == default || solutions.Count == 0 || solutions.All(sln => sln.Login != login))
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiScoreboard} response");
            }

            await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);

            client = new AsyncHttpClient(GetBaseUri(host), true);
            client.Cookies.SetCookies(GetBaseUri(host), cookie);

            result = await client.DoRequestAsync(HttpMethod.Get, ApiAuth, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiAuth} failed");
            }

            var user = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <User>(result.BodyAsString));

            if (user == default || user.Login != login || user.Bio != flag)
            {
                throw new CheckerException(ExitCode.CORRUPT, "flag not found");
            }
        }
Exemple #14
0
        public string LoginString(string url)
        {
            FileLog.Log($"LoginString Requset {url}");
            var newurl = url + "&fun=new&version=v2";
            var client = new AsyncHttpClient().UserAgent("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36")
                         .Header("Accept-Encoding", "gzip,deflate,br")
                         .Header("Accept-Language", "zh-CN,zh;q=0.9")
                         .Header("Accept", "application/json, text/plain, */*")
                         .Header("Connection", "keep-alive")
                         .Header("Host", "wx2.qq.com").Cookies(cookieContainer)
                         .AutomaticDecompression(DecompressionMethods.Deflate | DecompressionMethods.GZip)
                         .Referer("https://wx2.qq.com/").Url(newurl);
            var response = client.Get().Result;
            var str      = response.GetString();

            FileLog.Log($"GetString Response {str}");
            return(str);
        }
        public void OnPaymentDataRequested(PaymentRequest paymentRequest, string token, IPaymentDataCallback callback)
        {
            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Content-Type", "application/json; charset=UTF-8");
            headers.Add(merchantApiHeaderKeyForApiSecretKey, merchantApiSecretKey);
            AsyncHttpClient.Post(merchantServerUrl + SETUP, headers, GetSetupDataString(token), new HttpResponseCallback
            {
                Success = (response) =>
                {
                    callback.CompletionWithPaymentData(response);
                },
                Failure = (p0) =>
                {
                    paymentRequest.Cancel();
                }
            });
        }
Exemple #16
0
            public async Task <IBuffer> download(string url, object extra)
            {
                AsyncHttpClient http = new AsyncHttpClient();

                http.Url(url);
                if (extra != null)
                {
                    //把相关信息传过去作防盗验证
                    var user = extra as User;
                    http.Header("UserID", user.UserID);
                    http.Header("Sex", user.Sex);
                    http.Header("APPID", "1111");
                    http.Header("APPMK", "XXXXXXXXXXXXXXXX");
                }

                var rsp = await http.Get();

                return(rsp.getBuffer());
            }
Exemple #17
0
        public AsyncHttpClient CreateHttpClient()
        {
            AsyncHttpClient client   = new AsyncHttpClient();
            var             mHandler = new HttpClientHandler();

            client
            .Header("Connection", "keep-alive")
            .Header("Keep-Alive", "600")
            .UserAgent("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36")
            .Header("Accept-Encoding", "gzip,deflate,br")
            .Header("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4").AutomaticDecompression(DecompressionMethods.Deflate | DecompressionMethods.GZip)
            .AllowAutoRedirect(false).Cookies(cookieContainer)
            .ExpectContinue(false);    //.Timeout(35000)
            Referer = "https://wx.qq.com/";
            if (Referer != string.Empty)
            {
                client.Referer(Referer);
                client.Header("Origin", Referer);
            }
            return(client);
        }
Exemple #18
0
        public void SingleThread()
        {
            var count = 100;

            async Task AsyncFunc()
            {
                var        url        = "http://www.w3school.com.cn/";
                HttpClient httpClient = new HttpClient();
                var        start      = DateTime.Now;

                for (int i = 0; i < count; i++)
                {
                    var data = await httpClient.GetByteArrayAsync(url);
                }
                var end = DateTime.Now;

                TestContext.WriteLine($"HttpClient request {count} times , cost {(end - start).TotalMilliseconds}ms");

                Thread.Sleep(2000);
                AsyncHttpClient asyncHttpClient = new AsyncHttpClient();

                start = DateTime.Now;
                for (int i = 0; i < count; i++)
                {
                    var request = new HttpRequest()
                    {
                        Uri = new Uri(url)
                    };
                    var res = await asyncHttpClient.ExecuteAsync(request);

                    var data = await res.BodyStream.ReadAsByteArrayAsync();
                }
                end = DateTime.Now;
                TestContext.WriteLine($"AsyncHttpClient request {count} times , cost {(end - start).TotalMilliseconds}ms");
            }

            var func = AsyncFunc();

            func.Wait();
        }
Exemple #19
0
        public void MultiThread()
        {
            var        thread     = 10;
            var        count      = 1000;
            var        url        = "https://www.baidu.com/";
            HttpClient httpClient = new HttpClient();
            var        start      = DateTime.Now;
            var        allTask    = new List <Task>();
            var        counter    = 0;

            for (int i = 0; i < thread; i++)
            {
                allTask.Add(Task.Run(async() =>
                {
                    while (true)
                    {
                        lock (this)
                        {
                            counter++;
                            if (counter > count + 1)
                            {
                                return;
                            }
                        }
                        var data = await httpClient.GetByteArrayAsync(url);
                    }
                }));
            }
            foreach (var task in allTask)
            {
                task.Wait();
            }
            var end = DateTime.Now;

            TestContext.WriteLine($"HttpClient {thread} threads request {count} times , cost {(end - start).TotalMilliseconds}ms");

            Thread.Sleep(2000);
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();

            start = DateTime.Now;

            allTask = new List <Task>();
            counter = 0;
            for (int i = 0; i < thread; i++)
            {
                allTask.Add(Task.Run(async() =>
                {
                    while (true)
                    {
                        lock (this)
                        {
                            counter++;
                            if (counter > count + 1)
                            {
                                return;
                            }
                        }
                        var request = new HttpRequest()
                        {
                            Uri = new Uri(url)
                        };
                        var res  = await asyncHttpClient.ExecuteAsync(request);
                        var data = await res.BodyStream.ReadAsByteArrayAsync();
                    }
                }));
            }
            foreach (var task in allTask)
            {
                task.Wait();
            }
            end = DateTime.Now;
            TestContext.WriteLine($"AsyncHttpClient {thread} threads request {count} times , cost {(end - start).TotalMilliseconds}ms");
        }
Exemple #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HttpTester"/> class.
 /// </summary>
 /// <param name="iterations">Number of iterations to run</param>
 /// <param name="requestConfiguration">The request configuration to run</param>
 /// <param name="httpClient">The async http client to use</param>
 public HttpTester(int iterations, RequestConfiguration requestConfiguration, AsyncHttpClient httpClient)
 {
     this.iterations           = iterations;
     this.requestConfiguration = requestConfiguration;
     this.httpClient           = httpClient;
 }
Exemple #21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HttpTester"/> class.
 /// </summary>
 /// <param name="iterations">Number of iterations to run</param>
 /// <param name="requestConfiguration">The request configuration to run</param>
 /// <param name="httpClient">The async http client to use</param>
 public HttpTester(int iterations, RequestConfiguration requestConfiguration, AsyncHttpClient httpClient)
 {
     this.iterations = iterations;
     this.requestConfiguration = requestConfiguration;
     this.httpClient = httpClient;
 }
Exemple #22
0
        public async Task Check(string host)
        {
            var client = new AsyncHttpClient(GetBaseUri(host), true);

            var result = await client.DoRequestAsync(HttpMethod.Get, "/", null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), "get / failed");
            }

            await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);

            result = await client.DoRequestAsync(HttpMethod.Get, ApiGenerate, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiGenerate} failed");
            }

            var rubik = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <GeneratedRubik>(result.BodyAsString));

            if (rubik == default)
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiGenerate} response");
            }

            await Console.Error.WriteLineAsync($"rubik '{rubik.Rubik}', signed '{rubik.Value}'").ConfigureAwait(false);

            await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);

            var login = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase();
            var pass  = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase();
            var flag  = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase();

            await Console.Error.WriteLineAsync($"name '{login}', pass '{pass}', bio '{flag}'").ConfigureAwait(false);

            var solution = RndRubik.RandomSolution(MinRandomSolutionLength, MaxRandomSolutionLength);
            var query    = $"?login={WebUtility.UrlEncode(login)}&pass={WebUtility.UrlEncode(pass)}&bio={WebUtility.UrlEncode(flag)}&puzzle={WebUtility.UrlEncode(rubik.Value)}&solution={WebUtility.UrlEncode(solution)}";

            result = await client.DoRequestAsync(HttpMethod.Post, ApiSolve + query, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != (HttpStatusCode)418)
            {
                throw new CheckerException(result.StatusCode == HttpStatusCode.OK ? ExitCode.MUMBLE : result.StatusCode.ToExitCode(), $"invalid {ApiSolve} response");
            }

            await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);

            result = await client.DoRequestAsync(HttpMethod.Get, ApiAuth, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiAuth} failed");
            }

            var user = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <User>(result.BodyAsString));

            if (user == default || user.Login != login || user.Bio != flag)
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiAuth} response");
            }
        }
Exemple #23
0
        public async Task <string> Put(string host, string id, string flag, int vuln)
        {
            var client = new AsyncHttpClient(GetBaseUri(host), true);

            var result = await client.DoRequestAsync(HttpMethod.Get, ApiGenerate, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiGenerate} failed");
            }

            var rubik = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <GeneratedRubik>(result.BodyAsString));

            if (rubik == default)
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiGenerate} response");
            }

            await Console.Error.WriteLineAsync($"rubik '{rubik.Rubik}', signed '{rubik.Value}'").ConfigureAwait(false);

            string solution;

            try
            {
                solution = DoIt.TryOrDefault(() => SolveHelper.ConvertOutputSolution(RubikSolver.FindSolution(SolveHelper.ConvertInputCube(rubik.Rubik), 32, 10000)));
            }
            catch (RubikSolveException e)
            {
                await Console.Error.WriteLineAsync(e.Message).ConfigureAwait(false);

                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiGenerate} response: unsolvable puzzle");
            }

            await Console.Error.WriteLineAsync($"solution '{solution}'").ConfigureAwait(false);

            await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);

            var login = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase();
            var pass  = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase();

            await Console.Error.WriteLineAsync($"name '{login}', pass '{pass}', bio '{flag}'").ConfigureAwait(false);

            var query = $"?login={WebUtility.UrlEncode(login)}&pass={WebUtility.UrlEncode(pass)}&bio={WebUtility.UrlEncode(flag)}&puzzle={WebUtility.UrlEncode(rubik.Value)}&solution={WebUtility.UrlEncode(solution)}";

            result = await client.DoRequestAsync(HttpMethod.Post, ApiSolve + query, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"post {ApiSolve} failed");
            }

            var sln = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <Solution>(result.BodyAsString));

            if (sln == default || sln.Login != login || sln.MovesCount != solution.Length)
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiSolve} response");
            }

            await Console.Error.WriteLineAsync($"solution '{solution}'").ConfigureAwait(false);

            var cookie = client.Cookies.GetCookieHeader(GetBaseUri(host));
            await Console.Error.WriteLineAsync($"cookie '{cookie}'").ConfigureAwait(false);

            if (string.IsNullOrEmpty(cookie) || cookie.Length > 512)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"invalid {ApiSolve} response: cookies");
            }

            return($"{login}:{pass}:{Convert.ToBase64String(Encoding.UTF8.GetBytes(cookie))}");
        }
 public FilesClient(AsyncHttpClient client, JsonRpcSerializer serializer)
 {
     _client = client;
     _serializer = serializer;
 }
Exemple #25
0
        public async Task <string> Put(string host, string id, string flag, int vuln)
        {
            var len  = vuln == 1 ? RndUtil.Choice(11, 14) : RndUtil.Choice(12, 15);
            var name = RndText.RandomWord(len).RandomLeet().RandomUpperCase();

            var b64Name    = Convert.ToBase64String(Encoding.ASCII.GetBytes(name));
            var b64Entropy = Convert.ToBase64String(Encoding.ASCII.GetBytes(flag));

            await Console.Error.WriteLineAsync($"name '{name}', b64name '{b64Name}', entropy '{b64Entropy}'").ConfigureAwait(false);

            using (var bmp = RndBitmap.RndBmp(RndUtil.ThreadStaticRnd.Next(32) + 96, RndUtil.ThreadStaticRnd.Next(32) + 96))
                using (var wsClient = await AsyncWebSocketClient.TryConnectAsync(GetBaseWsUri(host), MaxWsMsgSize, NetworkOpTimeout).ConfigureAwait(false))
                {
                    if (wsClient == null)
                    {
                        throw new CheckerException(ExitCode.DOWN, "ws connect failed");
                    }

                    await Console.Error.WriteLineAsync("ws connected").ConfigureAwait(false);

                    if (await wsClient.TryWaitMessageAsync(buffer => Tuple.Create(buffer.Count == 2 && buffer.Array[0] == (byte)'h' && buffer.Array[1] == (byte)'i', buffer), NetworkOpTimeout).ConfigureAwait(false) == default(ArraySegment <byte>))
                    {
                        throw new CheckerException(ExitCode.MUMBLE, "await hello failed");
                    }

                    await Console.Error.WriteLineAsync("ws hello received").ConfigureAwait(false);

                    // ReSharper disable once AccessToDisposedClosure
                    var wsTask = Task.Run(() => wsClient.TryWaitMessageAsync(buffer =>
                    {
                        if (!ProtoBufHelper.TryDeserialize <Transmission>(buffer, out var transmission))
                        {
                            throw new CheckerException(ExitCode.MUMBLE, "invalid ws data");
                        }
                        return(Tuple.Create(transmission.Name == b64Name, transmission));
                    }, NetworkOpTimeout));

                    await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);

                    var httpClient = new AsyncHttpClient(GetBaseHttpUri(host));

                    var result = await httpClient.DoRequestAsync(WebRequestMethods.Http.Put, PutRelative, new WebHeaderCollection { { "X-SG1-Name", b64Name }, { "X-SG1-Entropy", b64Entropy } }, bmp.ToByteArray(), NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

                    if (result.StatusCode != HttpStatusCode.OK)
                    {
                        throw new CheckerException(result.StatusCode.ToExitCode(), $"put {PutRelative} failed");
                    }

                    var key = result.Headers?["X-SG1-Key"];
                    if (string.IsNullOrEmpty(key))
                    {
                        throw new CheckerException(ExitCode.MUMBLE, $"invalid {PutRelative} response");
                    }

                    if (!ProtoBufHelper.TryDeserialize(result.Body, out Spectrum spectrum))
                    {
                        throw new CheckerException(ExitCode.MUMBLE, $"invalid {PutRelative} response");
                    }

                    var expectedSpectrum = bmp.CalcSpectrum();

                    if (!spectrum.ComponentEquals(expectedSpectrum))
                    {
                        throw new CheckerException(ExitCode.MUMBLE, $"invalid {PutRelative} response");
                    }

                    await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);

                    var msg = await wsTask.ConfigureAwait(false);

                    if (msg == null || msg.Name != b64Name)
                    {
                        throw new CheckerException(ExitCode.MUMBLE, "await msg failed");
                    }

                    var flagid = $"{b64Name}:{Convert.ToBase64String(Encoding.ASCII.GetBytes(key))}";
                    await Console.Out.WriteLineAsync(flagid).ConfigureAwait(false);

                    return(flagid);
                }
        }
Exemple #26
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            this.RequestWindowFeature(WindowFeatures.NoTitle);
            SetContentView(Resource.Layout.activity_main);
            merchantServerUrl    = TextUtils.IsEmpty(merchantServerUrl) ? SERVER_URL : merchantServerUrl;
            merchantApiSecretKey = TextUtils.IsEmpty(merchantApiSecretKey) ? API_KEY : merchantApiSecretKey;
            merchantApiHeaderKeyForApiSecretKey = TextUtils.IsEmpty(merchantApiHeaderKeyForApiSecretKey)? API_HEADER_KEY: merchantApiHeaderKeyForApiSecretKey;
            context = this;
            SetStatusBarTranslucent(true);
            Button checkoutButton = (Button)FindViewById(Resource.Id.checkout_button);

            //
            checkoutButton.Click += (s, e) =>
            {
                if (TextUtils.IsEmpty(merchantApiSecretKey) || TextUtils.IsEmpty(merchantApiHeaderKeyForApiSecretKey) || TextUtils.IsEmpty(merchantServerUrl))
                {
                    Toast.MakeText(ApplicationContext, "Server parameters have not been configured correctly", ToastLength.Long).Show();
                    return;
                }
                paymentRequest = new PaymentRequest(context, paymentRequestListener);
                paymentRequest.Start();
            };
            //
            paymentRequestListener = new PaymentRequestListener
            {
                PaymentDataRequested = (paymentRequest, token, paymentDataCallback) =>
                {
                    Dictionary <string, string> headers = new Dictionary <string, string>();
                    headers.Add("Content-Type", "application/json; charset=UTF-8");
                    headers.Add(merchantApiHeaderKeyForApiSecretKey, merchantApiSecretKey);
                    AsyncHttpClient.Post(merchantServerUrl + SETUP, headers, GetSetupDataString(token), new HttpResponseCallback
                    {
                        Success = (response) =>
                        {
                            paymentDataCallback.CompletionWithPaymentData(response);
                        },
                        Failure = (e) =>
                        {
                            Log.Error(TAG, "HTTP Response problem: ", e);
                            System.Diagnostics.Debug.Write("HTTP Response problem: " + e);
                        }
                    });
                },
                PaymentResult = (paymentRequest, paymentRequestResult) =>
                {
                    if (paymentRequestResult.IsProcessed && (paymentRequestResult.Payment.GetPaymentStatus() == Payment.PaymentStatus.Authorised || paymentRequestResult.Payment.GetPaymentStatus() == Payment.PaymentStatus.Received))
                    {
                        verifyPayment(paymentRequestResult.Payment);
                        Intent intent = new Intent(context, typeof(SuccessActivity));
                        StartActivity(intent);
                        Finish();
                    }
                    else
                    {
                        Intent intent = new Intent(context, typeof(FailureActivity));
                        StartActivity(intent);
                        Finish();
                    }
                }
            };
        }
 public PlayerClient(AsyncHttpClient client, JsonRpcSerializer jsonRpcSerializer)
 {
     _client = client;
     _jsonRpcSerializer = jsonRpcSerializer;
 }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            paymentRequestDetailsListener = new PaymentRequestDetailsListener
            {
                PaymentMethodSelectionRequired = (paymentRequest, recurringMethods, otherMethods, callback) =>
                {
                    paymentMethodCallback = callback;
                    preferredPaymentMethods.Clear();
                    preferredPaymentMethods.AddRange(recurringMethods);
                    availablePaymentMethods.Clear();
                    availablePaymentMethods.AddRange(otherMethods);
                    PaymentMethodSelectionFragment paymentMethodSelectionFragment = new PaymentMethodSelectionFragment();
                    SupportFragmentManager.BeginTransaction().Replace(Android.Resource.Id.Content, paymentMethodSelectionFragment).AddToBackStack(null).CommitAllowingStateLoss();
                },
                RedirectRequired = (paymentRequest, redirectUrl, returnUriCallback) =>
                {
                    Log.Debug(TAG, "paymentRequestDetailsListener.onRedirectRequired(): " + redirectUrl);
                    uriCallback = returnUriCallback;
                    CustomTabsIntent.Builder builder          = new CustomTabsIntent.Builder();
                    CustomTabsIntent         customTabsIntent = builder.Build();
                    customTabsIntent.LaunchUrl(context, Android.Net.Uri.Parse(redirectUrl));
                },
                PaymentDetailsRequired = (paymentRequest, inputDetails, callback) =>
                {
                    Log.Debug(TAG, "paymentRequestDetailsListener.onPaymentDetailsRequired()");
                    String paymentMethodType = paymentRequest.PaymentMethod.GetType();

                    if (PaymentMethod.Type.Card.Equals(paymentMethodType))
                    {
                        CreditCardFragment creditCardFragment = new CreditCardFragment();
                        Bundle             bundle             = new Bundle();
                        //ONE CLICK CHECK
                        bool isOneClick = InputDetailsUtil.ContainsKey(inputDetails, "cardDetails.cvc");
                        if (isOneClick)
                        {
                            bundle.PutBoolean("oneClick", true);
                        }
                        creditCardFragment.setCreditCardInfoListener(new CreditCardInfoListener
                        {
                            CreditCardInfoProvided = (creditCardInfo) =>
                            {
                                if (isOneClick)
                                {
                                    CVCOnlyPaymentDetails cvcOnlyPaymentDetails = new CVCOnlyPaymentDetails(inputDetails);
                                    cvcOnlyPaymentDetails.FillCvc(creditCardInfo);
                                    callback.CompletionWithPaymentDetails(cvcOnlyPaymentDetails);
                                }
                                else
                                {
                                    CreditCardPaymentDetails creditCardPaymentDetails = new CreditCardPaymentDetails(inputDetails);
                                    creditCardPaymentDetails.FillCardToken(creditCardInfo);
                                    callback.CompletionWithPaymentDetails(creditCardPaymentDetails);
                                }
                            }
                        });
                        bundle.PutString("public_key", paymentRequest.PublicKey);
                        bundle.PutString("generation_time", paymentRequest.GenerationTime);
                        creditCardFragment.Arguments = bundle;

                        SupportFragmentManager.BeginTransaction().Replace(Android.Resource.Id.Content,
                                                                          creditCardFragment).AddToBackStack(null).CommitAllowingStateLoss();
                    }
                    else if (PaymentMethod.Type.Ideal.Equals(paymentMethodType))
                    {
                        AlertDialog.Builder     alertDialog       = new AlertDialog.Builder(this);
                        List <InputDetail.Item> issuers           = InputDetailsUtil.GetInputDetail(inputDetails, "idealIssuer").Items as List <InputDetail.Item>;
                        IssuerListAdapter       issuerListAdapter = new IssuerListAdapter(this, issuers);
                        alertDialog.SetSingleChoiceItems(issuerListAdapter, -1, new OnClickListener
                        {
                            Click = (dialogInterface, i) =>
                            {
                                IdealPaymentDetails idealPaymentDetails = new IdealPaymentDetails(inputDetails);
                                idealPaymentDetails.FillIssuer(issuers[i]);
                                dialogInterface.Dismiss();
                                callback.CompletionWithPaymentDetails(idealPaymentDetails);
                            }
                        });
                        alertDialog.Show();
                    }
                    else
                    {
                        String message = "UI for " + paymentMethodType + " has not been implemented.";
                        Log.Warn(TAG, message);
                        Toast.MakeText(this, message, ToastLength.Long).Show();
                        paymentRequest.Cancel();
                    }
                }
            };
            paymentRequestListener = new PaymentRequestListener
            {
                PaymentDataRequested = (paymentRequest, token, callback) =>
                {
                    Log.Debug(TAG, "paymentRequestListener.onPaymentDataRequested()");
                    Dictionary <string, string> headers = new Dictionary <string, string>();
                    headers.Add("Content-Type", "application/json; charset=UTF-8");
                    headers.Add(merchantApiHeaderKeyForApiSecretKey, merchantApiSecretKey);
                    AsyncHttpClient.Post(merchantServerUrl + SETUP, headers, getSetupDataString(token), new HttpResponseCallback
                    {
                        Success = (response) =>
                        {
                            callback.CompletionWithPaymentData(response);
                        },
                        Failure = (e) =>
                        {
                            Log.Error(TAG, "HTTP Response problem: ", e);
                            paymentRequest.Cancel();
                        }
                    });
                },
                PaymentResult = (paymentRequest, paymentResult) =>
                {
                    Log.Debug(TAG, "paymentRequestListener.onPaymentResult()");
                    String resultString;
                    if (paymentResult.IsProcessed)
                    {
                        resultString = paymentResult.Payment.GetPaymentStatus().ToString();
                        verifyPayment(paymentResult.Payment);
                    }
                    else
                    {
                        resultString = paymentResult.Error.ToString();
                    }

                    Intent intent = new Intent(ApplicationContext, typeof(PaymentResultActivity));
                    intent.PutExtra("Result", resultString);
                    intent.AddFlags(ActivityFlags.ClearTop);
                    intent.AddFlags(ActivityFlags.NewTask);
                    StartActivity(intent);
                    Finish();
                }
            };
            Log.Debug(TAG, "onCreate()");
            context = this;
            Android.Net.Uri uri = Intent.Data;
            if (uri == null)
            {
                setupInitScreen();
            }
            else
            {
                throw new Java.Lang.IllegalStateException("Application was supposed to be declared singleTask");
            }
        }
Exemple #29
0
        public async Task <string> Put(string host, string id, string flag, int vuln)
        {
            var client = new AsyncHttpClient(GetBaseUri(host), true);

            var login = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase();
            var name  = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase();
            var pass  = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase();

            await Console.Error.WriteLineAsync($"login '{login}', name '{name}', pass '{pass}'").ConfigureAwait(false);

            var signUpQuery = $"?login={WebUtility.UrlEncode(login)}&name={WebUtility.UrlEncode(name)}&password={WebUtility.UrlEncode(pass)}";
            var result      = await client.DoRequestAsync(HttpMethod.Post, ApiAuthSignUp + signUpQuery, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiAuthSignUp} failed");
            }

            await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);

            var items = Enumerable.Range(0, RndUtil.GetInt(1, 3)).Select(i => new Note {
                Title = RndText.RandomText(RndUtil.GetInt(MinRandomTitleLength, MaxRandomTitleLength)).RandomUmlauts(),
                Text  = RndText.RandomText(RndUtil.GetInt(MinRandomTextLength, MaxRandomTextLength)).RandomUmlauts()
            }).ToArray();

            var itemWithFlag = RndUtil.Choice(items);

            if (RndUtil.GetInt(0, 2) == 0)
            {
                itemWithFlag.Text = flag;
            }
            else
            {
                itemWithFlag.Title = flag;
            }
            itemWithFlag.IsPrivate = true;

            foreach (var item in items)
            {
                await Console.Error.WriteLineAsync($"title '{item.Title}', text '{item.Text}', isPrivate '{item.IsPrivate}'").ConfigureAwait(false);

                var q = $"?title={WebUtility.UrlEncode(item.Title)}&text={WebUtility.UrlEncode(item.Text)}" + (item.IsPrivate ? "&isPrivate=on" : null);
                result = await client.DoRequestAsync(HttpMethod.Post, ApiNotesAdd + q, null, NetworkOpTimeout).ConfigureAwait(false);

                if (result.StatusCode != HttpStatusCode.OK)
                {
                    throw new CheckerException(result.StatusCode.ToExitCode(), $"post {ApiNotesAdd} failed");
                }

                await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);
            }

            var query = GetRandomQuery(itemWithFlag);

            if (query.Trim('\"', ' ').Length <= 4)            //NOTE: too low entropy
            {
                query = flag;
            }

            await Console.Error.WriteLineAsync($"random query '{query}'").ConfigureAwait(false);

            var cookie = client.Cookies.GetCookieHeader(GetBaseUri(host));
            await Console.Error.WriteLineAsync($"cookie '{cookie}'").ConfigureAwait(false);

            var bytes = DoIt.TryOrDefault(() => Encoding.UTF8.GetBytes(cookie));

            if (bytes == null || bytes.Length > 1024)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), "too large or invalid cookies");
            }

            return($"{login}:{pass}:{Convert.ToBase64String(bytes)}:{WebUtility.UrlEncode(query)}");
        }
 public PlaylistClient(AsyncHttpClient client, JsonRpcSerializer serializer)
 {
     _client = client;
     _serializer = serializer;
 }
Exemple #31
0
        public async Task Get(string host, string id, string flag, int vuln)
        {
            var parts = id.Split(':', 4);

            if (parts.Length != 4)
            {
                throw new Exception($"Invalid flag id '{id}'");
            }

            var login        = parts[0];
            var pass         = parts[1];
            var cookie       = Encoding.UTF8.GetString(Convert.FromBase64String(parts[2]));
            var encodedQuery = parts[3];

            var client = new AsyncHttpClient(GetBaseUri(host), true);

            if (RndUtil.GetInt(0, 2) == 0)
            {
                await Console.Error.WriteLineAsync($"login by cookie '{cookie}'").ConfigureAwait(false);

                client.Cookies.SetCookies(GetBaseUri(host), cookie);
            }
            else
            {
                await Console.Error.WriteLineAsync($"login with login '{login}' and pass '{pass}'").ConfigureAwait(false);

                var loginQuery   = $"?login={WebUtility.UrlEncode(login)}&password={WebUtility.UrlEncode(pass)}";
                var signInResult = await client.DoRequestAsync(HttpMethod.Post, ApiAuthSignIn + loginQuery).ConfigureAwait(false);

                if (signInResult.StatusCode != HttpStatusCode.OK)
                {
                    throw new CheckerException(signInResult.StatusCode.ToExitCode(), $"get {ApiAuthSignIn} failed");
                }

                await Console.Error.WriteLineAsync($"cookie '{client.Cookies.GetCookieHeader(GetBaseUri(host))}'").ConfigureAwait(false);

                await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);
            }

            var query = RndUtil.Choice("?query=&myOnly=on", "?query=" + encodedQuery);

            var result = await client.DoRequestAsync(HttpMethod.Get, ApiNotesSearch + query, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiNotesSearch} failed");
            }

            var notes = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <List <Note> >(result.BodyAsString));

            if (notes == default)
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiNotesSearch} response");
            }

            await Console.Error.WriteLineAsync($"found '{notes.Count}' notes by query '{query}'").ConfigureAwait(false);

            var note = notes.FirstOrDefault(note => note.Author.Contains(flag) || note.Title.Contains(flag) || note.Text.Contains(flag));

            if (note == null)
            {
                throw new CheckerException(ExitCode.CORRUPT, "flag not found");
            }

            //NOTE: Also check phrase query

            if (!query.StartsWith("?query=%22") || !query.EndsWith("%22"))
            {
                return;
            }

            var words = WebUtility.UrlDecode(encodedQuery).Trim('"', ' ').Split().Where(word => !string.IsNullOrWhiteSpace(word)).Distinct().ToArray();

            if (words.Length < 2)
            {
                return;
            }

            query = string.Join(' ', words.Reverse());
            if (note.Author.Contains(query, StringComparison.InvariantCultureIgnoreCase) || note.Title.Contains(query, StringComparison.InvariantCultureIgnoreCase) || note.Text.Contains(query, StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            query = "?query=" + WebUtility.UrlEncode('"' + query + '"');
            await Console.Error.WriteLineAsync($"check phrase query reversed '{query}'").ConfigureAwait(false);

            result = await client.DoRequestAsync(HttpMethod.Get, ApiNotesSearch + query, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiNotesSearch} failed");
            }

            notes = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <List <Note> >(result.BodyAsString));
            if (notes == default)
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiNotesSearch} response");
            }

            await Console.Error.WriteLineAsync($"found '{notes.Count}' notes by query '{query}'").ConfigureAwait(false);

            if (notes.Any(note => note.Author.Contains(flag) || note.Title.Contains(flag) || note.Text.Contains(flag)))
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiNotesSearch} response: phrase query");
            }
        }
Exemple #32
0
        private static async void doHttp(SdSource source, HttpMessage msg, __CacheBlock cache, HttpCallback callback)
        {
            var encoding = Encoding.GetEncoding(msg.config.encode());

            AsyncHttpClient client = new AsyncHttpClient();

            client.UserAgent(msg.config.ua());
            client.Encoding(msg.config.encode());

            foreach (String key in msg.header.Keys)
            {
                client.Header(key, msg.header[key]);
            }

            string newUrl = null;

            if (msg.url.IndexOf(" ") >= 0)
            {
                newUrl = Uri.EscapeUriString(msg.url);
            }
            else
            {
                newUrl = msg.url;
            }

            client.Url(newUrl);

            string temp = null;

            AsyncHttpResponse rsp = null;

            try {
                if ("post".Equals(msg.config.method))
                {
                    rsp = await client.Post(msg.form);
                }
                else
                {
                    rsp = await client.Get();
                }

                if (rsp.StatusCode == HttpStatusCode.OK)
                {
                    source.setCookies(rsp.Cookies);
                    temp = rsp.GetString();

                    if (string.IsNullOrEmpty(rsp.location) == false)
                    {
                        Uri uri = new  Uri(msg.url);
                        rsp.location = uri.Scheme + "://" + uri.Host + rsp.location;
                    }
                }
            }
            catch (Exception ex) {
                Util.log(source, "HTTP", ex.Message);
            }

            if (temp == null)
            {
                if (cache == null || cache.value == null)
                {
                    callback(-2, msg, null, rsp.location);
                }
                else
                {
                    callback(1, msg, cache.value, rsp.location);
                }
            }
            else
            {
                callback(1, msg, temp, rsp.location);
            }
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            string resultString = "".ToString();

            paymentRequestListener = new PaymentRequestListener
            {
                PaymentDataRequested = (request, token, callback) =>
                {
                    if (paymentRequest != request)
                    {
                        Log.Debug(TAG, "onPaymentDataRequested(): This is not the payment request that we created.");
                        return;
                    }

                    Dictionary <string, string> headers = new Dictionary <string, string>();
                    headers.Add("Content-Type", "application/json; charset=UTF-8");
                    headers.Add(merchantApiHeaderKeyForApiSecretKey, merchantApiSecretKey);

                    AsyncHttpClient.Post(merchantServerUrl + SETUP, headers, getSetupDataString(token), new HttpResponseCallback
                    {
                        Success = (response) =>
                        {
                            callback.CompletionWithPaymentData(response);
                        },
                        Failure = (e) =>
                        {
                            paymentRequest.Cancel();
                        }
                    });
                },
                PaymentResult = (request, paymentResult) =>
                {
                    if (paymentRequest != request)
                    {
                        Log.Debug(TAG, "onPaymentResult(): This is not the payment request that we created.");
                        return;
                    }
                    string MresultString;
                    if (paymentResult.IsProcessed)
                    {
                        MresultString = paymentResult.Payment.GetPaymentStatus().ToString();
                        verifyPayment(paymentResult.Payment);
                    }
                    else
                    {
                        MresultString = paymentResult.Error.ToString();
                    }

                    Intent intent = new Intent(ApplicationContext, typeof(PaymentResultActivity));
                    intent.PutExtra("Result", MresultString);
                    intent.AddFlags(ActivityFlags.ClearTop);
                    intent.AddFlags(ActivityFlags.NewTask);
                    StartActivity(intent);
                    Finish(); // continuing these lines after add verifyPayment method
                }
            };
            PaymentDataEntryFragment paymentDataEntryFragment = new PaymentDataEntryFragment();

            SupportFragmentManager.BeginTransaction().Replace(Android.Resource.Id.Content,
                                                              paymentDataEntryFragment).CommitAllowingStateLoss();
        }
 public AudioLibraryClient(AsyncHttpClient client, JsonRpcSerializer serializer)
 {
     _client = client;
     _serializer = serializer;
 }