Reuse httpclient, create in Util

This commit is contained in:
Raymond 2021-11-10 11:56:39 -05:00
parent 93863dbc8a
commit 321f39dc55
7 changed files with 34 additions and 28 deletions

View file

@ -1,3 +1,5 @@
using System.Threading.Tasks;
using Dalamud.Game.Network.Structures; using Dalamud.Game.Network.Structures;
namespace Dalamud.Game.Network.Internal.MarketBoardUploaders namespace Dalamud.Game.Network.Internal.MarketBoardUploaders
@ -11,18 +13,21 @@ namespace Dalamud.Game.Network.Internal.MarketBoardUploaders
/// Upload data about an item. /// Upload data about an item.
/// </summary> /// </summary>
/// <param name="item">The item request data being uploaded.</param> /// <param name="item">The item request data being uploaded.</param>
void Upload(MarketBoardItemRequest item); /// <returns>An async task.</returns>
Task Upload(MarketBoardItemRequest item);
/// <summary> /// <summary>
/// Upload tax rate data. /// Upload tax rate data.
/// </summary> /// </summary>
/// <param name="taxRates">The tax rate data being uploaded.</param> /// <param name="taxRates">The tax rate data being uploaded.</param>
void UploadTax(MarketTaxRates taxRates); /// <returns>An async task.</returns>
Task UploadTax(MarketTaxRates taxRates);
/// <summary> /// <summary>
/// Upload information about a purchase this client has made. /// Upload information about a purchase this client has made.
/// </summary> /// </summary>
/// <param name="purchaseHandler">The purchase handler data associated with the sale.</param> /// <param name="purchaseHandler">The purchase handler data associated with the sale.</param>
void UploadPurchase(MarketBoardPurchaseHandler purchaseHandler); /// <returns>An async task.</returns>
Task UploadPurchase(MarketBoardPurchaseHandler purchaseHandler);
} }
} }

View file

@ -1,11 +1,12 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers;
using System.Text; using System.Text;
using System.Threading.Tasks;
using Dalamud.Game.Network.Internal.MarketBoardUploaders.Universalis.Types; using Dalamud.Game.Network.Internal.MarketBoardUploaders.Universalis.Types;
using Dalamud.Game.Network.Structures; using Dalamud.Game.Network.Structures;
using Dalamud.Utility;
using Newtonsoft.Json; using Newtonsoft.Json;
using Serilog; using Serilog;
@ -29,10 +30,9 @@ namespace Dalamud.Game.Network.Internal.MarketBoardUploaders.Universalis
} }
/// <inheritdoc/> /// <inheritdoc/>
public void Upload(MarketBoardItemRequest request) public async Task Upload(MarketBoardItemRequest request)
{ {
var clientState = Service<ClientState.ClientState>.Get(); var clientState = Service<ClientState.ClientState>.Get();
using var client = new HttpClient();
Log.Verbose("Starting Universalis upload."); Log.Verbose("Starting Universalis upload.");
var uploader = clientState.LocalContentId; var uploader = clientState.LocalContentId;
@ -80,7 +80,7 @@ namespace Dalamud.Game.Network.Internal.MarketBoardUploaders.Universalis
var listingPath = "/upload"; var listingPath = "/upload";
var listingUpload = JsonConvert.SerializeObject(listingsUploadObject); var listingUpload = JsonConvert.SerializeObject(listingsUploadObject);
Log.Verbose($"{listingPath}: {listingUpload}"); Log.Verbose($"{listingPath}: {listingUpload}");
client.PostAsync($"{ApiBase}{listingPath}/{ApiKey}", new StringContent(listingUpload, Encoding.UTF8, "application/json")).GetAwaiter().GetResult(); await Util.HttpClient.PostAsync($"{ApiBase}{listingPath}/{ApiKey}", new StringContent(listingUpload, Encoding.UTF8, "application/json"));
// ==================================================================================== // ====================================================================================
@ -108,7 +108,7 @@ namespace Dalamud.Game.Network.Internal.MarketBoardUploaders.Universalis
var historyPath = "/upload"; var historyPath = "/upload";
var historyUpload = JsonConvert.SerializeObject(historyUploadObject); var historyUpload = JsonConvert.SerializeObject(historyUploadObject);
Log.Verbose($"{historyPath}: {historyUpload}"); Log.Verbose($"{historyPath}: {historyUpload}");
client.PostAsync($"{ApiBase}{historyPath}/{ApiKey}", new StringContent(historyUpload, Encoding.UTF8, "application/json")).GetAwaiter().GetResult(); await Util.HttpClient.PostAsync($"{ApiBase}{historyPath}/{ApiKey}", new StringContent(historyUpload, Encoding.UTF8, "application/json"));
// ==================================================================================== // ====================================================================================
@ -116,10 +116,9 @@ namespace Dalamud.Game.Network.Internal.MarketBoardUploaders.Universalis
} }
/// <inheritdoc/> /// <inheritdoc/>
public void UploadTax(MarketTaxRates taxRates) public async Task UploadTax(MarketTaxRates taxRates)
{ {
var clientState = Service<ClientState.ClientState>.Get(); var clientState = Service<ClientState.ClientState>.Get();
using var client = new HttpClient();
// ==================================================================================== // ====================================================================================
@ -142,7 +141,7 @@ namespace Dalamud.Game.Network.Internal.MarketBoardUploaders.Universalis
var taxUpload = JsonConvert.SerializeObject(taxUploadObject); var taxUpload = JsonConvert.SerializeObject(taxUploadObject);
Log.Verbose($"{taxPath}: {taxUpload}"); Log.Verbose($"{taxPath}: {taxUpload}");
client.PostAsync($"{ApiBase}{taxPath}/{ApiKey}", new StringContent(taxUpload, Encoding.UTF8, "application/json")).GetAwaiter().GetResult(); await Util.HttpClient.PostAsync($"{ApiBase}{taxPath}/{ApiKey}", new StringContent(taxUpload, Encoding.UTF8, "application/json"));
// ==================================================================================== // ====================================================================================
@ -155,12 +154,9 @@ namespace Dalamud.Game.Network.Internal.MarketBoardUploaders.Universalis
/// to track the available listings, that is done via the listings packet. All this does is remove /// to track the available listings, that is done via the listings packet. All this does is remove
/// a listing, or delete it, when a purchase has been made. /// a listing, or delete it, when a purchase has been made.
/// </remarks> /// </remarks>
public void UploadPurchase(MarketBoardPurchaseHandler purchaseHandler) public async Task UploadPurchase(MarketBoardPurchaseHandler purchaseHandler)
{ {
var clientState = Service<ClientState.ClientState>.Get(); var clientState = Service<ClientState.ClientState>.Get();
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(ApiKey);
var itemId = purchaseHandler.CatalogId; var itemId = purchaseHandler.CatalogId;
var worldId = clientState.LocalPlayer?.CurrentWorld.Id ?? 0; var worldId = clientState.LocalPlayer?.CurrentWorld.Id ?? 0;
@ -180,7 +176,10 @@ namespace Dalamud.Game.Network.Internal.MarketBoardUploaders.Universalis
var deleteListing = JsonConvert.SerializeObject(deleteListingObject); var deleteListing = JsonConvert.SerializeObject(deleteListingObject);
Log.Verbose($"{deletePath}: {deleteListing}"); Log.Verbose($"{deletePath}: {deleteListing}");
client.PostAsync($"{ApiBase}{deletePath}", new StringContent(deleteListing, Encoding.UTF8, "application/json")).GetAwaiter().GetResult(); var content = new StringContent(deleteListing, Encoding.UTF8, "application/json");
content.Headers.Add("Authorization", ApiKey);
await Util.HttpClient.PostAsync($"{ApiBase}{deletePath}", content);
// ==================================================================================== // ====================================================================================

View file

@ -44,8 +44,6 @@ namespace Dalamud.Interface.Internal.Windows
// TODO: Change back to master after release // TODO: Change back to master after release
private const string MainRepoImageUrl = "https://raw.githubusercontent.com/goatcorp/DalamudPlugins/api4/{0}/{1}/images/{2}"; private const string MainRepoImageUrl = "https://raw.githubusercontent.com/goatcorp/DalamudPlugins/api4/{0}/{1}/images/{2}";
private readonly HttpClient httpClient = new();
private BlockingCollection<Func<Task>> downloadQueue = new(); private BlockingCollection<Func<Task>> downloadQueue = new();
private CancellationTokenSource downloadToken = new(); private CancellationTokenSource downloadToken = new();
@ -264,7 +262,7 @@ namespace Dalamud.Interface.Internal.Windows
HttpResponseMessage data; HttpResponseMessage data;
try try
{ {
data = await this.httpClient.GetAsync(url); data = await Util.HttpClient.GetAsync(url);
} }
catch (InvalidOperationException) catch (InvalidOperationException)
{ {
@ -381,7 +379,7 @@ namespace Dalamud.Interface.Internal.Windows
HttpResponseMessage data; HttpResponseMessage data;
try try
{ {
data = await this.httpClient.GetAsync(url); data = await Util.HttpClient.GetAsync(url);
} }
catch (InvalidOperationException) catch (InvalidOperationException)
{ {

View file

@ -409,8 +409,7 @@ namespace Dalamud.Plugin.Internal
var downloadUrl = useTesting ? repoManifest.DownloadLinkTesting : repoManifest.DownloadLinkInstall; var downloadUrl = useTesting ? repoManifest.DownloadLinkTesting : repoManifest.DownloadLinkInstall;
var version = useTesting ? repoManifest.TestingAssemblyVersion : repoManifest.AssemblyVersion; var version = useTesting ? repoManifest.TestingAssemblyVersion : repoManifest.AssemblyVersion;
using var client = new HttpClient(); var response = await Util.HttpClient.GetAsync(downloadUrl);
var response = await client.GetAsync(downloadUrl);
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
var outputDir = new DirectoryInfo(Path.Combine(this.pluginDirectory.FullName, repoManifest.InternalName, version.ToString())); var outputDir = new DirectoryInfo(Path.Combine(this.pluginDirectory.FullName, repoManifest.InternalName, version.ToString()));

View file

@ -6,6 +6,7 @@ using System.Threading.Tasks;
using Dalamud.Logging.Internal; using Dalamud.Logging.Internal;
using Dalamud.Plugin.Internal.Types; using Dalamud.Plugin.Internal.Types;
using Dalamud.Utility;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace Dalamud.Plugin.Internal namespace Dalamud.Plugin.Internal
@ -74,10 +75,9 @@ namespace Dalamud.Plugin.Internal
try try
{ {
Log.Information($"Fetching repo: {this.PluginMasterUrl}"); Log.Information($"Fetching repo: {this.PluginMasterUrl}");
using var client = new HttpClient();
// ?ticks causes a cache invalidation. Get a fresh repo every time. // ?ticks causes a cache invalidation. Get a fresh repo every time.
using var response = await client.GetAsync(this.PluginMasterUrl + "?" + DateTime.Now.Ticks); using var response = await Util.HttpClient.GetAsync(this.PluginMasterUrl + "?" + DateTime.Now.Ticks);
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
var data = await response.Content.ReadAsStringAsync(); var data = await response.Content.ReadAsStringAsync();

View file

@ -1,4 +1,4 @@
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -28,8 +28,6 @@ namespace Dalamud.Support
if (content.IsNullOrWhitespace()) if (content.IsNullOrWhitespace())
return; return;
using var client = new HttpClient();
var model = new FeedbackModel var model = new FeedbackModel
{ {
Content = content, Content = content,
@ -45,7 +43,7 @@ namespace Dalamud.Support
} }
var postContent = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json"); var postContent = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
var response = await client.PostAsync(BugBaitUrl, postContent); var response = await Util.HttpClient.PostAsync(BugBaitUrl, postContent);
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
} }

View file

@ -3,6 +3,7 @@ using System.Diagnostics;
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
using System.Linq; using System.Linq;
using System.Net.Http;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
@ -23,6 +24,12 @@ namespace Dalamud.Utility
{ {
private static string gitHashInternal; private static string gitHashInternal;
/// <summary>
/// Gets an httpclient for usage.
/// Do NOT await this.
/// </summary>
public static HttpClient HttpClient { get; } = new();
/// <summary> /// <summary>
/// Gets the assembly version of Dalamud. /// Gets the assembly version of Dalamud.
/// </summary> /// </summary>