Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e27d5e1c77 | ||
|
|
6af68da3eb | ||
|
|
7dc2ac6a86 | ||
|
|
8f6b853b6c | ||
|
|
e876486c00 | ||
|
|
e71226be4a | ||
|
|
bd674dcc31 | ||
|
|
141846d79d | ||
|
|
a4bae0226e |
@@ -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; }
|
||||
}
|
||||
@@ -5,4 +5,10 @@ namespace SimApi.Communications;
|
||||
/// <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;
|
||||
};
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using SimApi.CoceSdk;
|
||||
|
||||
namespace SimApi.Configurations;
|
||||
|
||||
@@ -16,6 +17,14 @@ public class SimApiOptions
|
||||
/// </summary>
|
||||
public bool EnableSimApiAuth { get; set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 是否使用CoceSdk
|
||||
/// </summary>
|
||||
public bool EnableCoceSdk { get; set; }
|
||||
|
||||
public CoceAppSdkOption CoceSdkOptions { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 启用在线文档,启用后 访问 /swagger 可以查看对应的api文档。
|
||||
/// default: false
|
||||
@@ -75,9 +84,9 @@ public class SimApiOptions
|
||||
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)
|
||||
|
||||
@@ -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;
|
||||
|
||||
namespace SimApi.Controllers;
|
||||
|
||||
[ApiExplorerSettings(GroupName = "api")]
|
||||
public class SimApiCommonController(SimApiAuth auth) : SimApiBaseController
|
||||
{
|
||||
/// <summary>
|
||||
@@ -24,10 +22,10 @@ public class SimApiCommonController(SimApiAuth auth) : SimApiBaseController
|
||||
/// 检测用户登陆的控制器
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpPost("/auth/check"), SimApiDoc("认证", "检测登陆")]
|
||||
[HttpPost, SimApiDoc("认证", "检测登陆")]
|
||||
public SimApiBaseResponse<string> CheckLogin()
|
||||
{
|
||||
ErrorWhenNull(LoginInfo, 401);
|
||||
ErrorWhenNull(LoginInfo, 401,"未登录");
|
||||
return new SimApiBaseResponse<string>
|
||||
{
|
||||
Data = LoginInfo.Id
|
||||
@@ -38,7 +36,7 @@ public class SimApiCommonController(SimApiAuth auth) : SimApiBaseController
|
||||
/// 退出登陆
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpPost("/auth/logout"), SimApiDoc("认证", "退出登陆")]
|
||||
[HttpPost, SimApiDoc("认证", "退出登陆")]
|
||||
public SimApiBaseResponse Logout()
|
||||
{
|
||||
string? token = null;
|
||||
@@ -51,8 +49,8 @@ public class SimApiCommonController(SimApiAuth auth) : SimApiBaseController
|
||||
auth.Logout(token!);
|
||||
return new SimApiBaseResponse();
|
||||
}
|
||||
|
||||
[HttpPost("/logined"),SimApiAuth]
|
||||
|
||||
[HttpPost,SimApiAuth]
|
||||
public SimApiBaseResponse<SimApiLoginItem> UserInfo()
|
||||
{
|
||||
return new SimApiBaseResponse<SimApiLoginItem>(LoginInfo);
|
||||
|
||||
+6
-38
@@ -13,48 +13,16 @@ namespace SimApi.Helpers;
|
||||
public class SimApiAuth(IDistributedCache cache)
|
||||
{
|
||||
/// <summary>
|
||||
/// 产生一个Token记录并返回Token
|
||||
/// 登录信息
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="meta"></param>
|
||||
/// <param name="loginItem"></param>
|
||||
/// <param name="token"></param>
|
||||
/// <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);
|
||||
}
|
||||
|
||||
/// <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;
|
||||
token ??= Guid.NewGuid().ToString();
|
||||
cache.SetString(token, JsonSerializer.Serialize(loginItem));
|
||||
return token;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+2
-3
@@ -21,15 +21,14 @@
|
||||
<ItemGroup>
|
||||
<Folder Include="Helpers\"/>
|
||||
<Folder Include="Communications\"/>
|
||||
<Folder Include="Controllers\"/>
|
||||
<Folder Include="Middlewares\"/>
|
||||
<Folder Include="Exceptions\"/>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Minio" Version="6.0.3" />
|
||||
<PackageReference Include="MQTTnet" Version="4.3.6.1152" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.6.2" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.6.2" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.7.1" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.7.1" />
|
||||
</ItemGroup>
|
||||
<ProjectExtensions>
|
||||
<MonoDevelop>
|
||||
|
||||
+51
-3
@@ -1,4 +1,7 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using SimApi.Helpers;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
@@ -7,6 +10,8 @@ using SimApi.Middlewares;
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SimApi.Attributes;
|
||||
using SimApi.CoceSdk;
|
||||
using SimApi.Configurations;
|
||||
using SimApi.Logger;
|
||||
|
||||
@@ -38,6 +43,11 @@ public static class SimApiExtensions
|
||||
builder.AddSingleton<SimApiAuth>();
|
||||
}
|
||||
|
||||
if (simApiOptions.EnableCoceSdk)
|
||||
{
|
||||
builder.AddSingleton<CoceApp>();
|
||||
}
|
||||
|
||||
if (simApiOptions.EnableCors)
|
||||
{
|
||||
builder.AddCors(cors => cors.AddPolicy("any",
|
||||
@@ -47,6 +57,19 @@ public static class SimApiExtensions
|
||||
if (simApiOptions.EnableSynapse)
|
||||
{
|
||||
builder.AddSingleton<Synapse>();
|
||||
//自动依赖注入
|
||||
var stackTrace = new StackTrace();
|
||||
var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1)?.GetMethod();
|
||||
var assembly = callingMethod?.DeclaringType?.Assembly;
|
||||
var types = assembly?.GetTypes() ?? [];
|
||||
foreach (var type in types)
|
||||
{
|
||||
var methodsWithSynapse = type.GetMethods()
|
||||
.Where(m => m.GetCustomAttribute<SynapseRpcAttribute>() != null ||
|
||||
m.GetCustomAttribute<SynapseEventAttribute>() != null);
|
||||
if (!methodsWithSynapse.Any()) continue;
|
||||
builder.AddScoped(type);
|
||||
}
|
||||
}
|
||||
|
||||
// 使用SimApiDoc
|
||||
@@ -147,7 +170,7 @@ public static class SimApiExtensions
|
||||
Id = "oauth2"
|
||||
}
|
||||
},
|
||||
new[] { "SimApiAuth" }
|
||||
["SimApiAuth"]
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -192,12 +215,12 @@ public static class SimApiExtensions
|
||||
|
||||
public static IHost UseSimApi(this IHost builder)
|
||||
{
|
||||
var options = builder.Services.GetRequiredService<SimApiOptions>();
|
||||
var options = builder.Services.GetRequiredService<SimApiOptions>();
|
||||
|
||||
var logger = builder.Services.GetRequiredService<ILogger<SimApiOptions>>();
|
||||
|
||||
logger.LogInformation("当前时区: {LocalId}", TimeZoneInfo.Local.Id);
|
||||
|
||||
|
||||
//请求一下检测存储错误
|
||||
if (options.EnableSimApiStorage)
|
||||
{
|
||||
@@ -205,6 +228,13 @@ public static class SimApiExtensions
|
||||
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)
|
||||
{
|
||||
logger.LogInformation("开始配置使用URL小写...");
|
||||
@@ -247,6 +277,24 @@ public static class SimApiExtensions
|
||||
{
|
||||
logger.LogInformation("开始配置SimApiAuth...");
|
||||
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)
|
||||
|
||||
+25
-23
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
@@ -12,14 +13,13 @@ namespace SimApi;
|
||||
|
||||
public partial class Synapse
|
||||
{
|
||||
|
||||
private string EventServerTopicPrefix => $"{Options.SysName}/event/";
|
||||
|
||||
private void RunEventServer()
|
||||
{
|
||||
Client!.ApplicationMessageReceivedAsync += e =>
|
||||
Client!.ApplicationMessageReceivedAsync += async e =>
|
||||
{
|
||||
if (!e.ApplicationMessage.Topic.StartsWith(EventServerTopicPrefix)) return Task.CompletedTask;
|
||||
if (!e.ApplicationMessage.Topic.StartsWith(EventServerTopicPrefix)) return;
|
||||
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
||||
var eventName = e.ApplicationMessage.Topic.Replace(EventServerTopicPrefix, string.Empty);
|
||||
logger.LogDebug("Synapse Event Receive: {EventName}\n{Body}", eventName, reqBody);
|
||||
@@ -27,32 +27,33 @@ public partial class Synapse
|
||||
.Where(x => Regex.IsMatch(eventName,
|
||||
"^" + Regex.Escape(x.Key!).Replace("\\+", "[^/]+").Replace("\\#", ".*") + "$"))
|
||||
.ToArray();
|
||||
foreach (var method in methods)
|
||||
{
|
||||
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(method.Class!);
|
||||
var mt = callClass.GetType().GetMethod(method.Method!);
|
||||
try
|
||||
var tasks = methods.Select(method => Task.Run(() =>
|
||||
{
|
||||
if (mt!.GetParameters().Length == 2)
|
||||
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(method.Class!);
|
||||
var mt = callClass.GetType().GetMethod(method.Method!);
|
||||
try
|
||||
{
|
||||
var pt = mt.GetParameters()[1].ParameterType;
|
||||
mt.Invoke(callClass, pt == typeof(string)
|
||||
? [eventName, reqBody]
|
||||
: [eventName, JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption)]);
|
||||
if (mt!.GetParameters().Length == 2)
|
||||
{
|
||||
var pt = mt.GetParameters()[1].ParameterType;
|
||||
mt.Invoke(callClass, pt == typeof(string)
|
||||
? new object?[] { eventName, reqBody }
|
||||
: new object?[] { eventName, JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) });
|
||||
}
|
||||
else
|
||||
{
|
||||
mt.Invoke(callClass, new object[] { eventName });
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
mt.Invoke(callClass, [eventName]);
|
||||
logger.LogError("Synapse Event Processor Error: {Err}\n{Stack}", ex.Message, ex.StackTrace);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError("Synapse Event Processor Error: {Err}\n{Stack}", ex.Message,ex.StackTrace);
|
||||
}
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}))
|
||||
.ToList();
|
||||
await Task.WhenAll(tasks);
|
||||
};
|
||||
SubRpcServerTopic();
|
||||
SubEventServerTopic();
|
||||
}
|
||||
|
||||
private void SubEventServerTopic()
|
||||
@@ -64,6 +65,7 @@ public partial class Synapse
|
||||
{
|
||||
topic = "$queue/" + topic;
|
||||
}
|
||||
|
||||
var evSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
|
||||
.WithTopicFilter(o => o.WithTopic(topic)).Build();
|
||||
Client!.SubscribeAsync(evSubOpts).Wait();
|
||||
|
||||
+18
-9
@@ -1,10 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using MQTTnet;
|
||||
using MQTTnet.Packets;
|
||||
using SimApi.Communications;
|
||||
using SimApi.Helpers;
|
||||
|
||||
@@ -38,7 +40,8 @@ public partial class Synapse
|
||||
Client!.SubscribeAsync(rcSubOpts).Wait();
|
||||
}
|
||||
|
||||
private string? FireRpc(string app, string action, object? param)
|
||||
private string? FireRpc(string app, string action, object? param, Dictionary<string, string>? headers = null,
|
||||
int? timeout = null)
|
||||
{
|
||||
string paramJson;
|
||||
if (param is string strParam)
|
||||
@@ -54,23 +57,29 @@ public partial class Synapse
|
||||
var messageId = Guid.NewGuid().ToString();
|
||||
var tcs = new TaskCompletionSource<string>();
|
||||
ResponseCompletionSources.Add(messageId, tcs);
|
||||
var message = new MqttApplicationMessageBuilder()
|
||||
var messageBuilder = new MqttApplicationMessageBuilder()
|
||||
.WithTopic(topic)
|
||||
.WithPayload(paramJson)
|
||||
.WithResponseTopic($"{Options.AppName},{Options.AppId}")
|
||||
.WithContentType(messageId)
|
||||
.WithRetainFlag(false)
|
||||
.Build();
|
||||
.WithResponseTopic($"{Options.AppName},{Options.AppId},{messageId}")
|
||||
.WithContentType("application/json")
|
||||
.WithRetainFlag(false);
|
||||
foreach (var h in headers ?? new Dictionary<string, string>())
|
||||
{
|
||||
messageBuilder.WithUserProperty(h.Key, h.Value);
|
||||
}
|
||||
|
||||
var message = messageBuilder.Build();
|
||||
if (!Client!.IsConnected) return null;
|
||||
Client.PublishAsync(message, CancellationToken.None).Wait();
|
||||
logger.LogDebug(
|
||||
"Synapse RPC Client Request: ({PropsMessageId}) {OptionsAppName} -> {Action}@{App}\n{ParamJson}", messageId,
|
||||
Options.AppName, action, app, paramJson);
|
||||
"Synapse RPC Client Request: ({PropsMessageId}) {OptionsAppName} -> {Action}@{App}\n{ParamJson}\nHeaders: {Headers}",
|
||||
messageId, Options.AppName, action, app, paramJson, JsonSerializer.Serialize(headers));
|
||||
|
||||
string response;
|
||||
try
|
||||
{
|
||||
if (tcs.Task.Wait(Options.RpcTimeout * 1000))
|
||||
timeout ??= Options.RpcTimeout;
|
||||
if (tcs.Task.Wait(timeout.Value * 1000))
|
||||
{
|
||||
response = tcs.Task.Result;
|
||||
logger.LogDebug(
|
||||
|
||||
+54
-38
@@ -28,55 +28,71 @@ public partial class Synapse
|
||||
var appInfo = e.ApplicationMessage.ResponseTopic.Split(",");
|
||||
logger.LogDebug(
|
||||
"Synapse RPC Server Receive: ({BasicPropertiesMessageId}) {BasicPropertiesReplyTo} -> {BasicPropertiesType}@{OptionsAppName}\n{S}",
|
||||
e.ApplicationMessage.ContentType, appInfo[0], action, Options.AppName,
|
||||
reqBody);
|
||||
appInfo[2], appInfo[0], action, Options.AppName, reqBody);
|
||||
SimApiBaseResponse res;
|
||||
var method = RpcRegistry.FirstOrDefault(x => x.Key == action);
|
||||
if (method == null) return Task.CompletedTask;
|
||||
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(method.Class!);
|
||||
var mt = callClass.GetType().GetMethod(method.Method!);
|
||||
try
|
||||
if (method == null)
|
||||
{
|
||||
var methodParams = mt!.GetParameters();
|
||||
object? ret;
|
||||
if (methodParams.Length == 0)
|
||||
{
|
||||
ret = mt.Invoke(callClass, []);
|
||||
}
|
||||
else
|
||||
{
|
||||
var pt = mt.GetParameters()[0].ParameterType;
|
||||
var param = pt == typeof(string)
|
||||
? [reqBody]
|
||||
: new[] { JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) };
|
||||
ret = mt.Invoke(callClass, param);
|
||||
}
|
||||
|
||||
res = new SimApiBaseResponse<object?>
|
||||
{
|
||||
Data = ret
|
||||
};
|
||||
res = new SimApiBaseResponse(404, "method not found");
|
||||
}
|
||||
catch (TargetInvocationException ex)
|
||||
else
|
||||
{
|
||||
if (ex.InnerException is SimApiException ie)
|
||||
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(method.Class!);
|
||||
var mt = callClass.GetType().GetMethod(method.Method!);
|
||||
try
|
||||
{
|
||||
logger.LogDebug("Synapse RPC调用错误: {Err}", ie.Message);
|
||||
res = new SimApiBaseResponse(ie.Code, ie.Message);
|
||||
var methodParams = mt!.GetParameters();
|
||||
object? ret;
|
||||
switch (methodParams.Length)
|
||||
{
|
||||
case 1:
|
||||
var pt = mt.GetParameters()[0].ParameterType;
|
||||
var param = pt == typeof(string)
|
||||
? [reqBody]
|
||||
: new[] { JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) };
|
||||
ret = mt.Invoke(callClass, param);
|
||||
break;
|
||||
case 2:
|
||||
var headerData =
|
||||
e.ApplicationMessage.UserProperties.ToDictionary(x => x.Name, x => x.Value);
|
||||
var pt2 = mt.GetParameters()[0].ParameterType;
|
||||
var param2 = pt2 == typeof(string)
|
||||
? [reqBody]
|
||||
: new[] { JsonSerializer.Deserialize(reqBody, pt2, SimApiUtil.JsonOption), headerData };
|
||||
ret = mt.Invoke(callClass, param2);
|
||||
break;
|
||||
default:
|
||||
ret = mt.Invoke(callClass, []);
|
||||
break;
|
||||
}
|
||||
|
||||
res = new SimApiBaseResponse<object?>
|
||||
{
|
||||
Data = ret
|
||||
};
|
||||
}
|
||||
else
|
||||
catch (TargetInvocationException ex)
|
||||
{
|
||||
if (ex.InnerException is SimApiException ie)
|
||||
{
|
||||
logger.LogDebug("Synapse RPC调用错误: {Err}", ie.Message);
|
||||
res = new SimApiBaseResponse(ie.Code, ie.Message);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogError("Synapse RPC 方法异常: {Err}\n{Stack}", ex.Message, ex.StackTrace);
|
||||
res = new SimApiBaseResponse(500, ex.Message);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogDebug("Synapse RPC调用失败: {Err}", ex.Message);
|
||||
res = new SimApiBaseResponse(500, ex.Message);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogDebug("Synapse RPC调用失败: {Err}", ex.Message);
|
||||
res = new SimApiBaseResponse(500, ex.Message);
|
||||
}
|
||||
|
||||
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]}/{appInfo[2]}";
|
||||
var message = new MqttApplicationMessageBuilder()
|
||||
.WithTopic(reply)
|
||||
.WithPayload(returnJson)
|
||||
@@ -86,14 +102,14 @@ public partial class Synapse
|
||||
Client.PublishAsync(message, CancellationToken.None).Wait();
|
||||
logger.LogDebug(
|
||||
"Synapse Rpc Server Return: ({BasicPropertiesMessageId}) {BasicPropertiesType}@{OptionsAppName} -> {BasicPropertiesReplyTo}\n{ReturnJson}",
|
||||
e.ApplicationMessage.ContentType, action, Options.AppName, appInfo[0], returnJson);
|
||||
appInfo[2], action, Options.AppName, appInfo[0], returnJson);
|
||||
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
SubRpcServerTopic();
|
||||
}
|
||||
|
||||
public void SubRpcServerTopic()
|
||||
private void SubRpcServerTopic()
|
||||
{
|
||||
var rsSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
|
||||
.WithTopicFilter(o =>
|
||||
|
||||
+46
-7
@@ -13,6 +13,7 @@ using MQTTnet.Formatter;
|
||||
using SimApi.Attributes;
|
||||
using SimApi.Communications;
|
||||
using SimApi.Configurations;
|
||||
using SimApi.Exceptions;
|
||||
using SimApi.Helpers;
|
||||
|
||||
namespace SimApi;
|
||||
@@ -86,9 +87,12 @@ public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logge
|
||||
/// <param name="appName"></param>
|
||||
/// <param name="method"></param>
|
||||
/// <param name="param"></param>
|
||||
/// <param name="headers"></param>
|
||||
/// <param name="timeout"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public SimApiBaseResponse<T> Rpc<T>(string appName, string method, dynamic? param = null)
|
||||
public SimApiBaseResponse<T> Rpc<T>(string appName, string method, dynamic? param = null,
|
||||
Dictionary<string, string>? headers = null, int? timeout = null)
|
||||
{
|
||||
var res = new SimApiBaseResponse(500, "Synapse Rpc Client Disabled!");
|
||||
if (Options.DisableRpcClient)
|
||||
@@ -97,7 +101,7 @@ public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logge
|
||||
}
|
||||
else
|
||||
{
|
||||
var data = FireRpc(appName, method, param);
|
||||
var data = FireRpc(appName, method, param, headers, timeout);
|
||||
res = JsonSerializer.Deserialize<SimApiBaseResponse<T>>(data, SimApiUtil.JsonOption);
|
||||
}
|
||||
|
||||
@@ -110,14 +114,40 @@ public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logge
|
||||
/// <param name="appName"></param>
|
||||
/// <param name="method"></param>
|
||||
/// <param name="param"></param>
|
||||
/// <param name="headers"></param>
|
||||
/// <param name="timeout"></param>
|
||||
/// <returns></returns>
|
||||
public SimApiBaseResponse<object> Rpc(string appName, string method, dynamic? param = null)
|
||||
public SimApiBaseResponse<object> Rpc(string appName, string method, dynamic? param = null,
|
||||
Dictionary<string, string>? headers = null, int? timeout = null)
|
||||
{
|
||||
return Rpc<object>(appName, method, param);
|
||||
return Rpc<object>(appName, method, param, headers, timeout);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 只能在Rpc方法中使用,快捷抛出异常返回
|
||||
/// </summary>
|
||||
/// <param name="code"></param>
|
||||
/// <param name="message"></param>
|
||||
/// <exception cref="SimApiException"></exception>
|
||||
public void RpcError(int code, string message = "")
|
||||
{
|
||||
throw new SimApiException(code, message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// 如果条件成立,则爆出错误
|
||||
/// </summary>
|
||||
/// <param name="condition"></param>
|
||||
/// <param name="code"></param>
|
||||
/// <param name="message"></param>
|
||||
public void RpcErrorWhen(bool condition, int code, string message = "")
|
||||
{
|
||||
if (condition) RpcError(code, message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发送一个事件x
|
||||
/// </summary>
|
||||
/// <param name="eventName"></param>
|
||||
/// <param name="param"></param>
|
||||
@@ -247,10 +277,19 @@ public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logge
|
||||
|
||||
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(tmp.Class!);
|
||||
var mt = callClass.GetType().GetMethod(tmp.Method);
|
||||
if (mt!.GetParameters().Length > 1)
|
||||
if (mt!.GetParameters().Length > 2)
|
||||
{
|
||||
logger.LogError(
|
||||
"Synapse Rpc Register Error: Only one or none parameter supported. {Key} -> {Method}@{Class}",
|
||||
"Synapse Rpc Register Error: Only 1,2 or none parameter supported. {Key} -> {Method}@{Class}",
|
||||
tmp.Key, tmp.Method, tmp.Class.Name);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (mt.GetParameters().Length == 2 &&
|
||||
mt.GetParameters()[1].ParameterType != typeof(Dictionary<string, string>))
|
||||
{
|
||||
logger.LogError(
|
||||
"Synapse Rpc Register Error: RpcMethod Parameter 2 must be Dictionary<string, string>. {Key} -> {Method}@{Class}",
|
||||
tmp.Key, tmp.Method, tmp.Class.Name);
|
||||
continue;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user