Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd674dcc31 | ||
|
|
141846d79d | ||
|
|
a4bae0226e | ||
|
|
15f74b6570 | ||
|
|
ac4619a789 | ||
|
|
4d0f801f21 | ||
|
|
683cf9176a | ||
|
|
1ee8d941e9 |
@@ -0,0 +1,235 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Microsoft.Extensions.Caching.Distributed;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using SimApi.Communications;
|
||||||
|
using SimApi.Configurations;
|
||||||
|
using SimApi.Helpers;
|
||||||
|
|
||||||
|
namespace SimApi.CoceSdk;
|
||||||
|
|
||||||
|
public class CoceApp(SimApiOptions simApiOptions, ILogger<CoceApp> logger, IDistributedCache cache)
|
||||||
|
{
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取Level Token
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="lv1Token"></param>
|
||||||
|
/// <param name="level"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public LevelTokenResponse? GetLevelToken(string lv1Token, int level = 5)
|
||||||
|
{
|
||||||
|
var dict = new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
{ "lv1Token", lv1Token },
|
||||||
|
{ "time", (int)SimApiUtil.TimestampNow },
|
||||||
|
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
|
||||||
|
{ "level", level }
|
||||||
|
};
|
||||||
|
return QueryAppApi<LevelTokenResponse>("/api/app/token", dict);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 通过用户手机号搜索用户
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="phone"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public UserInfo? SearchUserByPhone(string phone)
|
||||||
|
{
|
||||||
|
var dict = new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
{ "cell", phone },
|
||||||
|
{ "time", (int)SimApiUtil.TimestampNow },
|
||||||
|
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
|
||||||
|
};
|
||||||
|
return QueryAppApi<UserInfo>("/api/app/user/search-by-phone", dict);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 通过给出的UserId列表获取用户信息
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="userIds"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public UserInfo[]? SearchUserByIds(IEnumerable<string> userIds)
|
||||||
|
{
|
||||||
|
var dict = new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
{ "ids", string.Join(",", userIds) },
|
||||||
|
{ "time", (int)SimApiUtil.TimestampNow },
|
||||||
|
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
|
||||||
|
};
|
||||||
|
return QueryAppApi<UserInfo[]>("/api/app/user/search-by-ids", dict);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 向用户发送消息
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="userId"></param>
|
||||||
|
/// <param name="title"></param>
|
||||||
|
/// <param name="content"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public bool SendUserMessage(string userId, string title, string content)
|
||||||
|
{
|
||||||
|
var dict = new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
{ "time", (int)SimApiUtil.TimestampNow },
|
||||||
|
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
|
||||||
|
{ "userId", userId },
|
||||||
|
{ "type", "text" },
|
||||||
|
{ "title", title },
|
||||||
|
{ "text", content }
|
||||||
|
};
|
||||||
|
return QueryAppApiNoResp("/api/app/message", dict);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建交易订单号
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="name"></param>
|
||||||
|
/// <param name="amount"></param>
|
||||||
|
/// <param name="ext"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public string? TradeCreate(string name, int amount, string ext)
|
||||||
|
{
|
||||||
|
var dict = new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
{ "time", (int)SimApiUtil.TimestampNow },
|
||||||
|
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
|
||||||
|
{ "amount", amount },
|
||||||
|
{ "ext", ext },
|
||||||
|
{ "name", name }
|
||||||
|
};
|
||||||
|
return QueryAppApi<string>("/api/app/trade/create", dict);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 查询订单状态
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="tradeNo"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public CheckTradeResponse? TradeCheck(string tradeNo)
|
||||||
|
{
|
||||||
|
var dict = new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
{ "time", (int)SimApiUtil.TimestampNow },
|
||||||
|
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
|
||||||
|
{ "tradeNo", tradeNo }
|
||||||
|
};
|
||||||
|
return QueryAppApi<CheckTradeResponse>("/api/app/trade/result", dict);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 对订单进行退款
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="tradeNo"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public bool TradeRefund(string tradeNo)
|
||||||
|
{
|
||||||
|
var dict = new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
{ "time", (int)SimApiUtil.TimestampNow },
|
||||||
|
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
|
||||||
|
{ "tradeNo", tradeNo }
|
||||||
|
};
|
||||||
|
return QueryAppApiNoResp("/api/app/trade/refund", dict);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private T? QueryAppApi<T>(string endpoint, Dictionary<string, object> request)
|
||||||
|
{
|
||||||
|
var response = QueryAppApi(endpoint, request);
|
||||||
|
var result = response.Content.ReadFromJsonAsync<SimApiBaseResponse<T>>().Result!;
|
||||||
|
if (result.Code == 200) return result.Data;
|
||||||
|
logger.LogDebug("发生错误: {Code} => {Message}", result.Code, result.Message);
|
||||||
|
return default;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool QueryAppApiNoResp(string endpoint, Dictionary<string, object> request)
|
||||||
|
{
|
||||||
|
var response = QueryAppApi(endpoint, request);
|
||||||
|
var result = response.Content.ReadFromJsonAsync<SimApiBaseResponse>().Result!;
|
||||||
|
return result.Code == 200;
|
||||||
|
}
|
||||||
|
|
||||||
|
private HttpResponseMessage QueryAppApi(string endpoint, Dictionary<string, object> request)
|
||||||
|
{
|
||||||
|
var platUrl = simApiOptions.CoceSdkOptions.ApiEndpoint + endpoint;
|
||||||
|
var sorted = request.OrderBy(x => x.Key);
|
||||||
|
var signStr = sorted.Aggregate("", (current, item) => current + $"{item.Key}={item.Value}&").TrimEnd('&');
|
||||||
|
logger.LogDebug("签名的字符串: {SignStr}", signStr);
|
||||||
|
var sign = SimApiUtil.Md5(signStr + simApiOptions.CoceSdkOptions.AppKey);
|
||||||
|
logger.LogDebug("签名: {Sign}", sign);
|
||||||
|
request.Add("sign", sign);
|
||||||
|
logger.LogDebug("请求地址: {PlatUrl} => {Data}", platUrl, JsonSerializer.Serialize(request));
|
||||||
|
var http = new HttpClient();
|
||||||
|
return http.PostAsJsonAsync(platUrl, request).Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取用户的群组信息
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="token">Level >=2 的Token</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public IEnumerable<GroupInfo>? GetUserGroups(string token)
|
||||||
|
{
|
||||||
|
const string uri = "/api/lv2/user/groups";
|
||||||
|
var resp = ProxyQuery<GroupInfo[]>(uri, token,"{}");
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取用户信息
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="token"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public UserInfo? GetUserInfo(string token)
|
||||||
|
{
|
||||||
|
const string uri = "/api/lv1/user/info";
|
||||||
|
return ProxyQuery<UserInfo>(uri, token);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SaveToken(string userId, string levelToken)
|
||||||
|
{
|
||||||
|
cache.SetString($"LEVEL:TOKEN:{userId}", levelToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
public string? GetToken(string userId)
|
||||||
|
{
|
||||||
|
return cache.GetString($"LEVEL:TOKEN:{userId}");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public dynamic? ProxyQuery(string uri, string token, string json) => ProxyQuery<dynamic>(uri, token, json);
|
||||||
|
|
||||||
|
public dynamic? ProxyQueue(string uri, string token, object data) =>
|
||||||
|
ProxyQuery<dynamic>(uri, token, JsonSerializer.Serialize(data));
|
||||||
|
|
||||||
|
public T? ProxyQueue<T>(string uri, string token, object data) =>
|
||||||
|
ProxyQuery<T>(uri, token, JsonSerializer.Serialize(data));
|
||||||
|
|
||||||
|
public T? ProxyQuery<T>(string uri, string token, string json = "{}")
|
||||||
|
{
|
||||||
|
var http = new HttpClient();
|
||||||
|
http.DefaultRequestHeaders.Add("Token", token);
|
||||||
|
var realUrl = simApiOptions.CoceSdkOptions.ApiEndpoint + uri;
|
||||||
|
var response = http.PostAsync(realUrl, new StringContent(json, Encoding.UTF8, "application/json"))
|
||||||
|
.Result;
|
||||||
|
var resp = response.Content.ReadFromJsonAsync<SimApiBaseResponse<T>>().Result!;
|
||||||
|
if (resp.Code != 200)
|
||||||
|
{
|
||||||
|
logger.LogDebug("请求发生错误: {RespCode} => {RespMessage}", resp.Code, resp.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return resp.Code == 200 ? resp.Data : default;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ConfigResponse GetConfig()
|
||||||
|
{
|
||||||
|
return new ConfigResponse(simApiOptions.CoceSdkOptions.AppId!, simApiOptions.CoceSdkOptions.AuthEndpoint);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace SimApi.CoceSdk;
|
||||||
|
|
||||||
|
public class CoceAppSdkOption
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* 中心API服务器地址
|
||||||
|
*/
|
||||||
|
public string ApiEndpoint { get; set; } = "https://api.coce.cc";
|
||||||
|
|
||||||
|
public string AuthEndpoint { get; set; } = "https://home.coce.cc";
|
||||||
|
|
||||||
|
public string? AppId { get; set; }
|
||||||
|
|
||||||
|
public string? AppKey { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace SimApi.CoceSdk;
|
||||||
|
|
||||||
|
public record ConfigResponse(string AppId, string AuthUrl);
|
||||||
|
|
||||||
|
public record LevelTokenResponse(string Token, string UserId, int TokenLevel);
|
||||||
|
|
||||||
|
public record GroupInfo(string Id, string Name, string Image, string Description, string Role);
|
||||||
|
|
||||||
|
public record UserInfo(string UserId, string Name, string Image);
|
||||||
|
|
||||||
|
public record CheckTradeResponse(
|
||||||
|
string TradeNo,
|
||||||
|
int Amount,
|
||||||
|
int Fee,
|
||||||
|
string Name,
|
||||||
|
string? Ext,
|
||||||
|
string Status,
|
||||||
|
DateTime CreatedAt,
|
||||||
|
DateTime? FinishedAt,
|
||||||
|
DateTime? RefundAt,
|
||||||
|
DateTime? CloseAt);
|
||||||
|
|
||||||
|
public class UserInfoWithGroup
|
||||||
|
{
|
||||||
|
public string? UserId { get; set; }
|
||||||
|
|
||||||
|
public string? Name { get; set; }
|
||||||
|
|
||||||
|
public string? LevelToken { get; set; }
|
||||||
|
|
||||||
|
public UserGroupItem[]? UserGroupItems { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class UserGroupItem
|
||||||
|
{
|
||||||
|
public string? GroupId { get; set; }
|
||||||
|
|
||||||
|
public string? GroupName { get; set; }
|
||||||
|
|
||||||
|
public string? GroupRole { get; set; }
|
||||||
|
}
|
||||||
@@ -54,7 +54,7 @@ public class SimApiBaseResponse(int code = 200, string message = "成功")
|
|||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
public class SimApiBasePageResponse<T>() : SimApiBaseResponse
|
public class SimApiBasePageResponse<T>() : SimApiBaseResponse
|
||||||
{
|
{
|
||||||
public T List { get; set; }
|
public T? List { get; set; }
|
||||||
public int Page { get; set; } = 1;
|
public int Page { get; set; } = 1;
|
||||||
public int Count { get; set; } = 20;
|
public int Count { get; set; } = 20;
|
||||||
public int Total { get; set; }
|
public int Total { get; set; }
|
||||||
@@ -74,7 +74,7 @@ public class SimApiBasePageResponse<T>() : SimApiBaseResponse
|
|||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
public class SimApiBaseResponse<T>() : SimApiBaseResponse
|
public class SimApiBaseResponse<T>() : SimApiBaseResponse
|
||||||
{
|
{
|
||||||
public T Data { get; set; }
|
public T? Data { get; set; }
|
||||||
|
|
||||||
public SimApiBaseResponse(T data) : this()
|
public SimApiBaseResponse(T data) : this()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -5,4 +5,10 @@ namespace SimApi.Communications;
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// 登录信息中间件
|
/// 登录信息中间件
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public record SimApiLoginItem(string Id, string[] Type,Dictionary<string,string>? Meta = null);
|
public class SimApiLoginItem
|
||||||
|
{
|
||||||
|
public string? Id { get; set; }
|
||||||
|
public string[] Type { get; set; } = new[] { "user" };
|
||||||
|
public Dictionary<string, string>? Meta { get; set; } = null;
|
||||||
|
public object? Extra { get; set; } = null;
|
||||||
|
};
|
||||||
@@ -11,17 +11,17 @@ public class SimApiDocGroupOption
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// 文档标识
|
/// 文档标识
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string Id { get; set; }
|
public string Id { get; set; } = null!;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 文档名称
|
/// 文档名称
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string Name { get; set; }
|
public string Name { get; set; } = null!;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 文档描述
|
/// 文档描述
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string Description { get; set; }
|
public string Description { get; set; } = null!;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -33,11 +33,11 @@ public class SimApiAuthOption
|
|||||||
|
|
||||||
public string Description { get; set; } = "认证服务器颁发的AccessToken";
|
public string Description { get; set; } = "认证服务器颁发的AccessToken";
|
||||||
|
|
||||||
public string AuthorizationUrl { get; set; }
|
public string AuthorizationUrl { get; set; } = null!;
|
||||||
|
|
||||||
public string TokenUrl { get; set; }
|
public string TokenUrl { get; set; } = null!;
|
||||||
|
|
||||||
public Dictionary<string, string> Scopes { get; set; }
|
public Dictionary<string, string> Scopes { get; set; } = null!;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using SimApi.CoceSdk;
|
||||||
|
|
||||||
namespace SimApi.Configurations;
|
namespace SimApi.Configurations;
|
||||||
|
|
||||||
@@ -14,13 +15,21 @@ public class SimApiOptions
|
|||||||
/// 启用SimApiAuth,一个简单的基于Header Token的认证方式。
|
/// 启用SimApiAuth,一个简单的基于Header Token的认证方式。
|
||||||
/// default: false
|
/// default: false
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSimApiAuth { get; set; } = false;
|
public bool EnableSimApiAuth { get; set; }
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否使用CoceSdk
|
||||||
|
/// </summary>
|
||||||
|
public bool EnableCoceSdk { get; set; }
|
||||||
|
|
||||||
|
public CoceAppSdkOption CoceSdkOptions { get; set; } = new();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启用在线文档,启用后 访问 /swagger 可以查看对应的api文档。
|
/// 启用在线文档,启用后 访问 /swagger 可以查看对应的api文档。
|
||||||
/// default: false
|
/// default: false
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSimApiDoc { get; set; } = false;
|
public bool EnableSimApiDoc { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启用异常拦截,启用后,所有的异常将被通过json反馈。
|
/// 启用异常拦截,启用后,所有的异常将被通过json反馈。
|
||||||
@@ -32,7 +41,7 @@ public class SimApiOptions
|
|||||||
/// 开启S3兼容的存储系统。
|
/// 开启S3兼容的存储系统。
|
||||||
/// default: false
|
/// default: false
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSimApiStorage { get; set; } = false;
|
public bool EnableSimApiStorage { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 开启ForwardHeaders,开启后可以透传负载均衡的Headers
|
/// 开启ForwardHeaders,开启后可以透传负载均衡的Headers
|
||||||
@@ -50,12 +59,12 @@ public class SimApiOptions
|
|||||||
/// 启用格式化的 Console Logger
|
/// 启用格式化的 Console Logger
|
||||||
/// default: false
|
/// default: false
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableLogger { get; set; } = false;
|
public bool EnableLogger { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 是否启用Synapse
|
/// 是否启用Synapse
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSynapse { get; set; } = false;
|
public bool EnableSynapse { get; set; }
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -70,22 +79,22 @@ public class SimApiOptions
|
|||||||
|
|
||||||
public SimApiSynapseOptions SimApiSynapseOptions { get; set; } = new();
|
public SimApiSynapseOptions SimApiSynapseOptions { get; set; } = new();
|
||||||
|
|
||||||
public void ConfigureSimApiSynapse(Action<SimApiSynapseOptions> options = null)
|
public void ConfigureSimApiSynapse(Action<SimApiSynapseOptions>? options = null)
|
||||||
{
|
{
|
||||||
options?.Invoke(SimApiSynapseOptions);
|
options?.Invoke(SimApiSynapseOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void ConfigureSimApiSynapse(SimApiSynapseOptions options)
|
public void ConfigureCoceSdk(Action<CoceAppSdkOption>? options = null)
|
||||||
{
|
{
|
||||||
SimApiSynapseOptions = options;
|
options?.Invoke(CoceSdkOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void ConfigureSimApiDoc(Action<SimApiDocOptions> options = null)
|
public void ConfigureSimApiDoc(Action<SimApiDocOptions>? options = null)
|
||||||
{
|
{
|
||||||
options?.Invoke(SimApiDocOptions);
|
options?.Invoke(SimApiDocOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void ConfigureSimApiStorage(Action<SimApiStorageOptions> options = null)
|
public void ConfigureSimApiStorage(Action<SimApiStorageOptions>? options = null)
|
||||||
{
|
{
|
||||||
options?.Invoke(SimApiStorageOptions);
|
options?.Invoke(SimApiStorageOptions);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,12 @@ public class SimApiSynapseOptions
|
|||||||
public string? AppId { get; set; }
|
public string? AppId { get; set; }
|
||||||
public int RpcTimeout { get; set; } = 3;
|
public int RpcTimeout { get; set; } = 3;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Event是否使用负载均衡
|
||||||
|
/// 也就是订阅$queue主题,消息会分发给不同的AppId
|
||||||
|
/// 如果false,多个AppId都可以同时收到消息
|
||||||
|
/// </summary>
|
||||||
|
public bool EventLoadBalancing { get; set; } = false;
|
||||||
public bool EnableConfigStore { get; set; } = true;
|
public bool EnableConfigStore { get; set; } = true;
|
||||||
public bool DisableEventClient { get; set; } = false;
|
public bool DisableEventClient { get; set; } = false;
|
||||||
public bool DisableRpcClient { get; set; } = false;
|
public bool DisableRpcClient { get; set; } = false;
|
||||||
|
|||||||
@@ -26,8 +26,7 @@ public class SimApiBaseController : Controller
|
|||||||
/// <param name="context"></param>
|
/// <param name="context"></param>
|
||||||
public override void OnActionExecuting(ActionExecutingContext context)
|
public override void OnActionExecuting(ActionExecutingContext context)
|
||||||
{
|
{
|
||||||
if (!context.ModelState.IsValid)
|
if (context.ModelState.IsValid) return;
|
||||||
{
|
|
||||||
foreach (var item in context.ModelState.Values.Where(item =>
|
foreach (var item in context.ModelState.Values.Where(item =>
|
||||||
item.ValidationState == ModelValidationState.Invalid))
|
item.ValidationState == ModelValidationState.Invalid))
|
||||||
{
|
{
|
||||||
@@ -35,7 +34,6 @@ public class SimApiBaseController : Controller
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using SimApi.Attributes;
|
||||||
|
using SimApi.CoceSdk;
|
||||||
|
using SimApi.Communications;
|
||||||
|
using SimApi.Helpers;
|
||||||
|
|
||||||
|
namespace SimApi.Controllers;
|
||||||
|
|
||||||
|
public class SimApiCoceController(CoceApp coce,SimApiAuth auth) : SimApiBaseController
|
||||||
|
{
|
||||||
|
[HttpPost]
|
||||||
|
public SimApiBaseResponse<ConfigResponse> GetConfig()
|
||||||
|
{
|
||||||
|
return new SimApiBaseResponse<ConfigResponse>(coce.GetConfig());
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost]
|
||||||
|
public SimApiBaseResponse<string> Login([FromBody] SimApiOneFieldRequest<string> request)
|
||||||
|
{
|
||||||
|
var data = coce.GetLevelToken(request.Data!);
|
||||||
|
ErrorWhenNull(data, 400);
|
||||||
|
coce.SaveToken(data!.UserId, data.Token);
|
||||||
|
var userinfo = coce.GetUserInfo(data!.Token);
|
||||||
|
var meta = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
{ "name", userinfo!.Name },
|
||||||
|
{ "image", userinfo.Image }
|
||||||
|
};
|
||||||
|
var groups = coce.GetUserGroups(data.Token!)!;
|
||||||
|
var loginItem = new SimApiLoginItem
|
||||||
|
{
|
||||||
|
Id = data.UserId,
|
||||||
|
Meta = meta,
|
||||||
|
Extra = groups
|
||||||
|
};
|
||||||
|
return new SimApiBaseResponse<string>(auth.Login(loginItem));
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost, SimApiAuth]
|
||||||
|
public SimApiBaseResponse<GroupInfo[]> ListGroups()
|
||||||
|
{
|
||||||
|
var levelToken = coce.GetToken(LoginInfo.Id!);
|
||||||
|
var groups = coce.GetUserGroups(levelToken!)!;
|
||||||
|
return new SimApiBaseResponse<GroupInfo[]>(groups.ToArray());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,8 +4,6 @@ using SimApi.Communications;
|
|||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi.Controllers;
|
namespace SimApi.Controllers;
|
||||||
|
|
||||||
[ApiExplorerSettings(GroupName = "api")]
|
|
||||||
public class SimApiCommonController(SimApiAuth auth) : SimApiBaseController
|
public class SimApiCommonController(SimApiAuth auth) : SimApiBaseController
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -24,10 +22,10 @@ public class SimApiCommonController(SimApiAuth auth) : SimApiBaseController
|
|||||||
/// 检测用户登陆的控制器
|
/// 检测用户登陆的控制器
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpPost("/auth/check"), SimApiDoc("认证", "检测登陆")]
|
[HttpPost, SimApiDoc("认证", "检测登陆")]
|
||||||
public SimApiBaseResponse<string> CheckLogin()
|
public SimApiBaseResponse<string> CheckLogin()
|
||||||
{
|
{
|
||||||
ErrorWhenNull(LoginInfo, 401);
|
ErrorWhenNull(LoginInfo, 401,"未登录");
|
||||||
return new SimApiBaseResponse<string>
|
return new SimApiBaseResponse<string>
|
||||||
{
|
{
|
||||||
Data = LoginInfo.Id
|
Data = LoginInfo.Id
|
||||||
@@ -38,7 +36,7 @@ public class SimApiCommonController(SimApiAuth auth) : SimApiBaseController
|
|||||||
/// 退出登陆
|
/// 退出登陆
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpPost("/auth/logout"), SimApiDoc("认证", "退出登陆")]
|
[HttpPost, SimApiDoc("认证", "退出登陆")]
|
||||||
public SimApiBaseResponse Logout()
|
public SimApiBaseResponse Logout()
|
||||||
{
|
{
|
||||||
string? token = null;
|
string? token = null;
|
||||||
@@ -52,7 +50,7 @@ public class SimApiCommonController(SimApiAuth auth) : SimApiBaseController
|
|||||||
return new SimApiBaseResponse();
|
return new SimApiBaseResponse();
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("/logined"),SimApiAuth]
|
[HttpPost,SimApiAuth]
|
||||||
public SimApiBaseResponse<SimApiLoginItem> UserInfo()
|
public SimApiBaseResponse<SimApiLoginItem> UserInfo()
|
||||||
{
|
{
|
||||||
return new SimApiBaseResponse<SimApiLoginItem>(LoginInfo);
|
return new SimApiBaseResponse<SimApiLoginItem>(LoginInfo);
|
||||||
|
|||||||
+6
-38
@@ -13,48 +13,16 @@ namespace SimApi.Helpers;
|
|||||||
public class SimApiAuth(IDistributedCache cache)
|
public class SimApiAuth(IDistributedCache cache)
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 产生一个Token记录并返回Token
|
/// 登录信息
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="id"></param>
|
/// <param name="loginItem"></param>
|
||||||
/// <param name="type"></param>
|
|
||||||
/// <param name="meta"></param>
|
|
||||||
/// <param name="token"></param>
|
/// <param name="token"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public string Login(string id, Dictionary<string, string>? meta = null, string type = "user", string? token = null)
|
public string Login(SimApiLoginItem loginItem, string? token = null)
|
||||||
{
|
{
|
||||||
return Login(id, meta, new[] { type }, token);
|
token ??= Guid.NewGuid().ToString();
|
||||||
}
|
cache.SetString(token, JsonSerializer.Serialize(loginItem));
|
||||||
|
return token;
|
||||||
/// <summary>
|
|
||||||
/// 产生一个Token并记录用户ID角色[多角色]
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="id"></param>
|
|
||||||
/// <param name="type"></param>
|
|
||||||
/// <param name="meta"></param>
|
|
||||||
/// <param name="uuid"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
// ReSharper disable once MemberCanBePrivate.Global
|
|
||||||
public string Login(string id, Dictionary<string, string>? meta, string[] type, string? uuid = null)
|
|
||||||
{
|
|
||||||
uuid ??= Guid.NewGuid().ToString();
|
|
||||||
var loginItem = new SimApiLoginItem(id, type, meta);
|
|
||||||
cache.SetString(uuid, JsonSerializer.Serialize(loginItem));
|
|
||||||
return uuid;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 设置登录的Meta信息
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="token"></param>
|
|
||||||
/// <param name="meta"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
public bool SetMeta(string token, Dictionary<string, string> meta)
|
|
||||||
{
|
|
||||||
var login = GetLogin(token);
|
|
||||||
if (login == null) { return false; }
|
|
||||||
var newLogin = new SimApiLoginItem(login.Id, login.Type, login.Meta);
|
|
||||||
cache.SetString(token,JsonSerializer.Serialize(newLogin));
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -112,7 +112,7 @@ public class SimApiStorage
|
|||||||
/// <param name="path"></param>
|
/// <param name="path"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
/// <exception cref="Exception"></exception>
|
/// <exception cref="Exception"></exception>
|
||||||
public string FullUrl(string path)
|
public string? FullUrl(string? path)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(path)) return path;
|
if (string.IsNullOrEmpty(path)) return path;
|
||||||
if(path.StartsWith("http://") || path.StartsWith("https://")) return path;
|
if(path.StartsWith("http://") || path.StartsWith("https://")) return path;
|
||||||
|
|||||||
+10
-3
@@ -1,13 +1,11 @@
|
|||||||
using System;
|
using System;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using SimApi.Helpers;
|
|
||||||
|
|
||||||
namespace SimApi.Logger;
|
namespace SimApi.Logger;
|
||||||
|
|
||||||
public class SimApiLogger(string name) : ILogger
|
public class SimApiLogger(string name) : ILogger
|
||||||
{
|
{
|
||||||
public IDisposable BeginScope<TState>(TState state) => default!;
|
public IDisposable BeginScope<TState>(TState state) where TState : notnull => default!;
|
||||||
|
|
||||||
public bool IsEnabled(LogLevel logLevel) => true;
|
public bool IsEnabled(LogLevel logLevel) => true;
|
||||||
|
|
||||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
|
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
|
||||||
@@ -33,3 +31,12 @@ public class SimApiLogger(string name) : ILogger
|
|||||||
Console.ResetColor();
|
Console.ResetColor();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class EmptyDisposable : IDisposable
|
||||||
|
{
|
||||||
|
public static EmptyDisposable Instance { get; } = new EmptyDisposable();
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-3
@@ -21,15 +21,14 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Folder Include="Helpers\"/>
|
<Folder Include="Helpers\"/>
|
||||||
<Folder Include="Communications\"/>
|
<Folder Include="Communications\"/>
|
||||||
<Folder Include="Controllers\"/>
|
|
||||||
<Folder Include="Middlewares\"/>
|
<Folder Include="Middlewares\"/>
|
||||||
<Folder Include="Exceptions\"/>
|
<Folder Include="Exceptions\"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Minio" Version="6.0.3" />
|
<PackageReference Include="Minio" Version="6.0.3" />
|
||||||
<PackageReference Include="MQTTnet" Version="4.3.6.1152" />
|
<PackageReference Include="MQTTnet" Version="4.3.6.1152" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.6.2" />
|
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.7.1" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.6.2" />
|
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.7.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ProjectExtensions>
|
<ProjectExtensions>
|
||||||
<MonoDevelop>
|
<MonoDevelop>
|
||||||
|
|||||||
+38
-7
@@ -7,6 +7,7 @@ using SimApi.Middlewares;
|
|||||||
using Microsoft.AspNetCore.HttpOverrides;
|
using Microsoft.AspNetCore.HttpOverrides;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using SimApi.CoceSdk;
|
||||||
using SimApi.Configurations;
|
using SimApi.Configurations;
|
||||||
using SimApi.Logger;
|
using SimApi.Logger;
|
||||||
|
|
||||||
@@ -19,7 +20,7 @@ public static class SimApiExtensions
|
|||||||
{
|
{
|
||||||
//**********快捷添加**************
|
//**********快捷添加**************
|
||||||
public static IServiceCollection AddSimApi(this IServiceCollection builder,
|
public static IServiceCollection AddSimApi(this IServiceCollection builder,
|
||||||
Action<SimApiOptions> options = null)
|
Action<SimApiOptions>? options = null)
|
||||||
{
|
{
|
||||||
var simApiOptions = new SimApiOptions();
|
var simApiOptions = new SimApiOptions();
|
||||||
options?.Invoke(simApiOptions);
|
options?.Invoke(simApiOptions);
|
||||||
@@ -38,6 +39,11 @@ public static class SimApiExtensions
|
|||||||
builder.AddSingleton<SimApiAuth>();
|
builder.AddSingleton<SimApiAuth>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (simApiOptions.EnableCoceSdk)
|
||||||
|
{
|
||||||
|
builder.AddSingleton<CoceApp>();
|
||||||
|
}
|
||||||
|
|
||||||
if (simApiOptions.EnableCors)
|
if (simApiOptions.EnableCors)
|
||||||
{
|
{
|
||||||
builder.AddCors(cors => cors.AddPolicy("any",
|
builder.AddCors(cors => cors.AddPolicy("any",
|
||||||
@@ -147,7 +153,7 @@ public static class SimApiExtensions
|
|||||||
Id = "oauth2"
|
Id = "oauth2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
new[] { "SimApiAuth" }
|
["SimApiAuth"]
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -205,6 +211,13 @@ public static class SimApiExtensions
|
|||||||
builder.Services.GetService<SimApiStorage>();
|
builder.Services.GetService<SimApiStorage>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (options.EnableCoceSdk)
|
||||||
|
{
|
||||||
|
logger.LogInformation("开始配置CoceAppSdk...\nApi入口: {ApiUrl}\nAuth入口:{AuthUrl}n\nAppId: {AppId}",
|
||||||
|
options.CoceSdkOptions.ApiEndpoint, options.CoceSdkOptions.AuthEndpoint,
|
||||||
|
options.CoceSdkOptions.AppId);
|
||||||
|
}
|
||||||
|
|
||||||
if (options.EnableLowerUrl)
|
if (options.EnableLowerUrl)
|
||||||
{
|
{
|
||||||
logger.LogInformation("开始配置使用URL小写...");
|
logger.LogInformation("开始配置使用URL小写...");
|
||||||
@@ -224,11 +237,11 @@ public static class SimApiExtensions
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="builder"></param>
|
/// <param name="builder"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static IApplicationBuilder UseSimApi(this IApplicationBuilder builder)
|
public static WebApplication UseSimApi(this WebApplication builder)
|
||||||
{
|
{
|
||||||
var options = builder.ApplicationServices.GetRequiredService<SimApiOptions>();
|
var options = builder.Services.GetRequiredService<SimApiOptions>();
|
||||||
|
|
||||||
var logger = builder.ApplicationServices.GetRequiredService<ILogger<SimApiOptions>>();
|
var logger = builder.Services.GetRequiredService<ILogger<SimApiOptions>>();
|
||||||
|
|
||||||
logger.LogInformation("当前时区: {LocalId}", TimeZoneInfo.Local.Id);
|
logger.LogInformation("当前时区: {LocalId}", TimeZoneInfo.Local.Id);
|
||||||
if (options.EnableForwardHeaders)
|
if (options.EnableForwardHeaders)
|
||||||
@@ -247,6 +260,24 @@ public static class SimApiExtensions
|
|||||||
{
|
{
|
||||||
logger.LogInformation("开始配置SimApiAuth...");
|
logger.LogInformation("开始配置SimApiAuth...");
|
||||||
builder.UseMiddleware<SimApiAuthMiddleware>();
|
builder.UseMiddleware<SimApiAuthMiddleware>();
|
||||||
|
builder.MapControllerRoute(name: "GetUserInfo", pattern: "/user/info",
|
||||||
|
defaults: new { controller = "SimApiCommon", action = "UserInfo" });
|
||||||
|
builder.MapControllerRoute(name: "CheckLogin", pattern: "/auth/check",
|
||||||
|
defaults: new { controller = "SimApiCommon", action = "CheckLogin" });
|
||||||
|
builder.MapControllerRoute(name: "Logout", pattern: "/auth/logout",
|
||||||
|
defaults: new { controller = "SimApiCommon", action = "Logout" });
|
||||||
|
if (options.EnableCoceSdk)
|
||||||
|
{
|
||||||
|
logger.LogInformation("开始配置CoceAppSdk...\nApi入口: {ApiUrl}\nAuth入口:{AuthUrl}n\nAppId: {AppId}",
|
||||||
|
options.CoceSdkOptions.ApiEndpoint, options.CoceSdkOptions.AuthEndpoint,
|
||||||
|
options.CoceSdkOptions.AppId);
|
||||||
|
builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/auth/login",
|
||||||
|
defaults: new { controller = "SimApiCoce", action = "Login" });
|
||||||
|
builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/user/groups",
|
||||||
|
defaults: new { controller = "SimApiCoce", action = "ListGroups" });
|
||||||
|
builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/auth/config",
|
||||||
|
defaults: new { controller = "SimApiCoce", action = "GetConfig" });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.EnableSimApiDoc)
|
if (options.EnableSimApiDoc)
|
||||||
@@ -277,7 +308,7 @@ public static class SimApiExtensions
|
|||||||
if (options.EnableSimApiStorage)
|
if (options.EnableSimApiStorage)
|
||||||
{
|
{
|
||||||
logger.LogInformation("开始配置SimApiStorage...");
|
logger.LogInformation("开始配置SimApiStorage...");
|
||||||
builder.ApplicationServices.GetService<SimApiStorage>();
|
builder.Services.GetService<SimApiStorage>();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.EnableLowerUrl)
|
if (options.EnableLowerUrl)
|
||||||
@@ -287,7 +318,7 @@ public static class SimApiExtensions
|
|||||||
|
|
||||||
if (options.EnableSynapse)
|
if (options.EnableSynapse)
|
||||||
{
|
{
|
||||||
var synapse = builder.ApplicationServices.GetRequiredService<Synapse>();
|
var synapse = builder.Services.GetRequiredService<Synapse>();
|
||||||
synapse.Init();
|
synapse.Init();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+14
-8
@@ -13,6 +13,8 @@ public partial class Synapse
|
|||||||
public event EventHandler<ConfigStoreItem>? OnConfigChanged;
|
public event EventHandler<ConfigStoreItem>? OnConfigChanged;
|
||||||
private Dictionary<string, string> CurrentConfig { get; } = new();
|
private Dictionary<string, string> CurrentConfig { get; } = new();
|
||||||
|
|
||||||
|
private string ConfigStoreTopicPrefix => $"{Options.SysName}/synapse-config-store/";
|
||||||
|
|
||||||
private bool FireSetConfig(string key, string value)
|
private bool FireSetConfig(string key, string value)
|
||||||
{
|
{
|
||||||
if (key.Contains('#') || key.Contains('+')) return false;
|
if (key.Contains('#') || key.Contains('+')) return false;
|
||||||
@@ -35,22 +37,26 @@ public partial class Synapse
|
|||||||
|
|
||||||
private void RunConfigStoreServer()
|
private void RunConfigStoreServer()
|
||||||
{
|
{
|
||||||
var csTopicPrefix = $"{Options.SysName}/synapse-config-store/";
|
|
||||||
var eventSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
|
|
||||||
.WithTopicFilter(o =>
|
|
||||||
o.WithTopic($"{csTopicPrefix}#").WithRetainHandling(MqttRetainHandling.SendAtSubscribe))
|
|
||||||
.Build();
|
|
||||||
Client!.ApplicationMessageReceivedAsync += e =>
|
Client!.ApplicationMessageReceivedAsync += e =>
|
||||||
{
|
{
|
||||||
if (!e.ApplicationMessage.Topic.StartsWith(csTopicPrefix)) return Task.CompletedTask;
|
if (!e.ApplicationMessage.Topic.StartsWith(ConfigStoreTopicPrefix)) return Task.CompletedTask;
|
||||||
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
||||||
var eventName = e.ApplicationMessage.Topic.Replace(csTopicPrefix, string.Empty);
|
var eventName = e.ApplicationMessage.Topic.Replace(ConfigStoreTopicPrefix, string.Empty);
|
||||||
CurrentConfig[eventName] = reqBody;
|
CurrentConfig[eventName] = reqBody;
|
||||||
OnConfigChanged?.Invoke(this, new ConfigStoreItem(eventName, reqBody));
|
OnConfigChanged?.Invoke(this, new ConfigStoreItem(eventName, reqBody));
|
||||||
logger.LogDebug("Synapse Config Changed: {Config} => {Data}", eventName, reqBody);
|
logger.LogDebug("Synapse Config Changed: {Config} => {Data}", eventName, reqBody);
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
};
|
};
|
||||||
Client.SubscribeAsync(eventSubOpts).Wait();
|
SubConfigStoreServerTopic();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SubConfigStoreServerTopic()
|
||||||
|
{
|
||||||
|
var csSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
|
||||||
|
.WithTopicFilter(o =>
|
||||||
|
o.WithTopic($"{ConfigStoreTopicPrefix}#").WithRetainHandling(MqttRetainHandling.SendAtSubscribe))
|
||||||
|
.Build();
|
||||||
|
Client!.SubscribeAsync(csSubOpts).Wait();
|
||||||
}
|
}
|
||||||
|
|
||||||
public record ConfigStoreItem(string Key, string Value);
|
public record ConfigStoreItem(string Key, string Value);
|
||||||
|
|||||||
+26
-14
@@ -1,4 +1,5 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
@@ -12,20 +13,21 @@ namespace SimApi;
|
|||||||
|
|
||||||
public partial class Synapse
|
public partial class Synapse
|
||||||
{
|
{
|
||||||
|
private string EventServerTopicPrefix => $"{Options.SysName}/event/";
|
||||||
|
|
||||||
private void RunEventServer()
|
private void RunEventServer()
|
||||||
{
|
{
|
||||||
var esTopicPrefix = $"{Options.SysName}/event/";
|
Client!.ApplicationMessageReceivedAsync += async e =>
|
||||||
Client!.ApplicationMessageReceivedAsync += e =>
|
|
||||||
{
|
{
|
||||||
if (!e.ApplicationMessage.Topic.StartsWith(esTopicPrefix)) return Task.CompletedTask;
|
if (!e.ApplicationMessage.Topic.StartsWith(EventServerTopicPrefix)) return;
|
||||||
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
||||||
var eventName = e.ApplicationMessage.Topic.Replace(esTopicPrefix, string.Empty);
|
var eventName = e.ApplicationMessage.Topic.Replace(EventServerTopicPrefix, string.Empty);
|
||||||
logger.LogDebug("Synapse Event Receive: {EventName}\n{Body}", eventName, reqBody);
|
logger.LogDebug("Synapse Event Receive: {EventName}\n{Body}", eventName, reqBody);
|
||||||
var methods = EventRegistry
|
var methods = EventRegistry
|
||||||
.Where(x => Regex.IsMatch(eventName,
|
.Where(x => Regex.IsMatch(eventName,
|
||||||
"^" + Regex.Escape(x.Key!).Replace("\\+", "[^/]+").Replace("\\#", ".*") + "$"))
|
"^" + Regex.Escape(x.Key!).Replace("\\+", "[^/]+").Replace("\\#", ".*") + "$"))
|
||||||
.ToArray();
|
.ToArray();
|
||||||
foreach (var method in methods)
|
var tasks = methods.Select(method => Task.Run(() =>
|
||||||
{
|
{
|
||||||
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(method.Class!);
|
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(method.Class!);
|
||||||
var mt = callClass.GetType().GetMethod(method.Method!);
|
var mt = callClass.GetType().GetMethod(method.Method!);
|
||||||
@@ -33,30 +35,40 @@ public partial class Synapse
|
|||||||
{
|
{
|
||||||
if (mt!.GetParameters().Length == 2)
|
if (mt!.GetParameters().Length == 2)
|
||||||
{
|
{
|
||||||
var pt = mt!.GetParameters()[0].ParameterType;
|
var pt = mt.GetParameters()[1].ParameterType;
|
||||||
mt.Invoke(callClass, pt == typeof(string)
|
mt.Invoke(callClass, pt == typeof(string)
|
||||||
? [eventName, reqBody]
|
? new object?[] { eventName, reqBody }
|
||||||
: [eventName, JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption)]);
|
: new object?[] { eventName, JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) });
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
mt.Invoke(callClass, [eventName]);
|
mt.Invoke(callClass, new object[] { eventName });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
logger.LogError("Synapse Event Processor Error: {Err}", ex.InnerException);
|
logger.LogError("Synapse Event Processor Error: {Err}\n{Stack}", ex.Message, ex.StackTrace);
|
||||||
}
|
}
|
||||||
|
}))
|
||||||
|
.ToList();
|
||||||
|
await Task.WhenAll(tasks);
|
||||||
|
};
|
||||||
|
SubEventServerTopic();
|
||||||
}
|
}
|
||||||
|
|
||||||
return Task.CompletedTask;
|
private void SubEventServerTopic()
|
||||||
};
|
{
|
||||||
foreach (var ev in EventRegistry)
|
foreach (var ev in EventRegistry)
|
||||||
{
|
{
|
||||||
var topic = $"$queue/{esTopicPrefix}{ev.Key}";
|
var topic = $"{EventServerTopicPrefix}{ev.Key}";
|
||||||
|
if (Options.EventLoadBalancing)
|
||||||
|
{
|
||||||
|
topic = "$queue/" + topic;
|
||||||
|
}
|
||||||
|
|
||||||
var evSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
|
var evSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
|
||||||
.WithTopicFilter(o => o.WithTopic(topic)).Build();
|
.WithTopicFilter(o => o.WithTopic(topic)).Build();
|
||||||
Client.SubscribeAsync(evSubOpts).Wait();
|
Client!.SubscribeAsync(evSubOpts).Wait();
|
||||||
logger.LogDebug("Synapse Event Register Event Success: {EventName}\nFull Topic: {Topic}", ev.Key, topic);
|
logger.LogDebug("Synapse Event Register Event Success: {EventName}\nFull Topic: {Topic}", ev.Key, topic);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+12
-6
@@ -14,22 +14,28 @@ public partial class Synapse
|
|||||||
{
|
{
|
||||||
private Dictionary<string, TaskCompletionSource<string>> ResponseCompletionSources { get; } = new();
|
private Dictionary<string, TaskCompletionSource<string>> ResponseCompletionSources { get; } = new();
|
||||||
|
|
||||||
|
private string EventClientTopicPrefix => $"{Options.SysName}/{Options.AppName}/rpc/client/{Options.AppId}/";
|
||||||
|
|
||||||
private void RunRpcClient()
|
private void RunRpcClient()
|
||||||
{
|
{
|
||||||
var rcTopic = $"{Options.SysName}/{Options.AppName}/rpc/client/{Options.AppId}/";
|
|
||||||
var rcSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
|
|
||||||
.WithTopicFilter(o => o.WithTopic($"{rcTopic}+")).Build();
|
|
||||||
Client!.ApplicationMessageReceivedAsync += e =>
|
Client!.ApplicationMessageReceivedAsync += e =>
|
||||||
{
|
{
|
||||||
if (!e.ApplicationMessage.Topic.StartsWith(rcTopic)) return Task.CompletedTask;
|
if (!e.ApplicationMessage.Topic.StartsWith(EventClientTopicPrefix)) return Task.CompletedTask;
|
||||||
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
||||||
var messageId = e.ApplicationMessage.Topic.Replace(rcTopic, string.Empty);
|
var messageId = e.ApplicationMessage.Topic.Replace(EventClientTopicPrefix, string.Empty);
|
||||||
if (!ResponseCompletionSources.TryGetValue(messageId, out var tcs)) return Task.CompletedTask;
|
if (!ResponseCompletionSources.TryGetValue(messageId, out var tcs)) return Task.CompletedTask;
|
||||||
tcs.SetResult(reqBody);
|
tcs.SetResult(reqBody);
|
||||||
ResponseCompletionSources.Remove(messageId);
|
ResponseCompletionSources.Remove(messageId);
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
};
|
};
|
||||||
Client.SubscribeAsync(rcSubOpts).Wait();
|
SubRpcClientTopic();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SubRpcClientTopic()
|
||||||
|
{
|
||||||
|
var rcSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
|
||||||
|
.WithTopicFilter(o => o.WithTopic($"{EventClientTopicPrefix}+")).Build();
|
||||||
|
Client!.SubscribeAsync(rcSubOpts).Wait();
|
||||||
}
|
}
|
||||||
|
|
||||||
private string? FireRpc(string app, string action, object? param)
|
private string? FireRpc(string app, string action, object? param)
|
||||||
|
|||||||
+21
-9
@@ -16,18 +16,15 @@ namespace SimApi;
|
|||||||
|
|
||||||
public partial class Synapse
|
public partial class Synapse
|
||||||
{
|
{
|
||||||
|
private string RpcServerTopicPrefix => $"{Options.SysName}/{Options.AppName}/rpc/server/";
|
||||||
|
|
||||||
private void RunRpcServer()
|
private void RunRpcServer()
|
||||||
{
|
{
|
||||||
var rsTopicPrefix = $"{Options.SysName}/{Options.AppName}/rpc/server/";
|
|
||||||
var rsSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
|
|
||||||
.WithTopicFilter(o =>
|
|
||||||
o.WithTopic($"$queue/{rsTopicPrefix}+").WithRetainHandling(MqttRetainHandling.SendAtSubscribe))
|
|
||||||
.Build();
|
|
||||||
Client!.ApplicationMessageReceivedAsync += e =>
|
Client!.ApplicationMessageReceivedAsync += e =>
|
||||||
{
|
{
|
||||||
if (!e.ApplicationMessage.Topic.StartsWith(rsTopicPrefix)) return Task.CompletedTask;
|
if (!e.ApplicationMessage.Topic.StartsWith(RpcServerTopicPrefix)) return Task.CompletedTask;
|
||||||
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
||||||
var action = e.ApplicationMessage.Topic.Replace(rsTopicPrefix, string.Empty);
|
var action = e.ApplicationMessage.Topic.Replace(RpcServerTopicPrefix, string.Empty);
|
||||||
var appInfo = e.ApplicationMessage.ResponseTopic.Split(",");
|
var appInfo = e.ApplicationMessage.ResponseTopic.Split(",");
|
||||||
logger.LogDebug(
|
logger.LogDebug(
|
||||||
"Synapse RPC Server Receive: ({BasicPropertiesMessageId}) {BasicPropertiesReplyTo} -> {BasicPropertiesType}@{OptionsAppName}\n{S}",
|
"Synapse RPC Server Receive: ({BasicPropertiesMessageId}) {BasicPropertiesReplyTo} -> {BasicPropertiesType}@{OptionsAppName}\n{S}",
|
||||||
@@ -35,7 +32,12 @@ public partial class Synapse
|
|||||||
reqBody);
|
reqBody);
|
||||||
SimApiBaseResponse res;
|
SimApiBaseResponse res;
|
||||||
var method = RpcRegistry.FirstOrDefault(x => x.Key == action);
|
var method = RpcRegistry.FirstOrDefault(x => x.Key == action);
|
||||||
if (method == null) return Task.CompletedTask;
|
if (method == null)
|
||||||
|
{
|
||||||
|
res = new SimApiBaseResponse(404, "method not found");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(method.Class!);
|
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(method.Class!);
|
||||||
var mt = callClass.GetType().GetMethod(method.Method!);
|
var mt = callClass.GetType().GetMethod(method.Method!);
|
||||||
try
|
try
|
||||||
@@ -77,6 +79,7 @@ public partial class Synapse
|
|||||||
logger.LogDebug("Synapse RPC调用失败: {Err}", ex.Message);
|
logger.LogDebug("Synapse RPC调用失败: {Err}", ex.Message);
|
||||||
res = new SimApiBaseResponse(500, ex.Message);
|
res = new SimApiBaseResponse(500, ex.Message);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var returnJson = JsonSerializer.Serialize((object)res, SimApiUtil.JsonOption);
|
var returnJson = JsonSerializer.Serialize((object)res, SimApiUtil.JsonOption);
|
||||||
var reply = $"{Options.SysName}/{appInfo[0]}/rpc/client/{appInfo[1]}/{e.ApplicationMessage.ContentType}";
|
var reply = $"{Options.SysName}/{appInfo[0]}/rpc/client/{appInfo[1]}/{e.ApplicationMessage.ContentType}";
|
||||||
@@ -93,6 +96,15 @@ public partial class Synapse
|
|||||||
|
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
};
|
};
|
||||||
Client.SubscribeAsync(rsSubOpts).Wait();
|
SubRpcServerTopic();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SubRpcServerTopic()
|
||||||
|
{
|
||||||
|
var rsSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
|
||||||
|
.WithTopicFilter(o =>
|
||||||
|
o.WithTopic($"$queue/{RpcServerTopicPrefix}+").WithRetainHandling(MqttRetainHandling.SendAtSubscribe))
|
||||||
|
.Build();
|
||||||
|
Client!.SubscribeAsync(rsSubOpts).Wait();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+6
-1
@@ -165,6 +165,11 @@ public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logge
|
|||||||
Client.ConnectedAsync += _ =>
|
Client.ConnectedAsync += _ =>
|
||||||
{
|
{
|
||||||
logger.LogInformation("Synapse MQTT[{AppName}:{AppId}] 连接成功...", Options.AppName, Options.AppId);
|
logger.LogInformation("Synapse MQTT[{AppName}:{AppId}] 连接成功...", Options.AppName, Options.AppId);
|
||||||
|
//RPC客户端
|
||||||
|
if (!Options.DisableRpcClient) SubRpcClientTopic();
|
||||||
|
if (RpcRegistry.Count > 0) SubRpcServerTopic();
|
||||||
|
if (EventRegistry.Count > 0) SubEventServerTopic();
|
||||||
|
if (Options.EnableConfigStore) SubConfigStoreServerTopic();
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
};
|
};
|
||||||
//重连
|
//重连
|
||||||
@@ -213,7 +218,7 @@ public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logge
|
|||||||
|
|
||||||
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(tmp.Class!);
|
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(tmp.Class!);
|
||||||
var mt = callClass.GetType().GetMethod(tmp.Method);
|
var mt = callClass.GetType().GetMethod(tmp.Method);
|
||||||
if (mt!.GetParameters().Length > 2 || mt.GetParameters().Length<1)
|
if (mt!.GetParameters().Length > 2 || mt.GetParameters().Length < 1)
|
||||||
{
|
{
|
||||||
logger.LogError(
|
logger.LogError(
|
||||||
"Synapse Event Register Error: Only one or two parameter supported. {Key} -> {Method}@{Class}",
|
"Synapse Event Register Error: Only one or two parameter supported. {Key} -> {Method}@{Class}",
|
||||||
|
|||||||
Reference in New Issue
Block a user