Merge pull request #35 from Bubuni-Team/refactor/http-client-factory

Use HTTP client factory where possible
This commit is contained in:
Andriy
2023-07-29 00:32:51 +03:00
committed by GitHub
35 changed files with 261 additions and 170 deletions
+1
View File
@@ -55,6 +55,7 @@ namespace Kruzya.TelegramBot.Core
services.AddHostedService<DeleteService>();
services.AddScoped<IOptionProvider, DbOptionProvider>();
services.AddHttpClient();
// Trigger module handlers.
_core.Modules.ConfigureServices(services);
@@ -1,5 +1,4 @@
using System;
using System.Net.Http;
using System.Net.Http;
using System.Threading.Tasks;
using Kruzya.TelegramBot.Core.Extensions;
using Telegram.Bot.Types;
@@ -8,12 +7,11 @@ namespace Kruzya.TelegramBot.CombotAntiSpam.Combot;
public class CombotClient : ICombotClient
{
public HttpClient _HttpClient;
private readonly HttpClient _httpClient;
public CombotClient()
public CombotClient(HttpClient httpClient)
{
_HttpClient = new HttpClient();
_HttpClient.BaseAddress = new Uri("https://api.cas.chat/check");
_httpClient = httpClient;
}
public bool IsSpammer(User user)
@@ -23,7 +21,7 @@ public class CombotClient : ICombotClient
public async Task<bool> IsSpammerAsync(User user)
{
var result = await _HttpClient.GetJsonAsync<CombotApiResponse>($"?user_id={user.Id}");
var result = await _httpClient.GetJsonAsync<CombotApiResponse>($"?user_id={user.Id}");
return result.IsSpammer;
}
}
+5 -1
View File
@@ -1,6 +1,7 @@
using Kruzya.TelegramBot.CombotAntiSpam.Combot;
using Kruzya.TelegramBot.Core;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace Kruzya.TelegramBot.CombotAntiSpam;
@@ -12,6 +13,9 @@ public class CombotAntiSpam : Module
public override void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ICombotClient, CombotClient>();
services.AddHttpClient<ICombotClient, CombotClient>(c =>
{
c.BaseAddress = new Uri("https://api.cas.chat/check");
});
}
}
+8
View File
@@ -0,0 +1,8 @@
using West.TelegramBot.ContentStore.Model;
namespace West.TelegramBot.ContentStore.API;
public interface IKittiesApi
{
public Task<KittiesResponse> GetKittiesImageAsync(string type);
}
@@ -0,0 +1,8 @@
using West.TelegramBot.ContentStore.Model;
namespace West.TelegramBot.ContentStore.API;
public interface ISomeRandomApi
{
public Task<SomeRandomApiAnimalResponse> GetAnimalAsync(string animalId);
}
+28
View File
@@ -0,0 +1,28 @@
using System.Text;
using West.TelegramBot.ContentStore.Model;
namespace West.TelegramBot.ContentStore.API;
public class KittiesApi : IKittiesApi
{
private readonly HttpClient _client;
public KittiesApi(HttpClient client)
{
_client = client;
}
public async Task<KittiesResponse> GetKittiesImageAsync(string type)
{
var httpResponse = await _client.GetAsync($"v1/{type}");
var headers = httpResponse.Headers;
var titleBytes =
Convert.FromBase64String(headers.GetValues("X-Video-Title").First());
return new KittiesResponse(
await httpResponse.Content.ReadAsStreamAsync(),
headers.GetValues("X-Video-Source").First(),
Encoding.UTF8.GetString(titleBytes)
);
}
}
+21
View File
@@ -0,0 +1,21 @@
using System.Net.Http.Json;
using West.TelegramBot.ContentStore.Model;
namespace West.TelegramBot.ContentStore.API;
public class SomeRandomApi : ISomeRandomApi
{
private readonly HttpClient _client;
public SomeRandomApi(HttpClient client)
{
_client = client;
}
public async Task<SomeRandomApiAnimalResponse> GetAnimalAsync(string animalId)
{
return (await _client.GetFromJsonAsync<SomeRandomApiAnimalResponse>(
$"animal/{animalId}"
))!;
}
}
+19 -1
View File
@@ -1,7 +1,9 @@
using Kruzya.TelegramBot.Core;
using Kruzya.TelegramBot.Core.Extensions;
using Kruzya.TelegramBot.Core.Options;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Net.Http.Headers;
using West.TelegramBot.ContentStore.API;
using West.TelegramBot.ContentStore.Option;
using West.TelegramBot.ContentStore.Service;
@@ -27,6 +29,22 @@ public class ContentStore : Module
{
services.AddOption<AllowNsfw>();
var kittiesConfig = Configuration.GetSection("KittiesService");
services.AddHttpClient<IKittiesApi, KittiesApi>(c =>
{
c.BaseAddress = kittiesConfig.GetValue<Uri>("Uri");
c.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
kittiesConfig.GetValue<string>("token")
);
});
services.AddHttpClient<ISomeRandomApi, SomeRandomApi>(c =>
{
c.BaseAddress = new Uri("https://some-random-api.com");
});
foreach (var serviceType in MediaServiceTypes)
{
services.AddScoped(typeof(IRandomMediaService), serviceType);
@@ -0,0 +1,15 @@
namespace West.TelegramBot.ContentStore.Model;
public class KittiesResponse
{
public Stream Content { get; set; }
public string Source { get; set; }
public string Title { get; set; }
public KittiesResponse(Stream content, string source, string title)
{
Content = content;
Source = source;
Title = title;
}
}
@@ -1,56 +0,0 @@
using System.Net.Http.Headers;
using System.Text;
using BotFramework.Utils;
using Microsoft.Extensions.Configuration;
using Telegram.Bot.Types;
using West.TelegramBot.ContentStore.Model;
using West.TelegramBot.ContentStore.Option;
namespace West.TelegramBot.ContentStore.Service;
public abstract class AbstractKittiesService : IRandomMediaService
{
private readonly AllowNsfw _allowNsfw;
protected abstract string VideoType { get; }
public abstract StoreItem StoreItem { get; }
private readonly HttpClient _httpClient;
protected AbstractKittiesService(IConfiguration configuration, AllowNsfw allowNsfw)
{
var section = configuration.GetSection("KittiesService");
var uri = section.GetValue<Uri>("Uri");
var token = section.GetValue<string>("Token");
_httpClient = new HttpClient
{
BaseAddress = uri,
DefaultRequestHeaders =
{
Authorization = new AuthenticationHeaderValue("Bearer", token)
}
};
_allowNsfw = allowNsfw;
}
public async Task<RandomMedia> GetRandomMediaAsync()
{
var response = await _httpClient.GetAsync($"v1/{VideoType}");
var headers = response.Headers;
var videoSource = headers.GetValues("X-Video-Source").FirstOrDefault(string.Empty);
var videoTitleBase64 = headers.GetValues("X-Video-Title").FirstOrDefault(string.Empty);
var videoTitle = Encoding.UTF8.GetString(Convert.FromBase64String(videoTitleBase64));
return new RandomMedia(
new InputFile(await response.Content.ReadAsStreamAsync()),
new HtmlString().Url(videoSource, videoTitle).ToString(),
true
);
}
public async Task<bool> CanView(Chat chat, User user)
{
return await _allowNsfw.GetValueAsync(chat.Id);
}
}
@@ -15,5 +15,6 @@ public abstract class AbstractNsfwService : IRandomMediaService
_allowNsfw = allowNsfw;
}
public async Task<bool> CanView(Chat chat, User user) => await _allowNsfw.GetValueAsync(chat.Id);
public async Task<bool> CanView(Chat chat, User user)
=> await _allowNsfw.GetValueAsync(chat.Id);
}
@@ -10,12 +10,10 @@ public class AnimBoobsService : AbstractNsfwService
private readonly HttpClient _httpClient;
public override StoreItem StoreItem { get; } = new("anim_boobs", "Сиськи.gif", 120, 40);
public AnimBoobsService(AllowNsfw allowNsfw) : base(allowNsfw)
public AnimBoobsService(AllowNsfw allowNsfw, IHttpClientFactory factory) : base(allowNsfw)
{
_httpClient = new HttpClient
{
BaseAddress = new Uri("https://westdev.me/_boobs/")
};
_httpClient = factory.CreateClient();
_httpClient.BaseAddress = new Uri("https://westdev.me/_boobs/");
}
public override async Task<RandomMedia> GetRandomMediaAsync()
@@ -9,15 +9,12 @@ public abstract class AnimalAsAService : IRandomMediaService
private readonly HttpClient _httpClient;
public abstract StoreItem StoreItem { get; }
protected AnimalAsAService(Uri baseAddress)
protected AnimalAsAService(IHttpClientFactory factory, Uri baseAddress)
{
_httpClient = new HttpClient
{
BaseAddress = baseAddress
};
_httpClient = factory.CreateClient();
_httpClient.BaseAddress = baseAddress;
}
public async Task<RandomMedia> GetRandomMediaAsync()
{
var resp = await _httpClient.GetAsync("images/search");
@@ -1,7 +0,0 @@
namespace West.TelegramBot.ContentStore.Service;
public class BirdService : SomeRandomApiAbstractService
{
public BirdService(): base("bird", "Птица", 40, 165)
{}
}
@@ -5,5 +5,6 @@ namespace West.TelegramBot.ContentStore.Service;
public class CatApiService : AnimalAsAService
{
public override StoreItem StoreItem { get; } = new("cat", "Котэ", 40, 10);
public CatApiService() : base(new Uri("https://api.thecatapi.com/v1/")) {}
public CatApiService(IHttpClientFactory factory) :
base(factory, new Uri("https://api.thecatapi.com/v1/")) {}
}
@@ -5,5 +5,6 @@ namespace West.TelegramBot.ContentStore.Service;
public class DogApiService : AnimalAsAService
{
public override StoreItem StoreItem { get; } = new("dog", "Пёсель", 40, 20);
public DogApiService() : base(new Uri("https://api.thedogapi.com/v1/")) {}
public DogApiService(IHttpClientFactory factory) :
base(factory, new Uri("https://api.thedogapi.com/v1/")) {}
}
@@ -1,7 +0,0 @@
namespace West.TelegramBot.ContentStore.Service;
public class FoxService : SomeRandomApiAbstractService
{
public FoxService(): base("fox", "Лисица", 40, 170)
{}
}
@@ -1,7 +0,0 @@
namespace West.TelegramBot.ContentStore.Service;
public class KangarooService : SomeRandomApiAbstractService
{
public KangarooService(): base("kangaroo", "Кенгуру", 40, 175)
{}
}
@@ -0,0 +1,38 @@
using BotFramework.Utils;
using Telegram.Bot.Types;
using West.TelegramBot.ContentStore.API;
using West.TelegramBot.ContentStore.Model;
using West.TelegramBot.ContentStore.Option;
namespace West.TelegramBot.ContentStore.Service.Kitties;
public abstract class AbstractKittiesService : IRandomMediaService
{
private readonly IKittiesApi _api;
private readonly AllowNsfw _allowNsfw;
protected abstract string VideoType { get; }
public abstract StoreItem StoreItem { get; }
protected AbstractKittiesService(IKittiesApi api, AllowNsfw allowNsfw)
{
_api = api;
_allowNsfw = allowNsfw;
}
public async Task<RandomMedia> GetRandomMediaAsync()
{
var response = await _api.GetKittiesImageAsync(VideoType);
return new RandomMedia(
new InputFile(response.Content),
new HtmlString().Url(response.Source, response.Title).ToString(),
true
);
}
public async Task<bool> CanView(Chat chat, User user)
{
return await _allowNsfw.GetValueAsync(chat.Id);
}
}
@@ -1,15 +1,17 @@
using Kruzya.TelegramBot.Core.Data;
using Microsoft.Extensions.Configuration;
using West.TelegramBot.ContentStore.API;
using West.TelegramBot.ContentStore.Model;
using West.TelegramBot.ContentStore.Option;
namespace West.TelegramBot.ContentStore.Service;
namespace West.TelegramBot.ContentStore.Service.Kitties;
public class GayKittiesService : AbstractKittiesService
{
public GayKittiesService(IConfiguration configuration, AllowNsfw allowNsfw) : base(configuration, allowNsfw)
public GayKittiesService(IKittiesApi api, AllowNsfw allowNsfw) : base(api, allowNsfw)
{
}
protected override string VideoType => "gay";
public override StoreItem StoreItem { get; } = new("kitties_gay", "Прон (не геи)", 40, 110);}
public override StoreItem StoreItem { get; } = new("kitties_gay", "Прон (не геи)", 40, 110);
}
@@ -1,16 +1,16 @@
using Kruzya.TelegramBot.Core.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration;
using West.TelegramBot.ContentStore.API;
using West.TelegramBot.ContentStore.Model;
using West.TelegramBot.ContentStore.Option;
namespace West.TelegramBot.ContentStore.Service;
namespace West.TelegramBot.ContentStore.Service.Kitties;
public class StraightKittiesService : AbstractKittiesService
{
protected override string VideoType => "straight";
public override StoreItem StoreItem { get; } = new("kitties_straight", "Прон", 40, 100);
public StraightKittiesService(IConfiguration configuration, AllowNsfw allowNsfw) : base(configuration, allowNsfw)
public StraightKittiesService(IKittiesApi api, AllowNsfw allowNsfw) : base(api, allowNsfw)
{
}
}
@@ -1,7 +0,0 @@
namespace West.TelegramBot.ContentStore.Service;
public class KoalaService : SomeRandomApiAbstractService
{
public KoalaService() : base("koala", "Коала", 40, 180)
{}
}
@@ -12,12 +12,10 @@ public class OBoobsService : AbstractNsfwService
private readonly HttpClient _httpClient;
public override StoreItem StoreItem { get; } = new("boobs", "Сиськи", 60, 30);
public OBoobsService(AllowNsfw allowNsfw) : base(allowNsfw)
public OBoobsService(AllowNsfw allowNsfw, IHttpClientFactory factory) : base(allowNsfw)
{
_httpClient = new HttpClient
{
BaseAddress = new Uri("http://api.oboobs.ru")
};
_httpClient = factory.CreateClient();
_httpClient.BaseAddress = new Uri("http://api.oboobs.ru");
}
public override async Task<RandomMedia> GetRandomMediaAsync()
@@ -1,7 +0,0 @@
namespace West.TelegramBot.ContentStore.Service;
public class PandaService : SomeRandomApiAbstractService
{
public PandaService(): base("panda", "Панда", 40, 160)
{}
}
@@ -1,7 +0,0 @@
namespace West.TelegramBot.ContentStore.Service;
public class RaccoonService : SomeRandomApiAbstractService
{
public RaccoonService(): base("raccoon", "Енот", 40, 160)
{}
}
@@ -1,7 +0,0 @@
namespace West.TelegramBot.ContentStore.Service;
public class RedPandaService : SomeRandomApiAbstractService
{
public RedPandaService(): base("red_panda", "Красная панда", 40, 150)
{}
}
@@ -0,0 +1,9 @@
using West.TelegramBot.ContentStore.API;
namespace West.TelegramBot.ContentStore.Service.SomeRandomApi;
public class BirdService : SomeRandomApiAbstractService
{
public BirdService(ISomeRandomApi api) : base(api, "bird", "Птица", 40, 165)
{ }
}
@@ -0,0 +1,9 @@
using West.TelegramBot.ContentStore.API;
namespace West.TelegramBot.ContentStore.Service.SomeRandomApi;
public class FoxService : SomeRandomApiAbstractService
{
public FoxService(ISomeRandomApi api) : base(api, "fox", "Лисица", 40, 170)
{ }
}
@@ -0,0 +1,9 @@
using West.TelegramBot.ContentStore.API;
namespace West.TelegramBot.ContentStore.Service.SomeRandomApi;
public class KangarooService : SomeRandomApiAbstractService
{
public KangarooService(ISomeRandomApi api) : base(api, "kangaroo", "Кенгуру", 40, 175)
{ }
}
@@ -0,0 +1,9 @@
using West.TelegramBot.ContentStore.API;
namespace West.TelegramBot.ContentStore.Service.SomeRandomApi;
public class KoalaService : SomeRandomApiAbstractService
{
public KoalaService(ISomeRandomApi api) : base(api, "koala", "Коала", 40, 180)
{ }
}
@@ -0,0 +1,9 @@
using West.TelegramBot.ContentStore.API;
namespace West.TelegramBot.ContentStore.Service.SomeRandomApi;
public class PandaService : SomeRandomApiAbstractService
{
public PandaService(ISomeRandomApi api) : base(api, "panda", "Панда", 40, 160)
{ }
}
@@ -0,0 +1,9 @@
using West.TelegramBot.ContentStore.API;
namespace West.TelegramBot.ContentStore.Service.SomeRandomApi;
public class RaccoonService : SomeRandomApiAbstractService
{
public RaccoonService(ISomeRandomApi api) : base(api, "raccoon", "Енот", 40, 160)
{ }
}
@@ -0,0 +1,9 @@
using West.TelegramBot.ContentStore.API;
namespace West.TelegramBot.ContentStore.Service.SomeRandomApi;
public class RedPandaService : SomeRandomApiAbstractService
{
public RedPandaService(ISomeRandomApi api) : base(api, "red_panda", "Красная панда", 40, 150)
{ }
}
@@ -0,0 +1,25 @@
using Telegram.Bot.Types;
using West.TelegramBot.ContentStore.API;
using West.TelegramBot.ContentStore.Model;
namespace West.TelegramBot.ContentStore.Service.SomeRandomApi;
public abstract class SomeRandomApiAbstractService : IRandomMediaService
{
private readonly ISomeRandomApi _api;
public StoreItem StoreItem { get; }
protected SomeRandomApiAbstractService(ISomeRandomApi api, string id, string name, double price, int order)
{
StoreItem = new(id, name, price, order);
_api = api;
}
public async Task<RandomMedia> GetRandomMediaAsync()
{
var image = await _api.GetAnimalAsync(StoreItem.Id);
return new RandomMedia(new InputFileUrl(image.Image), image.Fact);
}
}
@@ -1,29 +0,0 @@
using Newtonsoft.Json;
using Telegram.Bot.Types;
using West.TelegramBot.ContentStore.Model;
namespace West.TelegramBot.ContentStore.Service;
public abstract class SomeRandomApiAbstractService : IRandomMediaService
{
public StoreItem StoreItem { get; }
public string ApiId => StoreItem.Id;
private readonly HttpClient _httpClient;
public SomeRandomApiAbstractService(string id, string name, double price, int order)
{
StoreItem = new(id, name, price, order);
// TODO: use factory or something, cause we have a lot of http clients in use
_httpClient = new HttpClient();
}
public async Task<RandomMedia> GetRandomMediaAsync()
{
var response = await _httpClient.GetStringAsync($"https://some-random-api.com/animal/{ApiId}");
var image = JsonConvert.DeserializeObject<SomeRandomApiAnimalResponse>(response)!;
return new RandomMedia(new InputFileUrl(image.Image), image.Fact);
}
}