using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Flurl.Http;
namespace SKIT.FlurlHttpClient.Wechat.OpenAI
{
///
/// 一个微信智能对话 API HTTP 客户端。
///
public class WechatChatbotClient : CommonClientBase, ICommonClient
{
///
/// 获取当前客户端使用的微信智能对话平台凭证。
///
public Settings.Credentials Credentials { get; }
///
/// 用指定的配置项初始化 类的新实例。
///
/// 配置项。
public WechatChatbotClient(WechatChatbotClientOptions options)
: this(options, null)
{
}
///
///
///
///
///
///
internal protected WechatChatbotClient(WechatChatbotClientOptions options, HttpClient? httpClient, bool disposeClient = true)
: base(httpClient, disposeClient)
{
if (options is null) throw new ArgumentNullException(nameof(options));
Credentials = new Settings.Credentials(options);
FlurlClient.BaseUrl = options.Endpoint ?? WechatChatbotEndpoints.DEFAULT;
FlurlClient.WithTimeout(options.Timeout <= 0 ? Timeout.InfiniteTimeSpan : TimeSpan.FromMilliseconds(options.Timeout));
}
///
/// 使用当前客户端生成一个新的 对象。
///
///
///
///
///
public IFlurlRequest CreateFlurlRequest(WechatChatbotRequest request, HttpMethod httpMethod, params object[] urlSegments)
{
IFlurlRequest flurlRequest = base.CreateFlurlRequest(request, httpMethod, urlSegments);
return flurlRequest;
}
///
/// 异步发起请求。
///
///
///
///
///
///
public async Task SendFlurlRequestAsync(IFlurlRequest flurlRequest, HttpContent? httpContent = null, CancellationToken cancellationToken = default)
where T : WechatChatbotResponse, new()
{
if (flurlRequest is null) throw new ArgumentNullException(nameof(flurlRequest));
using IFlurlResponse flurlResponse = await base.SendFlurlRequestAsync(flurlRequest, httpContent, cancellationToken).ConfigureAwait(false);
return await WrapFlurlResponseAsJsonAsync(flurlResponse, cancellationToken).ConfigureAwait(false);
}
///
/// 异步发起请求。
///
///
///
///
///
///
public async Task SendFlurlRequestAsJsonAsync(IFlurlRequest flurlRequest, object? data = null, CancellationToken cancellationToken = default)
where T : WechatChatbotResponse, new()
{
if (flurlRequest is null) throw new ArgumentNullException(nameof(flurlRequest));
if (data is WechatChatbotRequest.Serialization.IEncryptedXmlable)
{
string plainXml = Utilities.XmlHelper.ConvertFromJson(JsonSerializer.Serialize(data));
string encryptedXml = Utilities.WxMsgCryptor.AESEncrypt(plainText: plainXml, encodingAESKey: Credentials.EncodingAESKey!, appId: Credentials.AppId!);
data = new { encrypt = encryptedXml };
}
bool isSimpleRequest = data is null ||
flurlRequest.Verb == HttpMethod.Get ||
flurlRequest.Verb == HttpMethod.Head ||
flurlRequest.Verb == HttpMethod.Options;
using IFlurlResponse flurlResponse = isSimpleRequest ?
await base.SendFlurlRequestAsync(flurlRequest, null, cancellationToken).ConfigureAwait(false) :
await base.SendFlurlRequestAsJsonAsync(flurlRequest, data, cancellationToken).ConfigureAwait(false);
return await WrapFlurlResponseAsJsonAsync(flurlResponse, cancellationToken).ConfigureAwait(false);
}
}
}