using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Flurl.Http;
namespace SKIT.FlurlHttpClient.Wechat.OpenAI
{
///
/// 一个微信智能对话平台接入 API HTTP 客户端。
///
public class WechatOpenAIPlatformClient : CommonClientBase, ICommonClient
{
///
/// 获取当前客户端使用的微信智能对话平台凭证。
///
public Settings.PlatformCredentials Credentials { get; }
///
/// 用指定的配置项初始化 类的新实例。
///
/// 配置项。
public WechatOpenAIPlatformClient(WechatOpenAIPlatformClientOptions options)
: base()
{
if (options == null) throw new ArgumentNullException(nameof(options));
Credentials = new Settings.PlatformCredentials(options);
FlurlClient.BaseUrl = options.Endpoints ?? WechatOpenAIPlatformEndpoints.DEFAULT;
FlurlClient.WithTimeout(TimeSpan.FromMilliseconds(options.Timeout));
}
///
/// 用指定的微信智能对话 AppId、Token、EncodingAESKey 初始化 类的新实例。
///
/// 微信智能对话 AppId。
/// 微信智能对话 Token。
/// 微信智能对话 EncodingAESKey。
public WechatOpenAIPlatformClient(string appId, string token, string encodingAESKey)
: this(new WechatOpenAIPlatformClientOptions() { AppId = appId, Token = token, EncodingAESKey = encodingAESKey })
{
}
///
/// 使用当前客户端生成一个新的 对象。
///
///
///
///
///
public IFlurlRequest CreateRequest(WechatOpenAIPlatformRequest request, HttpMethod method, params object[] urlSegments)
{
IFlurlRequest flurlRequest = FlurlClient.Request(urlSegments).WithVerb(method);
if (request.Timeout != null)
{
flurlRequest.WithTimeout(TimeSpan.FromMilliseconds(request.Timeout.Value));
}
return flurlRequest;
}
///
/// 异步发起请求。
///
///
///
///
///
///
public async Task SendRequestAsync(IFlurlRequest flurlRequest, HttpContent? httpContent = null, CancellationToken cancellationToken = default)
where T : WechatOpenAIPlatformResponse, new()
{
try
{
using IFlurlResponse flurlResponse = await base.SendRequestAsync(flurlRequest, httpContent, cancellationToken).ConfigureAwait(false);
return await GetResposneAsync(flurlResponse).ConfigureAwait(false);
}
catch (FlurlHttpException ex)
{
throw new WechatOpenAIException(ex.Message, ex);
}
}
///
/// 异步发起请求。
///
///
///
///
///
///
public async Task SendRequestWithJsonAsync(IFlurlRequest flurlRequest, object? data = null, CancellationToken cancellationToken = default)
where T : WechatOpenAIPlatformResponse, new()
{
try
{
if (data is WechatOpenAIPlatformRequest.Serialization.IEncryptedXmlable)
{
string plainXml = Utilities.XmlUtility.Serialize(data);
string encryptedXml = Utilities.WxBizMsgCryptor.AESEncrypt(plainText: plainXml, encodingAESKey: Credentials.EncodingAESKey!, appId: Credentials.AppId!);
data = new { encrypt = encryptedXml };
}
using IFlurlResponse flurlResponse = await base.SendRequestWithJsonAsync(flurlRequest, data, cancellationToken).ConfigureAwait(false);
return await GetResposneAsync(flurlResponse).ConfigureAwait(false);
}
catch (FlurlHttpException ex)
{
throw new WechatOpenAIException(ex.Message, ex);
}
}
///
/// 异步发起请求。
///
///
///
///
///
///
public async Task SendRequestWithUrlEncodedAsync(IFlurlRequest flurlRequest, object? data = null, CancellationToken cancellationToken = default)
where T : WechatOpenAIPlatformResponse, new()
{
try
{
if (data is WechatOpenAIPlatformRequest.Serialization.IEncryptedUrlEncoded)
{
string jwt = Utilities.JWTUtility.EncodeWithHS256(payload: data, secret: Credentials.EncodingAESKey!);
data = new { query = jwt };
}
using IFlurlResponse flurlResponse = await flurlRequest
.WithClient(FlurlClient)
.AllowAnyHttpStatus()
.SendUrlEncodedAsync(flurlRequest.Verb, data, cancellationToken)
.ConfigureAwait(false);
return await GetResposneAsync(flurlResponse).ConfigureAwait(false);
}
catch (FlurlHttpException ex)
{
throw new WechatOpenAIException(ex.Message, ex);
}
}
private async Task GetResposneAsync(IFlurlResponse flurlResponse)
where T : WechatOpenAIPlatformResponse, new()
{
byte[] bytes = await flurlResponse.GetBytesAsync().ConfigureAwait(false);
bool jsonable =
(bytes.Length > 1 && bytes[0] == 91 && bytes[bytes.Length - 1] == 93) || // "[...]"
(bytes.Length > 1 && bytes[0] == 123 && bytes[bytes.Length - 1] == 125); // "{...}"
T result = jsonable ? JsonSerializer.Deserialize(Encoding.UTF8.GetString(bytes)) : new T();
result.RawStatus = flurlResponse.StatusCode;
result.RawHeaders = new ReadOnlyDictionary(
flurlResponse.Headers
.GroupBy(e => e.Name)
.ToDictionary(
k => k.Key,
v => string.Join(", ", v.Select(e => e.Value))
)
);
result.RawBytes = bytes;
return result;
}
}
}