Files
zszq-trs/YLErpWeb/Hubs/SwapConfirmSendEmailHub.cs
T

109 lines
4.3 KiB
C#

using Microsoft.AspNetCore.SignalR;
using YLErp.DBModels;
using YLErp.Enums;
using YLErp.MailKit;
using YLErp.Modules.RiskModule;
using YLErp.Modules.SwapModule;
using static YLErp.ConsGlobal;
namespace YLErp.Web.Hubs
{
public class SwapConfirmSendEmailHub : Hub
{
private static bool isProcessing = false;
static readonly Dictionary<string, DateTime> _dic = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase);
static readonly Dictionary<int, string> _clientProgressDic = new Dictionary<int, string>();
public async Task StartProcessing(string jsonString)
{
SwapTradeSendEmailReq req = JsonHelper.Deserialize<SwapTradeSendEmailReq>(jsonString);
var connectionId = Context.ConnectionId;
var client = Clients.Client(connectionId);
if (Context.User == null)
{
await client.SendAsync("ExceptionMessage", "登录已失效,请重新登录");
return;
}
var user = Server.CacheProvider.Get("loginUser^" + Context.User.GetUserId()) as UserInfo;
if (user == null)
{
await client.SendAsync("ExceptionMessage", "登录已失效,请重新登录");
return;
}
var service = new SwapEndConfirmService(user);
if (isProcessing)
{
await client.SendAsync("ExceptionMessage", "正在发送邮件,请稍后再试");
foreach (var tradeId in req.tradeIds) {
var msg= GetProcess(tradeId,async (d) => {
await client.SendAsync("UpdateProgress", getUpdateProcess(tradeId, d));
});
await client.SendAsync("UpdateProgress", getUpdateProcess(tradeId, msg));
}
await client.SendAsync("ProcessCompleted", "");
return;
}
try
{
isProcessing = true;
_clientProgressDic.Clear();
_dic.Clear();
foreach (var tradeId in req.tradeIds)
{
_clientProgressDic[tradeId] = "发送中";
await client.SendAsync("UpdateProgress", getUpdateProcess(tradeId, "发送中"));
if (PS.Config.ErpElement.MailMessageRateLimit > 0)
{
var milliSeconds = 60d * 1000 / PS.Config.ErpElement.MailMessageRateLimit;
lock (_dic)
{
if (_dic.TryGetValue("sendEmail", out var dt))
{
while (dt < DateTime.Now && dt.AddMilliseconds(milliSeconds) > DateTime.Now)
{
Thread.Sleep(500);
}
}
_dic["sendEmail"] = DateTime.Now;
}
}
var result = service.SendConfirmEamil(tradeId);
_clientProgressDic[tradeId] = result;
await client.SendAsync("UpdateProgress", getUpdateProcess(tradeId, result));
}
isProcessing = false;
await client.SendAsync("ProcessCompleted", "");
}
catch (Exception ex)
{
isProcessing = false;
await client.SendAsync("ExceptionMessage", ex.Message);
}
}
private string GetProcess(int tradeId,Action<string> action)
{
if (_clientProgressDic.ContainsKey(tradeId))
{
string process= _clientProgressDic[tradeId];
if (action != null&& process=="发送中")
{
action.Invoke(process);
Thread.Sleep(1000);
return GetProcess(tradeId, action);
}
return process;
}
return "";
}
private string getUpdateProcess(int tradeId,string msg)
{
SwapTradeSendEmailResp resp = new SwapTradeSendEmailResp()
{
tradeId = tradeId,
send_email_result = msg
};
return JsonHelper.Serialize(resp);
}
}
}