Esempio n. 1
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="BaseHttp" /> class.
        /// </summary>
        /// <param name="host">The host</param>
        protected BaseHttp(string host)
        {
            Guard.NotNullOrEmpty(host, nameof(host), "Host could not be null or empty");

            BasePath = host;

            FlurlHttp.Configure(settings =>
            {
                var jsonSettings = new JsonSerializerSettings
                {
                    NullValueHandling      = NullValueHandling.Ignore,
                    ObjectCreationHandling = ObjectCreationHandling.Replace
                };
                settings.JsonSerializer = new NewtonsoftJsonSerializer(jsonSettings);
            });
        }
        public VstsRestClient(string organization, string token)
        {
            _organization = organization ?? throw new ArgumentNullException(nameof(organization));
            _token        = token ?? throw new ArgumentNullException(nameof(token));

            FlurlHttp.Configure(settings =>
            {
                var jsonSettings = new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver(),
                    Converters       = { new PolicyConverter() }
                };
                settings.JsonSerializer    = new NewtonsoftJsonSerializer(jsonSettings);
                settings.HttpClientFactory = new HttpClientFactory();
            });
        }
        public async Task SendProtobufAsync_Post_SimpleObject()
        {
            var obj = new SimpleModel
            {
                Age       = 26,
                Id        = Guid.NewGuid(),
                BirthDate = DateTime.Now,
                Name      = "Foo da Silva"
            };

            FlurlHttp.Configure(c => c.HttpClientFactory = new VerifyObjectHttpClientFactory(obj));

            var result = await new Url("https://some.url").SendProtobufAsync(HttpMethod.Post, obj);

            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
        }
Esempio n. 4
0
        public void BeforeAllTests()
        {
            if (!Environment.OSVersion.IsAppVeyor() && Process.GetProcessesByName("Fiddler").Any())
            {
                var webProxy = new WebProxy("http://localhost.:8888", BypassOnLocal: false);

                FlurlHttp.Configure(settings =>
                {
                    settings.HttpClientFactory = new ProxyFactory(webProxy);
                });
            }

#if NETFRAMEWORK
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
#endif
        }
Esempio n. 5
0
        /// <summary>
        /// Configures the application services that require configuration.
        /// </summary>
        /// <param name="jenkinsSettings">The settings required to configure Jenkins requests.</param>
        private static void ConfigureAppServices(JenkinsSettings jenkinsSettings)
        {
            var jsonSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            FlurlHttp.Configure(s => s.JsonSerializer = new NewtonsoftJsonSerializer(jsonSettings));

            if (!string.IsNullOrWhiteSpace(jenkinsSettings.User) || !string.IsNullOrWhiteSpace(jenkinsSettings.Password))
            {
                FlurlHttp.ConfigureClient(jenkinsSettings.BaseEndpoint, cl =>
                                          cl.WithBasicAuth(jenkinsSettings.User, jenkinsSettings.Password)
                                          );
            }
            jenkinsSettings.Password = null;
        }
 public AssistantClient(IOptions <HomeAssistantOptions> options, ILogger <AssistantClient> logger)
 {
     BaseUrl = (options.Value.Address.StartsWith("http") ? options.Value.Address : $"http://{options.Value.Address}").Trim('"', '\'').AppendPathSegment("api");
     // DefaultRequestHeaders.Accept
     //     .Add(new MediaTypeWithQualityHeaderValue("application/json"));
     FlurlHttp.Configure(settings => {
         var jsonSettings = new JsonSerializerSettings {
             NullValueHandling    = Newtonsoft.Json.NullValueHandling.Ignore,
             Formatting           = Formatting.None,
             StringEscapeHandling = StringEscapeHandling.Default
         };
         settings.JsonSerializer = new NewtonsoftJsonSerializer(jsonSettings);
     });
     _logger = logger;
     _logger.LogInformation($"Initialized AssistantClient for '{BaseUrl}'");
 }
Esempio n. 7
0
        private static void Main()
        {
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var services = new ServiceCollection();

            DependencyInjectionConfig.Register(services);
            // FlurlHttp.Configure(settings => settings.ConnectionLeaseTimeout = TimeSpan.FromMinutes(2));
            FlurlHttp.Configure(settings => settings.HttpClientFactory = new ConnectionLifetimeHttpClientFactory());
            using (var provider = services.BuildServiceProvider())
            {
                var mainForm = provider.GetService <Form1>();
                Application.Run(mainForm);
            }
        }
Esempio n. 8
0
        public static async Task Main(string[] args)
        {
            var username = args[0];
            var password = args[1];
            var hostname = args[2];

            FlurlHttp.Configure(settings => settings.HttpClientFactory = new HttpClientRedirectFactory());

            using (var client = new FlurlClient($"https://{hostname}/api/v1"))
            {
                var accessToken = (await client.Request("login")
                                   .PostJsonAsync(new { username, password })
                                   .ReceiveJson()).accessToken;

                client.Headers.Add("Authorization", $"Bearer {accessToken}");

                // Let's exercise the API
                var networkDevices = await client.Request("networkDevices").GetJsonAsync();

                Console.WriteLine($"Total number of network devices: {networkDevices.total}");

                // Get objects from the first network device
                var firstNetworkDevice = networkDevices.items[0];
                var objects            = await client.Request($"networkDevices/{firstNetworkDevice.id}/objects").GetJsonAsync();

                Console.Write($"Item Reference of first object on first device: {objects.items[0].itemReference}");


                // Get alarms, but exclude acknowledged and discarded alarms. Also only in the priority
                // range 0-70

                var alarms = await client.Request("alarms")
                             .SetQueryParams(new
                {
                    excludePending      = true,
                    excludeAcknowledged = true,
                    priorityRange       = "0,70"
                })
                             .GetJsonAsync();

                // Do the same thing but manually construct the URL
                alarms = await client.Request("alarms?excludePending=true&excludeAcknowledged=true&priorityRange=0,70")
                         .GetJsonAsync();

                Console.WriteLine(JsonConvert.SerializeObject(alarms.items[0], Formatting.Indented));
            }
        }
Esempio n. 9
0
        public IntegrationTests()
        {
            Directory.SetCurrentDirectory(Path.GetDirectoryName(typeof(IntegrationTests).Assembly.Location));

            ReadSecrets();

#if NETFRAMEWORK
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
#endif

            var webProxy = new WebProxy("http://localhost.:8888", BypassOnLocal: false);

            FlurlHttp.Configure(settings =>
            {
                settings.HttpClientFactory = new ProxyFactory(webProxy);
            });
        }
Esempio n. 10
0
        protected IntegrationTest()
        {
            DataFixture = new Fixture();
            Server      = new TestServer(new WebHostBuilder().UseStartup <InProcessStartUp>());

            FlurlHttp.Configure(c =>
            {
                c.HttpClientFactory = new HttpClientFactory(Server);
            });

            Client = new FlurlClient(Server.BaseAddress.AbsoluteUri);

            DeserializeWithPrivateSetters = new JsonSerializerSettings
            {
                ContractResolver = new JsonPrivateResolver()
            };
        }
Esempio n. 11
0
        public IntegrationTests()
        {
            Directory.SetCurrentDirectory(Path.GetDirectoryName(typeof(IntegrationTests).Assembly.Location));
            var lines  = File.ReadAllLines("../../.secrets.txt");
            var apiKey = lines[0].GetAfter(":");

            webhookSecret = lines[1].GetAfter(":");

            var webProxy = new WebProxy("http://localhost.:8888", BypassOnLocal: false);

            FlurlHttp.Configure(settings =>
            {
                settings.HttpClientFactory = new ProxyFactory(webProxy);
            });

            commerceApi = new CommerceApi(apiKey);
        }
        public static void Configure(Configuration config)
        {
            Func <FlurlCall, Task> beforeCallAsync = (FlurlCall call) =>
            {
                Log.Verbose("HTTP Request: {@HttpMethod} - {@Uri} - {@Headers} - {@Content}", call.HttpRequestMessage.Method, call.HttpRequestMessage.RequestUri, call.HttpRequestMessage.Headers.ToString(), call.HttpRequestMessage.Content);
                return(Task.CompletedTask);
            };

            Func <FlurlCall, Task> afterCallAsync = async(FlurlCall call) =>
            {
                Log.Verbose("HTTP Response: {@HttpStatusCode} - {@HttpMethod} - {@Uri} - {@Headers} - {@Content}", call.HttpResponseMessage?.StatusCode, call.HttpRequestMessage?.Method, call.HttpRequestMessage?.RequestUri, call.HttpResponseMessage.Headers.ToString(), await call.HttpResponseMessage?.Content?.ReadAsStringAsync());

                if (config.Observability.Prometheus.Enabled)
                {
                    HttpRequestHistogram
                    .WithLabels(
                        call.HttpRequestMessage.Method.ToString(),
                        call.HttpRequestMessage.RequestUri.Host,
                        call.HttpRequestMessage.RequestUri.AbsolutePath,
                        call.HttpRequestMessage.RequestUri.Query,
                        ((int)call.HttpResponseMessage.StatusCode).ToString(),
                        call.HttpResponseMessage.ReasonPhrase
                        ).Observe(call.Duration.GetValueOrDefault().TotalSeconds);
                }
            };

            Func <FlurlCall, Task> onErrorAsync = async(FlurlCall call) =>
            {
                var response = string.Empty;
                if (call.HttpResponseMessage is object)
                {
                    response = await call.HttpResponseMessage?.Content?.ReadAsStringAsync();
                }
                Log.Error("Http Call Failed. {@HttpStatusCode} {@Content}", call.HttpResponseMessage?.StatusCode, response);
            };

            FlurlHttp.Configure(settings =>
            {
                settings.Timeout                  = new TimeSpan(0, 0, 10);
                settings.BeforeCallAsync          = beforeCallAsync;
                settings.AfterCallAsync           = afterCallAsync;
                settings.OnErrorAsync             = onErrorAsync;
                settings.Redirects.ForwardHeaders = true;
            });
        }
Esempio n. 13
0
        /// <summary>
        ///     Default constructor.
        /// </summary>
        /// <param name="apiKey"> Your OneSignal API key </param>
        /// <param name="apiUri"> API uri </param>
        protected ResourceBase(string apiKey, string apiUri = "https://onesignal.com/api/v1")
        {
            ApiKey = apiKey;

            ApiUri = apiUri;

            FlurlHttp.Configure(config =>
            {
                config.JsonSerializer = new NewtonsoftJsonSerializer(
                    new JsonSerializerSettings
                {
                    MissingMemberHandling = MissingMemberHandling.Ignore,
                    NullValueHandling     = NullValueHandling.Ignore,
                    DefaultValueHandling  = DefaultValueHandling.Include
                }
                    );
            });
        }
        private void ConfigureFlurlHttpClient()
        {
            FlurlHttp.Configure(settings =>
            {
                var contractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                };

                var jsonSettings = new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    ContractResolver  = contractResolver
                };

                settings.JsonSerializer = new NewtonsoftJsonSerializer(jsonSettings);
            });
        }
Esempio n. 15
0
        public static void Configure()
        {
            FlurlHttp.Configure(settings => {
                var jsonSettings = new JsonSerializerSettings
                {
                    ContractResolver  = new CamelCasePropertyNamesContractResolver(),
                    NullValueHandling = NullValueHandling.Ignore,
                    Converters        = new List <Newtonsoft.Json.JsonConverter>
                    {
                        new Newtonsoft.Json.Converters.StringEnumConverter()
                    }
                };

                var serializer = new NewtonsoftJsonSerializer(jsonSettings);

                settings.JsonSerializer = serializer;
            });
        }
Esempio n. 16
0
        static string vk()
        {
            WebProxy proxy = new WebProxy("51.38.71.101", 8080);

            proxy = new WebProxy(new Uri("http://51.38.71.101:8080"));

            IServiceCollection container = new ServiceCollection();

            container.AddAudioBypass();
            container.AddSingleton <IWebProxy, WebProxy>(provider => proxy);
            FlurlHttp.Configure(settings =>
            {
                settings.HttpClientFactory = new ProxyHttpClientFactory("http://51.38.71.101:8080");
            });


            VkApi vk
            // = new VkApi();
                = new VkApi(container);

            //  (vk.AuthorizationFlow as VkNet.Utils.Browser).Proxy = proxy;

            vk.Authorize(new ApiAuthParams()
            {
                ApplicationId = 123456,
                Login         = "******",
                Password      = "******",
                Settings      = Settings.All
            });
            //   var fr = vk.Friends.Get(new FriendsGetParams() { Count = 1 });
            var v = vk.Audio.Get(new AudioGetParams()
            {
                AccessKey = "id556153348"
            });
            Audio audio = v.Last();
            // vk.Audio.Download(audio, @"C:\Projects\VK_API\VK_API\bin\Debug");
            string outStr = "";

            foreach (var audio1 in v)
            {
                outStr += $"{audio1.Title} - {audio1.Url != null}" + Environment.NewLine;
            }
            return(outStr);
        }
Esempio n. 17
0
        public WinToastNotification(ILogger logger, string executableServerPath, string serverHost = "localhost", int serverPort = 1234)
        {
            this.logger = logger;
            logger.Information("starting: initializing win toast notification");
            this.serverHost           = serverHost;
            this.serverPort           = serverPort;
            this.executableServerPath = executableServerPath;
            this.uri = string.Format("http://{0}:{1}", serverHost, serverPort);
            logger.Information($"uri={uri}");
            initializeServer();
#if DEBUG && USE_PROXY
            var proxy = new ProxyHttpClientFactory();
            FlurlHttp.Configure(settings => {
                settings.HttpClientFactory = proxy;
            });
            logger.Information($"using proxy at: {proxy.Address}");
#endif
            logger.Information("finished: initializing win toast notification");
        }
Esempio n. 18
0
        private static void RegisterDependencies(ContainerBuilder builder)
        {
            FlurlHttp.Configure(settings => settings.HttpClientFactory = new PollyHttpClientFactory());

            //using log module, best way create nuget for this
            builder.RegisterModule(new LogModule());
            builder.RegisterType <PageObject>().As <IPageObject>();
            builder.RegisterType <SendDataToSampleApi>().As <ISendDataToSampleApi>();

            builder.Register(x => Configuration.GetSection("selenium").Get <SeleniumConfig>()).As <SeleniumConfig>();
            builder.Register(x => Configuration.GetSection("sibApi").Get <SibApiConfig>()).As <SibApiConfig>();

            builder.Register(x =>
            {
                var seleniumConfig = x.Resolve <SeleniumConfig>();
                return(WebDriveFactory.CreateWebDrive(seleniumConfig.Browser, seleniumConfig.DrivePath,
                                                      seleniumConfig.Headless));
            }).As <IWebDriver>();
        }
Esempio n. 19
0
        public SwgohHelper(UserSettings settings)
        {
            User  = "******" + settings.Username;
            User += "&password="******"&grant_type=password";
            User += "&client_id=" + settings.ClientId;
            User += "&client_secret=" + settings.ClientSecret;

            Token      = null;
            ServiceUri = new UriPathBuilder(string.IsNullOrEmpty(settings.Protocol) ? "https" : settings.Protocol,
                                            string.IsNullOrEmpty(settings.Host) ? "api.swgoh.help" : settings.Host, string.IsNullOrEmpty(settings.Port) ? -1 : int.Parse(settings.Port));

            FlurlHttp.Configure(c =>
            {
                c.JsonSerializer = new NewtonsoftJsonSerializer(new JsonSerializerSettings {
                    NullValueHandling = NullValueHandling.Ignore
                });
            });
        }
Esempio n. 20
0
        private static void SetupHttp()
        {
            FlurlHttp.Configure(settings =>
            {
                var jsonSettings = new JsonSerializerSettings
                {
                    // This is important. If any DTOs are missing members, say, if Radarr or Sonarr adds one in a future
                    // version, this needs to fail to indicate that a software change is required. Otherwise, we lose
                    // state between when we request settings, and re-apply them again with a few properties modified.
                    MissingMemberHandling = MissingMemberHandling.Error,

                    // This makes sure that null properties, such as maxSize and preferredSize in Radarr
                    // Quality Definitions, do not get written out to JSON request bodies.
                    NullValueHandling = NullValueHandling.Ignore
                };

                settings.JsonSerializer = new NewtonsoftJsonSerializer(jsonSettings);
            });
        }
        /// <summary>
        /// Adds Configuration provider to work with confighub. Must be last provider in sequence. It uses appsettings.json file as source for local and remote synchronization.
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="loggerFactory">Optional, enables logging if provided</param>
        /// <returns></returns>
        public static IConfigurationBuilder AddConfigHub(this IConfigurationBuilder builder, ILoggerFactory loggerFactory = null)
        {
            FlurlHttp.Configure(config =>
                                config.JsonSerializer = new NewtonsoftJsonSerializer(new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            }));

            var appSettingsSource = builder.Sources.Where(source =>
                                                          (source is JsonConfigurationSource) &&
                                                          (source as JsonConfigurationSource).Path == "appsettings.json")
                                    .Cast <JsonConfigurationSource>()
                                    .FirstOrDefault();

            appSettingsSource.Build(builder);
            var configRoot = builder.Build();

            return(builder.Add(new ConfigurationSource(configRoot, appSettingsSource, loggerFactory)));
        }
Esempio n. 22
0
        public void Configure(IApplicationBuilder app)
        {
            FlurlHttp.Configure(
                config =>
            {
                var settings = new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                };
                config.JsonSerializer = new NewtonsoftJsonSerializer(settings);
            }
                );

            AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
            {
                logger.Trace(eventArgs.Exception);
            };

            app.UseOwin(x => x.UseNancy());
        }
Esempio n. 23
0
        /// <summary>
        /// Adds the following services: <br />
        /// <br />
        /// <see cref="IFlurlClient"/> (Singleton) <br />
        /// <see cref="ILocalStorageService"/> (Scoped) <br />
        /// <see cref="ISessionStorageService"/> (Scoped) <br />
        /// <see cref="IFlurlNavigationManager"/> (Scoped) <br />
        /// AddAuthorizationCore() <br />
        /// <see cref="YamlDotNet.Serialization.ISerializer"/> (Scoped) <br />
        /// <see cref="YamlDotNet.Serialization.IDeserializer"/> (Scoped) <br />
        /// <br />
        /// Also Configures <see cref="FlurlClient"/> with <see cref="HttpClientFactoryForBlazor"/>
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddSharedServices(this IServiceCollection services)
        {
            services.AddSingleton <IFlurlClient>(f => new FlurlClient("http://localhost:4000"));
            services.AddScoped <ILocalStorageService, LocalStorageService>();
            services.AddBlazoredSessionStorage(options =>
                                               options.JsonSerializerOptions.IgnoreNullValues = true);
            services.AddScoped <IFlurlNavigationManager, FlurlNavigationManager>();
            services.AddBootstrapCss();
            services.AddAuthorizationCore();

            services.AddScoped(f => Yaml.NewSerializer);
            services.AddScoped(f => Yaml.NewDeserializer);

            FlurlHttp.Configure(settings =>
            {
                settings.HttpClientFactory = new HttpClientFactoryForBlazor();
            });

            return(services);
        }
Esempio n. 24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RestApiClient"/> class.
        /// </summary>
        /// <param name="token">The token.</param>
        public RestApiClient(string token)
        {
            if (string.IsNullOrWhiteSpace(token))
            {
                throw new ArgumentNullException(token);
            }

            FlurlHttp.Configure(settings =>
            {
                var jsonSettings = new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver(),
                };

                settings.JsonSerializer = new NewtonsoftJsonSerializer(
                    jsonSettings);
            });

            this.token = token;
        }
Esempio n. 25
0
        private static void AddClients(this IServiceCollection services)
        {
            services.AddHttpClient <AuthClient>(client =>
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            });

            services.AddSingleton <IFlurlClientFactory>(serviceProvider =>
            {
                var auth = serviceProvider.GetService <AuthClient>();
                FlurlHttp.Configure(settings => settings.HttpClientFactory = new PollyHttpClientFactory(auth));
                return(new PerBaseUrlFlurlClientFactory());
            });

            services.AddScoped <OutboxInvoiceClient>();
            services.AddScoped <InboxInvoiceClient>();
            services.AddScoped <CommonClient>();
            services.AddScoped <EArchiveInvoiceClient>();
        }
Esempio n. 26
0
        public static IServiceCollection AddTeamCloudHttp(this IServiceCollection services, Action <GlobalFlurlHttpSettings> configure = null)
        {
            services.AddSingleton <ITelemetryInitializer>(new TeamCloudTelemetryInitializer(Assembly.GetCallingAssembly()));

            if (services.Any(sd => sd.ServiceType == typeof(IHttpClientFactory) && sd.ImplementationType == typeof(DefaultHttpClientFactory)))
            {
                services.Replace(new ServiceDescriptor(typeof(IHttpClientFactory), CreateHttpClientFactory, ServiceLifetime.Singleton));
            }
            else
            {
                services.TryAddSingleton <IHttpClientFactory>(CreateHttpClientFactory);
            }

            FlurlHttp.Configure(configuration =>
            {
                configuration.HttpClientFactory = services.BuildServiceProvider().GetRequiredService <IHttpClientFactory>();

                configure?.Invoke(configuration);
            });

            return(services);
Esempio n. 27
0
        public async Task can_handle_error()
        {
            var handlerCalled = false;

            FlurlHttp.Configure(c => {
                c.OnError = call => {
                    call.ExceptionHandled = true;
                    handlerCalled         = true;
                };
            });

            try {
                await "https://httpbin.org/status/500".GetAsync();
                Assert.IsTrue(handlerCalled, "error handler shoule have been called.");
            }
            catch (FlurlHttpException) {
                Assert.Fail("exception should have been supressed.");
            }
            finally {
                FlurlHttp.Configure(c => c.ResetDefaults());
            }
        }
Esempio n. 28
0
        private void Init()
        {
            var id = ResourceLoader.GetForViewIndependentUse("AppCenter")?.GetString("AppCenterId");

            if (!string.IsNullOrEmpty(id))
            {
                AppCenter.Start(id,
                                typeof(Analytics), typeof(Crashes));
            }
            FlurlHttp.Configure(settings =>
            {
                settings.JsonSerializer = new WeiboJsonSerializer(WeiboJsonSerializerSetting.Settings);
                //settings.UrlEncodedSerializer = new WeiboUrlEncodedSerializer();
                settings.BeforeCall = call =>
                {
                    call.Request.Headers.Add("Cookie",
                                             string.Join(";",
                                                         Singleton <Api> .Instance.GetCookies().Select(it => $"{it.Key}={it.Value}")));
                };
                settings.OnErrorAsync = async call =>
                {
                    if (call.HttpStatus == HttpStatusCode.Forbidden)
                    {
                        //maybe errno:100005
                        var json = await call.Response.Content.ReadAsStringAsync();
                        try
                        {
                            call.FlurlRequest.Client.Settings.JsonSerializer.Deserialize <JObject>(json);
                        }
                        catch (FlurlParsingException e) when(e.InnerException is WeiboException)
                        {
                            //TODO: show notification
                        }
                    }
                };
            });
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            ImageCache.Instance.InitializeAsync(httpMessageHandler: new WeiboHttpClientHandler());
        }
Esempio n. 29
0
        public async Task <Result <ChatOverview[]> > Handle(GetChatsQuery request, CancellationToken cancellationToken)
        {
            var token = request.GetToken();

            FlurlHttp.Configure(settings => settings.JsonSerializer = new NewtonsoftJsonSerializer(Converter.Settings));
            var response = await new FlurlRequest(OVERVIEW_URL)
                           .WithOAuthBearerToken(token)
                           .GetAsync()
                           .ReceiveJson <Overview>();

            var chats = response
                        .Chats
                        .Where(p => p.ChatType == ChatType.Chat);

            var members = chats
                          .SelectMany(p => p.Members)
                          .Select(p => p.Mri)
                          .Distinct()
                          .ToArray();

            var me = chats.SelectMany(p => p.Members)
                     .GroupBy(g => g.Mri)
                     .OrderByDescending(g => g.Count())
                     .First().Key;

            var users = await _mediator.Send(new GetUsersQuery { Token = token, UserIds = members });

            var conversations = chats
                                .OrderByDescending(p => p.LastMessage.ComposeTime)
                                .Select(p => new ChatOverview {
                Author      = Truncate(GetAuthor(p, me, users)),
                Time        = p.LastMessage?.ComposeTime?.ToLocalTime(),
                LastMessage = Truncate(p.LastMessage?.Content?.Replace("\n", "").Replace("\r", ""))
            })
                                .ToArray();

            return(new Result <ChatOverview[]>(conversations));
        }
Esempio n. 30
0
        private static void ConfigureFlurl()
        {
            if (_flurlConfigured)
            {
                return;
            }

            FlurlHttp.Configure(settings =>
            {
                var jsonSettings = new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    ContractResolver      = new DefaultContractResolver
                    {
                        NamingStrategy = new CamelCaseNamingStrategy()
                    }
                };
                settings.JsonSerializer    = new NewtonsoftJsonSerializer(jsonSettings);
                settings.HttpClientFactory = new PollyHttpClientFactory();
            });

            _flurlConfigured = true;
        }