Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
87fda473d3 | ||
|
|
4ae72d2e6b | ||
|
|
afea9c82bd | ||
|
|
e53048a980 | ||
|
|
bbc2806995 | ||
|
|
404a638d5e | ||
|
|
e27d5e1c77 | ||
|
|
6af68da3eb | ||
|
|
7dc2ac6a86 | ||
|
|
8f6b853b6c | ||
|
|
e876486c00 | ||
|
|
e71226be4a | ||
|
|
bd674dcc31 | ||
|
|
141846d79d |
@@ -0,0 +1,8 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace SimApi.Attributes;
|
||||||
|
|
||||||
|
[AttributeUsage(AttributeTargets.Method)]
|
||||||
|
public class OriginResponseAttribute : Attribute
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -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,51 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using SimApi.Attributes;
|
||||||
|
using SimApi.Communications;
|
||||||
|
using SimApi.Controllers;
|
||||||
|
using SimApi.Helpers;
|
||||||
|
|
||||||
|
namespace SimApi.CoceSdk;
|
||||||
|
|
||||||
|
public class CoceController(CoceApp coce, SimApiAuth auth, IServiceProvider sp) : 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,
|
||||||
|
};
|
||||||
|
var processor = sp.GetService<ICoceLoginProcessor>();
|
||||||
|
processor?.Process(loginItem, groups.ToArray());
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using SimApi.Communications;
|
||||||
|
|
||||||
|
namespace SimApi.CoceSdk;
|
||||||
|
|
||||||
|
public interface ICoceLoginProcessor
|
||||||
|
{
|
||||||
|
SimApiLoginItem Process(SimApiLoginItem loginItem, GroupInfo[] groups);
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
|
using SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi.Communications;
|
namespace SimApi.Communications;
|
||||||
|
|
||||||
@@ -36,15 +37,7 @@ public class SimApiBaseResponse(int code = 200, string message = "成功")
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public override string ToString()
|
public override string ToString()
|
||||||
{
|
{
|
||||||
return JsonSerializer.Serialize(this, new JsonSerializerOptions
|
return SimApiUtil.Json(this);
|
||||||
{
|
|
||||||
IgnoreReadOnlyProperties = true,
|
|
||||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
|
||||||
Converters =
|
|
||||||
{
|
|
||||||
new JsonStringEnumConverter()
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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; } = null!;
|
||||||
|
public string[] Type { get; set; } = ["user"];
|
||||||
|
public Dictionary<string, string> Meta { get; set; } = new();
|
||||||
|
public object? Extra { get; set; }
|
||||||
|
};
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
namespace SimApi.Configurations;
|
||||||
|
|
||||||
|
public class SimApiJobOptions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// WebUi地址,设置为null表示不启用
|
||||||
|
/// </summary>
|
||||||
|
public string? DashboardUrl { get; set; } = "/jobs";
|
||||||
|
|
||||||
|
public string DashboardAuthUser { get; set; } = "admin";
|
||||||
|
public string DashboardAuthPass { get; set; } = "Admin@123!";
|
||||||
|
public string? RedisConfiguration { get; set; }
|
||||||
|
|
||||||
|
public int? Database { get; set; } = null;
|
||||||
|
public SimApiJobServerConfig[] Servers { get; set; } = [new()];
|
||||||
|
}
|
||||||
|
|
||||||
|
public class SimApiJobServerConfig()
|
||||||
|
{
|
||||||
|
public string[] Queues { get; set; } = ["default"];
|
||||||
|
public int WorkerNum { get; set; } = 50;
|
||||||
|
}
|
||||||
@@ -1,14 +1,16 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using SimApi.CoceSdk;
|
||||||
|
|
||||||
namespace SimApi.Configurations;
|
namespace SimApi.Configurations;
|
||||||
|
|
||||||
public class SimApiOptions
|
public class SimApiOptions
|
||||||
{
|
{
|
||||||
|
public string? RedisConfiguration { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启用全部Cors,对于开发前后分离的时候很有用。
|
/// 是否启用后台任务系统 *基于Hangfire
|
||||||
/// default: true
|
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableCors { get; set; } = true;
|
public bool EnableJob { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启用SimApiAuth,一个简单的基于Header Token的认证方式。
|
/// 启用SimApiAuth,一个简单的基于Header Token的认证方式。
|
||||||
@@ -16,12 +18,37 @@ public class SimApiOptions
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSimApiAuth { get; set; }
|
public bool EnableSimApiAuth { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否使用CoceSdk
|
||||||
|
/// </summary>
|
||||||
|
public bool EnableCoceSdk { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 开启S3兼容的存储系统。
|
||||||
|
/// default: false
|
||||||
|
/// </summary>
|
||||||
|
public bool EnableSimApiStorage { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启用在线文档,启用后 访问 /swagger 可以查看对应的api文档。
|
/// 启用在线文档,启用后 访问 /swagger 可以查看对应的api文档。
|
||||||
/// default: false
|
/// default: false
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSimApiDoc { get; set; }
|
public bool EnableSimApiDoc { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否启用Synapse
|
||||||
|
/// </summary>
|
||||||
|
public bool EnableSynapse { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 启用全部Cors,对于开发前后分离的时候很有用。
|
||||||
|
/// default: true
|
||||||
|
/// </summary>
|
||||||
|
public bool EnableCors { get; set; } = true;
|
||||||
|
|
||||||
|
|
||||||
|
public CoceAppSdkOption CoceSdkOptions { get; set; } = new();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启用异常拦截,启用后,所有的异常将被通过json反馈。
|
/// 启用异常拦截,启用后,所有的异常将被通过json反馈。
|
||||||
/// default: true
|
/// default: true
|
||||||
@@ -29,10 +56,10 @@ public class SimApiOptions
|
|||||||
public bool EnableSimApiException { get; set; } = true;
|
public bool EnableSimApiException { get; set; } = true;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 开启S3兼容的存储系统。
|
/// 启用返回结果拦截
|
||||||
/// default: false
|
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSimApiStorage { get; set; }
|
public bool EnableSimApiResponseFilter { get; set; } = true;
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 开启ForwardHeaders,开启后可以透传负载均衡的Headers
|
/// 开启ForwardHeaders,开启后可以透传负载均衡的Headers
|
||||||
@@ -46,17 +73,18 @@ public class SimApiOptions
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableLowerUrl { get; set; } = true;
|
public bool EnableLowerUrl { get; set; } = true;
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启用格式化的 Console Logger
|
/// 启用格式化的 Console Logger
|
||||||
/// default: false
|
/// default: false
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableLogger { get; set; }
|
public bool EnableLogger { get; set; } = true;
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 是否启用Synapse
|
/// 配置Job
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSynapse { get; set; }
|
public SimApiJobOptions SimApiJobOptions { get; set; } = new();
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Swagger文档相关配置,需要启用 EnableSimApiDoc
|
/// Swagger文档相关配置,需要启用 EnableSimApiDoc
|
||||||
@@ -75,9 +103,9 @@ public class SimApiOptions
|
|||||||
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)
|
||||||
@@ -89,4 +117,9 @@ public class SimApiOptions
|
|||||||
{
|
{
|
||||||
options?.Invoke(SimApiStorageOptions);
|
options?.Invoke(SimApiStorageOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void ConfigureSimApiJob(Action<SimApiJobOptions>? options = null)
|
||||||
|
{
|
||||||
|
options?.Invoke(SimApiJobOptions);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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);
|
||||||
|
|||||||
+7
-41
@@ -1,6 +1,4 @@
|
|||||||
#nullable enable
|
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Microsoft.Extensions.Caching.Distributed;
|
using Microsoft.Extensions.Caching.Distributed;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
@@ -13,48 +11,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>
|
||||||
@@ -65,7 +31,7 @@ public class SimApiAuth(IDistributedCache cache)
|
|||||||
public SimApiLoginItem? GetLogin(string token)
|
public SimApiLoginItem? GetLogin(string token)
|
||||||
{
|
{
|
||||||
var login = cache.GetString(token);
|
var login = cache.GetString(token);
|
||||||
return login != null ? JsonSerializer.Deserialize<SimApiLoginItem>(login) : default;
|
return login != null ? JsonSerializer.Deserialize<SimApiLoginItem>(login) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using Microsoft.Extensions.Caching.Distributed;
|
||||||
|
|
||||||
|
namespace SimApi.Helpers;
|
||||||
|
|
||||||
|
public class SimApiCache(IDistributedCache cache)
|
||||||
|
{
|
||||||
|
private const string Prefix = "SimApi:Cache:";
|
||||||
|
|
||||||
|
public void Set(string key, object value, DistributedCacheEntryOptions? options = null)
|
||||||
|
{
|
||||||
|
if (options is not null)
|
||||||
|
{
|
||||||
|
cache.SetString(Prefix + key, SimApiUtil.Json(value), options);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
cache.SetString(Prefix + key, SimApiUtil.Json(value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public string? Get(string key)
|
||||||
|
{
|
||||||
|
return cache.GetString(Prefix + key);
|
||||||
|
}
|
||||||
|
|
||||||
|
public T? Get<T>(string key)
|
||||||
|
{
|
||||||
|
var data = cache.GetString(Prefix + key);
|
||||||
|
return data == null ? default : JsonSerializer.Deserialize<T>(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using Hangfire.Dashboard;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
|
||||||
|
namespace SimApi.Helpers;
|
||||||
|
|
||||||
|
public class SimApiJobWebAuth(string user, string pass) : IDashboardAuthorizationFilter
|
||||||
|
{
|
||||||
|
public bool Authorize(DashboardContext context)
|
||||||
|
{
|
||||||
|
var httpContext = context.GetHttpContext();
|
||||||
|
var authHeader = httpContext.Request.Headers["Authorization"].FirstOrDefault();
|
||||||
|
if (authHeader != null && authHeader.StartsWith("Basic "))
|
||||||
|
{
|
||||||
|
var encodedUsernamePassword = authHeader.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries)[1].Trim();
|
||||||
|
var decodedUsernamePassword = Encoding.UTF8.GetString(Convert.FromBase64String(encodedUsernamePassword));
|
||||||
|
var username = decodedUsernamePassword.Split(':', 2)[0];
|
||||||
|
var password = decodedUsernamePassword.Split(':', 2)[1];
|
||||||
|
|
||||||
|
if (username == user && password == pass)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
httpContext.Response.StatusCode = 401;
|
||||||
|
httpContext.Response.Headers.WWWAuthenticate = "Basic realm=\"SimApiBasicAuth\"";
|
||||||
|
httpContext.Response.WriteAsync("").Wait();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Filters;
|
||||||
|
using SimApi.Attributes;
|
||||||
|
using SimApi.Communications;
|
||||||
|
|
||||||
|
namespace SimApi.Helpers;
|
||||||
|
|
||||||
|
public class SimApiResponseFilter : IResultFilter
|
||||||
|
{
|
||||||
|
public void OnResultExecuting(ResultExecutingContext context)
|
||||||
|
{
|
||||||
|
if (context.ActionDescriptor.EndpointMetadata.Any(meta => meta is OriginResponseAttribute))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
context.Result = context.Result switch
|
||||||
|
{
|
||||||
|
// 检查结果是否为 null
|
||||||
|
null => new OkObjectResult(new SimApiBaseResponse()),
|
||||||
|
ObjectResult { Value: SimApiBaseResponse simApiBaseResponse } =>
|
||||||
|
new OkObjectResult(simApiBaseResponse),
|
||||||
|
ObjectResult objectResult => new OkObjectResult(new SimApiBaseResponse<object>(objectResult.Value!)),
|
||||||
|
EmptyResult => new OkObjectResult(new SimApiBaseResponse()),
|
||||||
|
_ => context.Result
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnResultExecuted(ResultExecutedContext context)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
+35
-1
@@ -1,4 +1,5 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
@@ -7,6 +8,7 @@ using System.Text.Json;
|
|||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
using System.Text.Unicode;
|
using System.Text.Unicode;
|
||||||
|
using System.Xml.Serialization;
|
||||||
|
|
||||||
namespace SimApi.Helpers;
|
namespace SimApi.Helpers;
|
||||||
|
|
||||||
@@ -22,6 +24,7 @@ public static class SimApiUtil
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public static JsonSerializerOptions JsonOption => new()
|
public static JsonSerializerOptions JsonOption => new()
|
||||||
{
|
{
|
||||||
|
ReferenceHandler = ReferenceHandler.Preserve,
|
||||||
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
|
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
|
||||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
|
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
|
||||||
@@ -62,12 +65,43 @@ public static class SimApiUtil
|
|||||||
return stringBuilder.ToString();
|
return stringBuilder.ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// sha1加密字符串
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source">源字符串</param>
|
||||||
|
/// <param name="mode">加密结果"x2"结果为32位,"x3"结果为48位,"x4"结果为64位</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static string Sha1(string source, string mode = "x2")
|
||||||
|
{
|
||||||
|
var hash = SHA1.HashData(Encoding.UTF8.GetBytes(source));
|
||||||
|
var sb = new StringBuilder(hash.Length * 2);
|
||||||
|
foreach (var b in hash)
|
||||||
|
{
|
||||||
|
sb.Append(b.ToString(mode));
|
||||||
|
}
|
||||||
|
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 将XML字符串序列化为对象
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source"></param>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static T XmlDeserialize<T>(string source)
|
||||||
|
{
|
||||||
|
var xmlConvertor = new XmlSerializer(typeof(T));
|
||||||
|
using var reader = new StringReader(source);
|
||||||
|
return (T)xmlConvertor.Deserialize(reader)!;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 将对象序列化成JSON (控制台输出中文不会被编码)
|
/// 将对象序列化成JSON (控制台输出中文不会被编码)
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="obj"></param>
|
/// <param name="obj"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static string Json(object obj)
|
public static string Json(object? obj)
|
||||||
{
|
{
|
||||||
return JsonSerializer.Serialize(obj, JsonOption);
|
return JsonSerializer.Serialize(obj, JsonOption);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Linq;
|
using System.IO;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
@@ -27,12 +27,11 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
|
|||||||
switch (context.Response.StatusCode)
|
switch (context.Response.StatusCode)
|
||||||
{
|
{
|
||||||
case 200:
|
case 200:
|
||||||
break;
|
|
||||||
case 404:
|
|
||||||
throw new SimApiException(context.Response.StatusCode, "请求的接口不存在");
|
|
||||||
case 301:
|
case 301:
|
||||||
case 302:
|
case 302:
|
||||||
break;
|
break;
|
||||||
|
case 404:
|
||||||
|
throw new SimApiException(context.Response.StatusCode, "请求的接口不存在");
|
||||||
default:
|
default:
|
||||||
throw new SimApiException(context.Response.StatusCode);
|
throw new SimApiException(context.Response.StatusCode);
|
||||||
}
|
}
|
||||||
@@ -42,7 +41,6 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
|
|||||||
response = string.IsNullOrEmpty(ex.Message)
|
response = string.IsNullOrEmpty(ex.Message)
|
||||||
? new SimApiBaseResponse(ex.Code)
|
? new SimApiBaseResponse(ex.Code)
|
||||||
: new SimApiBaseResponse(ex.Code, ex.Message);
|
: new SimApiBaseResponse(ex.Code, ex.Message);
|
||||||
|
|
||||||
ErrorResponse(context, response);
|
ErrorResponse(context, response);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@@ -61,9 +59,8 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
|
|||||||
/// <param name="response"></param>
|
/// <param name="response"></param>
|
||||||
private static void ErrorResponse(HttpContext context, SimApiBaseResponse response)
|
private static void ErrorResponse(HttpContext context, SimApiBaseResponse response)
|
||||||
{
|
{
|
||||||
if (context.Response.HasStarted) return;
|
|
||||||
context.Response.StatusCode = 200;
|
context.Response.StatusCode = 200;
|
||||||
context.Response.Headers.Append("Content-Type", "application/json");
|
context.Response.Headers.Append("Content-Type", "application/json");
|
||||||
context.Response.WriteAsync(response.ToString());
|
context.Response.WriteAsync(response.ToString()).Wait();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+8
-7
@@ -19,17 +19,18 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Folder Include="Helpers\"/>
|
|
||||||
<Folder Include="Communications\"/>
|
<Folder Include="Communications\"/>
|
||||||
<Folder Include="Controllers\"/>
|
|
||||||
<Folder Include="Middlewares\"/>
|
|
||||||
<Folder Include="Exceptions\"/>
|
<Folder Include="Exceptions\"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Minio" Version="6.0.3" />
|
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.18" />
|
||||||
<PackageReference Include="MQTTnet" Version="4.3.6.1152" />
|
<PackageReference Include="Hangfire.Console" Version="1.4.3" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.6.2" />
|
<PackageReference Include="Hangfire.Redis.StackExchange" Version="1.12.0" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.6.2" />
|
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="9.0.5" />
|
||||||
|
<PackageReference Include="Minio" Version="6.0.4" />
|
||||||
|
<PackageReference Include="MQTTnet" Version="5.0.1.1416" />
|
||||||
|
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="8.1.1" />
|
||||||
|
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="8.1.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ProjectExtensions>
|
<ProjectExtensions>
|
||||||
<MonoDevelop>
|
<MonoDevelop>
|
||||||
|
|||||||
+143
-16
@@ -1,4 +1,12 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
using Hangfire;
|
||||||
|
using Hangfire.Console;
|
||||||
|
using Hangfire.Redis.StackExchange;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Builder;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
@@ -7,6 +15,8 @@ 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.Attributes;
|
||||||
|
using SimApi.CoceSdk;
|
||||||
using SimApi.Configurations;
|
using SimApi.Configurations;
|
||||||
using SimApi.Logger;
|
using SimApi.Logger;
|
||||||
|
|
||||||
@@ -23,6 +33,12 @@ public static class SimApiExtensions
|
|||||||
{
|
{
|
||||||
var simApiOptions = new SimApiOptions();
|
var simApiOptions = new SimApiOptions();
|
||||||
options?.Invoke(simApiOptions);
|
options?.Invoke(simApiOptions);
|
||||||
|
if (simApiOptions.RedisConfiguration != null)
|
||||||
|
{
|
||||||
|
builder.AddStackExchangeRedisCache(x => x.Configuration = simApiOptions.RedisConfiguration);
|
||||||
|
builder.AddSingleton<SimApiCache>();
|
||||||
|
}
|
||||||
|
|
||||||
if (simApiOptions.EnableLogger)
|
if (simApiOptions.EnableLogger)
|
||||||
{
|
{
|
||||||
builder.AddLogging(logger =>
|
builder.AddLogging(logger =>
|
||||||
@@ -38,6 +54,35 @@ public static class SimApiExtensions
|
|||||||
builder.AddSingleton<SimApiAuth>();
|
builder.AddSingleton<SimApiAuth>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (simApiOptions.EnableCoceSdk)
|
||||||
|
{
|
||||||
|
builder.AddSingleton<CoceApp>();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (simApiOptions.EnableJob)
|
||||||
|
{
|
||||||
|
builder.AddHangfire(x =>
|
||||||
|
{
|
||||||
|
var redisOption = new RedisStorageOptions();
|
||||||
|
if (simApiOptions.SimApiJobOptions.Database.HasValue)
|
||||||
|
{
|
||||||
|
redisOption.Db = simApiOptions.SimApiJobOptions.Database.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
x.UseRedisStorage(simApiOptions.SimApiJobOptions.RedisConfiguration ??
|
||||||
|
simApiOptions.RedisConfiguration, redisOption);
|
||||||
|
x.UseConsole();
|
||||||
|
});
|
||||||
|
foreach (var server in simApiOptions.SimApiJobOptions.Servers)
|
||||||
|
{
|
||||||
|
builder.AddHangfireServer(hfs =>
|
||||||
|
{
|
||||||
|
hfs.Queues = server.Queues;
|
||||||
|
hfs.WorkerCount = server.WorkerNum;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (simApiOptions.EnableCors)
|
if (simApiOptions.EnableCors)
|
||||||
{
|
{
|
||||||
builder.AddCors(cors => cors.AddPolicy("any",
|
builder.AddCors(cors => cors.AddPolicy("any",
|
||||||
@@ -47,6 +92,19 @@ public static class SimApiExtensions
|
|||||||
if (simApiOptions.EnableSynapse)
|
if (simApiOptions.EnableSynapse)
|
||||||
{
|
{
|
||||||
builder.AddSingleton<Synapse>();
|
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
|
// 使用SimApiDoc
|
||||||
@@ -147,7 +205,7 @@ public static class SimApiExtensions
|
|||||||
Id = "oauth2"
|
Id = "oauth2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
new[] { "SimApiAuth" }
|
["SimApiAuth"]
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -186,6 +244,17 @@ public static class SimApiExtensions
|
|||||||
builder.AddSingleton<SimApiStorage>();
|
builder.AddSingleton<SimApiStorage>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (simApiOptions.EnableSimApiResponseFilter)
|
||||||
|
{
|
||||||
|
builder.AddControllers(opt => opt.Filters.Add<SimApiResponseFilter>())
|
||||||
|
.AddXmlSerializerFormatters()
|
||||||
|
.AddJsonOptions(opt =>
|
||||||
|
{
|
||||||
|
opt.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
|
||||||
|
opt.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
builder.AddSingleton(simApiOptions);
|
builder.AddSingleton(simApiOptions);
|
||||||
return builder;
|
return builder;
|
||||||
}
|
}
|
||||||
@@ -198,6 +267,11 @@ public static class SimApiExtensions
|
|||||||
|
|
||||||
logger.LogInformation("当前时区: {LocalId}", TimeZoneInfo.Local.Id);
|
logger.LogInformation("当前时区: {LocalId}", TimeZoneInfo.Local.Id);
|
||||||
|
|
||||||
|
if (options.RedisConfiguration != null)
|
||||||
|
{
|
||||||
|
logger.LogInformation("开始配置 RedisCache ...");
|
||||||
|
}
|
||||||
|
|
||||||
//请求一下检测存储错误
|
//请求一下检测存储错误
|
||||||
if (options.EnableSimApiStorage)
|
if (options.EnableSimApiStorage)
|
||||||
{
|
{
|
||||||
@@ -205,9 +279,11 @@ public static class SimApiExtensions
|
|||||||
builder.Services.GetService<SimApiStorage>();
|
builder.Services.GetService<SimApiStorage>();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.EnableLowerUrl)
|
if (options.EnableCoceSdk)
|
||||||
{
|
{
|
||||||
logger.LogInformation("开始配置使用URL小写...");
|
logger.LogInformation("开始配置CoceAppSdk...\nApi入口: {ApiUrl}\nAuth入口:{AuthUrl}n\nAppId: {AppId}",
|
||||||
|
options.CoceSdkOptions.ApiEndpoint, options.CoceSdkOptions.AuthEndpoint,
|
||||||
|
options.CoceSdkOptions.AppId);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.EnableSynapse)
|
if (options.EnableSynapse)
|
||||||
@@ -216,6 +292,11 @@ public static class SimApiExtensions
|
|||||||
synapse.Init();
|
synapse.Init();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (options.EnableJob)
|
||||||
|
{
|
||||||
|
logger.LogInformation("开始配置 SimApiJob ...");
|
||||||
|
}
|
||||||
|
|
||||||
return builder;
|
return builder;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -227,10 +308,8 @@ public static class SimApiExtensions
|
|||||||
public static WebApplication UseSimApi(this WebApplication builder)
|
public static WebApplication UseSimApi(this WebApplication builder)
|
||||||
{
|
{
|
||||||
var options = builder.Services.GetRequiredService<SimApiOptions>();
|
var options = builder.Services.GetRequiredService<SimApiOptions>();
|
||||||
|
|
||||||
var logger = builder.Services.GetRequiredService<ILogger<SimApiOptions>>();
|
var logger = builder.Services.GetRequiredService<ILogger<SimApiOptions>>();
|
||||||
|
UseSimApi((IHost)builder);
|
||||||
logger.LogInformation("当前时区: {LocalId}", TimeZoneInfo.Local.Id);
|
|
||||||
if (options.EnableForwardHeaders)
|
if (options.EnableForwardHeaders)
|
||||||
{
|
{
|
||||||
logger.LogInformation("开始配置ForwardedHeaders...");
|
logger.LogInformation("开始配置ForwardedHeaders...");
|
||||||
@@ -243,10 +322,58 @@ public static class SimApiExtensions
|
|||||||
builder.UseCors("any");
|
builder.UseCors("any");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (options.EnableSimApiResponseFilter)
|
||||||
|
{
|
||||||
|
logger.LogInformation("开始配置SimApiResponseFilter...");
|
||||||
|
builder.MapControllers();
|
||||||
|
}
|
||||||
|
|
||||||
if (options.EnableSimApiAuth)
|
if (options.EnableSimApiAuth)
|
||||||
{
|
{
|
||||||
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 = "Coce",
|
||||||
|
action = "Login"
|
||||||
|
});
|
||||||
|
builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/user/groups",
|
||||||
|
defaults: new
|
||||||
|
{
|
||||||
|
controller = "Coce",
|
||||||
|
action = "ListGroups"
|
||||||
|
});
|
||||||
|
builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/auth/config",
|
||||||
|
defaults: new
|
||||||
|
{
|
||||||
|
controller = "Coce",
|
||||||
|
action = "GetConfig"
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.EnableSimApiDoc)
|
if (options.EnableSimApiDoc)
|
||||||
@@ -273,22 +400,22 @@ public static class SimApiExtensions
|
|||||||
builder.UseMiddleware<SimApiExceptionMiddleware>();
|
builder.UseMiddleware<SimApiExceptionMiddleware>();
|
||||||
}
|
}
|
||||||
|
|
||||||
//请求一下检测存储错误
|
|
||||||
if (options.EnableSimApiStorage)
|
|
||||||
{
|
|
||||||
logger.LogInformation("开始配置SimApiStorage...");
|
|
||||||
builder.Services.GetService<SimApiStorage>();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options.EnableLowerUrl)
|
if (options.EnableLowerUrl)
|
||||||
{
|
{
|
||||||
logger.LogInformation("开始配置使用URL小写...");
|
logger.LogInformation("开始配置使用URL小写...");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.EnableSynapse)
|
if (options is { EnableJob: true, SimApiJobOptions.DashboardUrl: not null })
|
||||||
{
|
{
|
||||||
var synapse = builder.Services.GetRequiredService<Synapse>();
|
logger.LogInformation("开始配置 SimApiJob Web控制台...");
|
||||||
synapse.Init();
|
builder.UseHangfireDashboard(options.SimApiJobOptions.DashboardUrl, new DashboardOptions
|
||||||
|
{
|
||||||
|
Authorization =
|
||||||
|
[
|
||||||
|
new SimApiJobWebAuth(options.SimApiJobOptions.DashboardAuthUser,
|
||||||
|
options.SimApiJobOptions.DashboardAuthPass)
|
||||||
|
]
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return builder;
|
return builder;
|
||||||
|
|||||||
+12
-10
@@ -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,14 +13,13 @@ namespace SimApi;
|
|||||||
|
|
||||||
public partial class Synapse
|
public partial class Synapse
|
||||||
{
|
{
|
||||||
|
|
||||||
private string EventServerTopicPrefix => $"{Options.SysName}/event/";
|
private string EventServerTopicPrefix => $"{Options.SysName}/event/";
|
||||||
|
|
||||||
private void RunEventServer()
|
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 reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
||||||
var eventName = e.ApplicationMessage.Topic.Replace(EventServerTopicPrefix, 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);
|
||||||
@@ -27,7 +27,7 @@ public partial class Synapse
|
|||||||
.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!);
|
||||||
@@ -37,20 +37,21 @@ public partial class Synapse
|
|||||||
{
|
{
|
||||||
var pt = mt.GetParameters()[1].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}\n{Stack}", ex.Message,ex.StackTrace);
|
logger.LogError("Synapse Event Processor Error: {Err}\n{Stack}", ex.Message, ex.StackTrace);
|
||||||
}
|
}
|
||||||
}
|
}))
|
||||||
return Task.CompletedTask;
|
.ToList();
|
||||||
|
await Task.WhenAll(tasks);
|
||||||
};
|
};
|
||||||
SubEventServerTopic();
|
SubEventServerTopic();
|
||||||
}
|
}
|
||||||
@@ -64,6 +65,7 @@ public partial class Synapse
|
|||||||
{
|
{
|
||||||
topic = "$queue/" + topic;
|
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();
|
||||||
|
|||||||
+18
-9
@@ -1,10 +1,12 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using MQTTnet;
|
using MQTTnet;
|
||||||
|
using MQTTnet.Packets;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
|
||||||
@@ -38,7 +40,8 @@ public partial class Synapse
|
|||||||
Client!.SubscribeAsync(rcSubOpts).Wait();
|
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;
|
string paramJson;
|
||||||
if (param is string strParam)
|
if (param is string strParam)
|
||||||
@@ -54,23 +57,29 @@ public partial class Synapse
|
|||||||
var messageId = Guid.NewGuid().ToString();
|
var messageId = Guid.NewGuid().ToString();
|
||||||
var tcs = new TaskCompletionSource<string>();
|
var tcs = new TaskCompletionSource<string>();
|
||||||
ResponseCompletionSources.Add(messageId, tcs);
|
ResponseCompletionSources.Add(messageId, tcs);
|
||||||
var message = new MqttApplicationMessageBuilder()
|
var messageBuilder = new MqttApplicationMessageBuilder()
|
||||||
.WithTopic(topic)
|
.WithTopic(topic)
|
||||||
.WithPayload(paramJson)
|
.WithPayload(paramJson)
|
||||||
.WithResponseTopic($"{Options.AppName},{Options.AppId}")
|
.WithResponseTopic($"{Options.AppName},{Options.AppId},{messageId}")
|
||||||
.WithContentType(messageId)
|
.WithContentType("application/json")
|
||||||
.WithRetainFlag(false)
|
.WithRetainFlag(false);
|
||||||
.Build();
|
foreach (var h in headers ?? new Dictionary<string, string>())
|
||||||
|
{
|
||||||
|
messageBuilder.WithUserProperty(h.Key, h.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
var message = messageBuilder.Build();
|
||||||
if (!Client!.IsConnected) return null;
|
if (!Client!.IsConnected) return null;
|
||||||
Client.PublishAsync(message, CancellationToken.None).Wait();
|
Client.PublishAsync(message, CancellationToken.None).Wait();
|
||||||
logger.LogDebug(
|
logger.LogDebug(
|
||||||
"Synapse RPC Client Request: ({PropsMessageId}) {OptionsAppName} -> {Action}@{App}\n{ParamJson}", messageId,
|
"Synapse RPC Client Request: ({PropsMessageId}) {OptionsAppName} -> {Action}@{App}\n{ParamJson}\nHeaders: {Headers}",
|
||||||
Options.AppName, action, app, paramJson);
|
messageId, Options.AppName, action, app, paramJson, JsonSerializer.Serialize(headers));
|
||||||
|
|
||||||
string response;
|
string response;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (tcs.Task.Wait(Options.RpcTimeout * 1000))
|
timeout ??= Options.RpcTimeout;
|
||||||
|
if (tcs.Task.Wait(timeout.Value * 1000))
|
||||||
{
|
{
|
||||||
response = tcs.Task.Result;
|
response = tcs.Task.Result;
|
||||||
logger.LogDebug(
|
logger.LogDebug(
|
||||||
|
|||||||
+26
-10
@@ -28,28 +28,42 @@ public partial class Synapse
|
|||||||
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}",
|
||||||
e.ApplicationMessage.ContentType, appInfo[0], action, Options.AppName,
|
appInfo[2], appInfo[0], action, Options.AppName, 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
|
||||||
{
|
{
|
||||||
var methodParams = mt!.GetParameters();
|
var methodParams = mt!.GetParameters();
|
||||||
object? ret;
|
object? ret;
|
||||||
if (methodParams.Length == 0)
|
switch (methodParams.Length)
|
||||||
{
|
|
||||||
ret = mt.Invoke(callClass, []);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
{
|
||||||
|
case 1:
|
||||||
var pt = mt.GetParameters()[0].ParameterType;
|
var pt = mt.GetParameters()[0].ParameterType;
|
||||||
var param = pt == typeof(string)
|
var param = pt == typeof(string)
|
||||||
? [reqBody]
|
? [reqBody]
|
||||||
: new[] { JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) };
|
: new[] { JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) };
|
||||||
ret = mt.Invoke(callClass, param);
|
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?>
|
res = new SimApiBaseResponse<object?>
|
||||||
@@ -66,6 +80,7 @@ public partial class Synapse
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
logger.LogError("Synapse RPC 方法异常: {Err}\n{Stack}", ex.Message, ex.StackTrace);
|
||||||
res = new SimApiBaseResponse(500, ex.Message);
|
res = new SimApiBaseResponse(500, ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -74,9 +89,10 @@ 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]}/{appInfo[2]}";
|
||||||
var message = new MqttApplicationMessageBuilder()
|
var message = new MqttApplicationMessageBuilder()
|
||||||
.WithTopic(reply)
|
.WithTopic(reply)
|
||||||
.WithPayload(returnJson)
|
.WithPayload(returnJson)
|
||||||
@@ -86,7 +102,7 @@ public partial class Synapse
|
|||||||
Client.PublishAsync(message, CancellationToken.None).Wait();
|
Client.PublishAsync(message, CancellationToken.None).Wait();
|
||||||
logger.LogDebug(
|
logger.LogDebug(
|
||||||
"Synapse Rpc Server Return: ({BasicPropertiesMessageId}) {BasicPropertiesType}@{OptionsAppName} -> {BasicPropertiesReplyTo}\n{ReturnJson}",
|
"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;
|
return Task.CompletedTask;
|
||||||
};
|
};
|
||||||
|
|||||||
+47
-9
@@ -8,11 +8,11 @@ using System.Threading.Tasks;
|
|||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using MQTTnet;
|
using MQTTnet;
|
||||||
using MQTTnet.Client;
|
|
||||||
using MQTTnet.Formatter;
|
using MQTTnet.Formatter;
|
||||||
using SimApi.Attributes;
|
using SimApi.Attributes;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
using SimApi.Configurations;
|
using SimApi.Configurations;
|
||||||
|
using SimApi.Exceptions;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi;
|
namespace SimApi;
|
||||||
@@ -21,7 +21,7 @@ public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logge
|
|||||||
{
|
{
|
||||||
private SimApiSynapseOptions Options { get; } = simApiOptions.SimApiSynapseOptions;
|
private SimApiSynapseOptions Options { get; } = simApiOptions.SimApiSynapseOptions;
|
||||||
|
|
||||||
private MqttFactory MqttFactory { get; } = new();
|
private MqttClientFactory MqttFactory { get; } = new();
|
||||||
public IMqttClient? Client { get; set; }
|
public IMqttClient? Client { get; set; }
|
||||||
|
|
||||||
private List<RegisterItem> EventRegistry { get; set; } = new();
|
private List<RegisterItem> EventRegistry { get; set; } = new();
|
||||||
@@ -86,9 +86,12 @@ public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logge
|
|||||||
/// <param name="appName"></param>
|
/// <param name="appName"></param>
|
||||||
/// <param name="method"></param>
|
/// <param name="method"></param>
|
||||||
/// <param name="param"></param>
|
/// <param name="param"></param>
|
||||||
|
/// <param name="headers"></param>
|
||||||
|
/// <param name="timeout"></param>
|
||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
/// <returns></returns>
|
/// <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!");
|
var res = new SimApiBaseResponse(500, "Synapse Rpc Client Disabled!");
|
||||||
if (Options.DisableRpcClient)
|
if (Options.DisableRpcClient)
|
||||||
@@ -97,7 +100,7 @@ public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logge
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
var data = FireRpc(appName, method, param);
|
var data = FireRpc(appName, method, param, headers, timeout);
|
||||||
res = JsonSerializer.Deserialize<SimApiBaseResponse<T>>(data, SimApiUtil.JsonOption);
|
res = JsonSerializer.Deserialize<SimApiBaseResponse<T>>(data, SimApiUtil.JsonOption);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,14 +113,40 @@ public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logge
|
|||||||
/// <param name="appName"></param>
|
/// <param name="appName"></param>
|
||||||
/// <param name="method"></param>
|
/// <param name="method"></param>
|
||||||
/// <param name="param"></param>
|
/// <param name="param"></param>
|
||||||
|
/// <param name="headers"></param>
|
||||||
|
/// <param name="timeout"></param>
|
||||||
/// <returns></returns>
|
/// <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>
|
||||||
///
|
/// 如果条件成立,则爆出错误
|
||||||
|
/// </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>
|
/// </summary>
|
||||||
/// <param name="eventName"></param>
|
/// <param name="eventName"></param>
|
||||||
/// <param name="param"></param>
|
/// <param name="param"></param>
|
||||||
@@ -247,10 +276,19 @@ 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 > 1)
|
if (mt!.GetParameters().Length > 2)
|
||||||
{
|
{
|
||||||
logger.LogError(
|
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);
|
tmp.Key, tmp.Method, tmp.Class.Name);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user