feat: 发送消息优化
This commit is contained in:
@@ -1,9 +1,5 @@
|
||||
package com.budwk.app.base.sms.impl;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.crypto.digest.DigestUtil;
|
||||
import cn.hutool.http.HttpRequest;
|
||||
import cn.hutool.http.HttpResponse;
|
||||
import cn.hutool.json.JSONObject;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import com.budwk.app.base.exception.BaseException;
|
||||
@@ -11,14 +7,10 @@ import com.budwk.app.base.sms.SmsService;
|
||||
import com.budwk.app.base.sms.model.*;
|
||||
import com.budwk.app.web.commons.base.Globals;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.nutz.integration.jedis.RedisService;
|
||||
import org.nutz.ioc.impl.PropertiesProxy;
|
||||
import org.nutz.ioc.loader.annotation.Inject;
|
||||
import org.nutz.ioc.loader.annotation.IocBean;
|
||||
import org.nutz.json.Json;
|
||||
import org.nutz.lang.Lang;
|
||||
import org.nutz.lang.Strings;
|
||||
import org.nutz.lang.util.NutMap;
|
||||
import org.nutz.log.Log;
|
||||
import org.nutz.log.Logs;
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ public class ZjnuMsgService {
|
||||
public MsgPlatformResponse send(MsgPlatformBaseRequest request, String channel) {
|
||||
MsgPlatformResponse result = new MsgPlatformResponse();
|
||||
if (!conf.getBoolean("msg.platform.enabled", false)
|
||||
|| !Globals.MyConfig.getBoolean("SendMsg", Globals.MyConfig.getBoolean("AppSms", false))) {
|
||||
|| !Globals.MyConfig.getBoolean("AppSms", false)) {
|
||||
result.setCode(0);
|
||||
result.setResult(true);
|
||||
result.setMsg("通讯平台未启用,已跳过实际发送");
|
||||
@@ -67,6 +67,7 @@ public class ZjnuMsgService {
|
||||
}
|
||||
String account = recipient.getAccount();
|
||||
String mobile = recipient.getMobile();
|
||||
String name = recipient.getName();
|
||||
if (Strings.isBlank(mobile) && Strings.isNotBlank(account) && account.matches("^\\d{11}$")) {
|
||||
mobile = account;
|
||||
account = null;
|
||||
@@ -76,12 +77,21 @@ public class ZjnuMsgService {
|
||||
if (users.size() != 1) {
|
||||
throw new BaseException("无法通过手机号唯一确定浙师大消息接收人工号");
|
||||
}
|
||||
account = users.get(0).getLoginname();
|
||||
Sys_user user = users.get(0);
|
||||
account = user.getLoginname();
|
||||
if (Strings.isBlank(name)) {
|
||||
name = user.getUsername();
|
||||
}
|
||||
} else if (Strings.isNotBlank(account) && Strings.isBlank(name)) {
|
||||
Sys_user user = dao.fetch(Sys_user.class, Cnd.where(Sys_user::getLoginname, "=", account));
|
||||
if (user != null) {
|
||||
name = user.getUsername();
|
||||
}
|
||||
}
|
||||
if (Strings.isBlank(account)) {
|
||||
throw new BaseException("浙师大消息接收人工号不能为空");
|
||||
}
|
||||
receivers.add(Map.of("type", "User", "userId", account, "name", Strings.sNull(recipient.getName())));
|
||||
receivers.add(Map.of("type", "User", "userId", account, "name", Strings.sNull(name)));
|
||||
}
|
||||
try {
|
||||
Map<String, Object> payload = new LinkedHashMap<>();
|
||||
|
||||
@@ -29,11 +29,13 @@ import org.nutz.ioc.loader.annotation.IocBean;
|
||||
import org.nutz.lang.Strings;
|
||||
import org.nutz.mvc.annotation.At;
|
||||
import org.nutz.mvc.annotation.Ok;
|
||||
import org.nutz.mvc.annotation.POST;
|
||||
import org.nutz.mvc.annotation.Param;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.validation.Valid;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
@IocBean
|
||||
@@ -83,7 +85,10 @@ public class SysMsgController {
|
||||
cnd.and("msg.sendType", "!=", "hide");
|
||||
cnd.desc("msg.sendAt");
|
||||
sql.setCondition(cnd);
|
||||
Pagination pagination = sysMsgService.listPageMap(pageNumber, pageSize, sql);
|
||||
Pagination<Map<String, Object>> pagination = sysMsgService.listPageMap(pageNumber, pageSize, sql);
|
||||
for (Map<String, Object> row : pagination.getList()) {
|
||||
row.put("sendStatus", sysMsgService.getSendStatus((String) row.get("id")));
|
||||
}
|
||||
return Result.success().addData(pagination);
|
||||
} catch (Exception e) {
|
||||
return Result.error();
|
||||
@@ -170,12 +175,29 @@ public class SysMsgController {
|
||||
msg.setSendAt(DateUtil.current());
|
||||
msg.setCreatedBy(SecurityUtil.getUserId());
|
||||
sysMsgService.saveMsg(msg, users,true);
|
||||
return Result.success();
|
||||
return Result.success("已提交发送");
|
||||
} catch (Exception e) {
|
||||
return Result.error();
|
||||
}
|
||||
}
|
||||
|
||||
@At("/resend/?")
|
||||
@POST
|
||||
@Ok("json")
|
||||
@SaCheckPermission("sys.manager.msg.add")
|
||||
@ApiOperation("重新发送失败的站内消息")
|
||||
public Result resend(String id) {
|
||||
try {
|
||||
if (sysMsgService.resend(id)) {
|
||||
return Result.success("已提交重新发送");
|
||||
}
|
||||
return Result.error("仅可重新发送失败的消息");
|
||||
} catch (Exception e) {
|
||||
log.error("提交消息重发失败,消息ID:{}", id, e);
|
||||
return Result.error("提交重新发送失败");
|
||||
}
|
||||
}
|
||||
|
||||
@At
|
||||
@Ok("json:{locked:'password|salt',ignoreNull:false}")
|
||||
@SaCheckLogin
|
||||
|
||||
@@ -16,6 +16,10 @@ public interface SysMsgService extends BaseService<Sys_msg> {
|
||||
*/
|
||||
Sys_msg saveMsg(Sys_msg sysMsg, String[] users, boolean isExternal);
|
||||
|
||||
String getSendStatus(String id);
|
||||
|
||||
boolean resend(String id);
|
||||
|
||||
/**
|
||||
* 删除消息及消息用户表数据
|
||||
*
|
||||
|
||||
@@ -6,6 +6,7 @@ import cn.hutool.http.HtmlUtil;
|
||||
import com.budwk.app.base.constant.RedisConstant;
|
||||
import com.budwk.app.base.service.impl.BaseServiceImpl;
|
||||
import com.budwk.app.base.sms.SmsService;
|
||||
import com.budwk.app.base.sms.model.MsgPlatformResponse;
|
||||
import com.budwk.app.base.sms.model.MsgPlatformWechatRequest;
|
||||
import com.budwk.app.base.utils.ManyAddOrRenewUtil;
|
||||
import com.budwk.app.sys.models.Sys_msg;
|
||||
@@ -15,6 +16,7 @@ import com.budwk.app.sys.services.SysMsgUserService;
|
||||
import com.budwk.app.sys.services.SysUserService;
|
||||
import com.budwk.app.sys.views.View_user;
|
||||
import com.budwk.app.web.commons.auth.utils.SecurityUtil;
|
||||
import com.budwk.app.web.commons.base.Globals;
|
||||
import org.nutz.aop.interceptor.async.Async;
|
||||
import org.nutz.aop.interceptor.ioc.TransAop;
|
||||
import org.nutz.dao.Cnd;
|
||||
@@ -36,11 +38,15 @@ import org.nutz.lang.random.R;
|
||||
import org.nutz.lang.util.NutMap;
|
||||
import org.nutz.log.Log;
|
||||
import org.nutz.log.Logs;
|
||||
import org.nutz.trans.Atom;
|
||||
import org.nutz.trans.Trans;
|
||||
import redis.clients.jedis.*;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
@IocBean(args = {"refer:dao"})
|
||||
public class SysMsgServiceImpl extends BaseServiceImpl<Sys_msg> implements SysMsgService {
|
||||
@@ -68,11 +74,27 @@ public class SysMsgServiceImpl extends BaseServiceImpl<Sys_msg> implements SysMs
|
||||
|
||||
private static NutMap typeMap = NutMap.NEW().addv("system", "系统消息").addv("user", "用户消息");
|
||||
|
||||
@Override
|
||||
@Aop(TransAop.READ_COMMITTED)
|
||||
public Sys_msg saveMsg(Sys_msg sysMsg, String[] users, boolean isExternal) {
|
||||
this.insert(sysMsg);
|
||||
private static final String SEND_KEY_PREFIX = RedisConstant.PLATFORM_REDIS_PREFIX + "sys:msg:send:";
|
||||
private static final long SEND_LEASE_MILLIS = 300_000L;
|
||||
private static final String CLAIM_SEND = """
|
||||
local status = redis.call('hget', KEYS[1], 'status')
|
||||
local deadline = tonumber(redis.call('hget', KEYS[1], 'deadline') or '0')
|
||||
if ARGV[1] == 'initial' then
|
||||
if status then return 0 end
|
||||
elseif status ~= 'failed' and (status ~= 'sending' or deadline > tonumber(ARGV[2])) then
|
||||
return 0
|
||||
end
|
||||
redis.call('hset', KEYS[1], 'status', 'sending', 'deadline', ARGV[3], 'attempt', ARGV[4])
|
||||
return 1
|
||||
""";
|
||||
private static final String UPDATE_SEND = """
|
||||
if redis.call('hget', KEYS[1], 'attempt') ~= ARGV[1] then return 0 end
|
||||
redis.call('hset', KEYS[1], ARGV[2], ARGV[3])
|
||||
return 1
|
||||
""";
|
||||
|
||||
@Override
|
||||
public Sys_msg saveMsg(Sys_msg sysMsg, String[] users, boolean isExternal) {
|
||||
Cnd cnd = Cnd.NEW();
|
||||
cnd.groupBy("loginname");
|
||||
FieldFilter fieldFilter = FieldFilter.create(View_user.class, "loginname|username|unitId|unitName|unionId|unionName");
|
||||
@@ -84,7 +106,6 @@ public class SysMsgServiceImpl extends BaseServiceImpl<Sys_msg> implements SysMs
|
||||
for (View_user viewUser : viewUsers) {
|
||||
Sys_msg_user sysMsgUser = new Sys_msg_user();
|
||||
sysMsgUser.setId(R.UU32());
|
||||
sysMsgUser.setMsgId(sysMsg.getId());
|
||||
sysMsgUser.setStatus(0);
|
||||
sysMsgUser.setLoginname(viewUser.getLoginname());
|
||||
sysMsgUser.setUserName(viewUser.getUsername());
|
||||
@@ -94,7 +115,16 @@ public class SysMsgServiceImpl extends BaseServiceImpl<Sys_msg> implements SysMs
|
||||
sysMsgUser.setUnionName(viewUser.getUnionName());
|
||||
list.add(sysMsgUser);
|
||||
}
|
||||
Trans.exec(Connection.TRANSACTION_READ_COMMITTED, (Atom) () -> {
|
||||
this.insert(sysMsg);
|
||||
for (Sys_msg_user msgUser : list) {
|
||||
msgUser.setMsgId(sysMsg.getId());
|
||||
}
|
||||
if (!list.isEmpty()) {
|
||||
dao().fastInsert(list);
|
||||
}
|
||||
});
|
||||
startSend(sysMsg, list, "initial");
|
||||
sysMsgUserService.clearCache();
|
||||
|
||||
List<String> loginNames = viewUsers.stream().map(View_user::getLoginname).distinct().toList();
|
||||
@@ -105,27 +135,117 @@ public class SysMsgServiceImpl extends BaseServiceImpl<Sys_msg> implements SysMs
|
||||
}
|
||||
});
|
||||
|
||||
//发送学校平台消息
|
||||
ThreadUtil.execute(() -> {
|
||||
for (String loginName : loginNames) {
|
||||
smsService.sendSmsByAccount(loginName,sysMsg.getNote());
|
||||
if (!(Strings.isNotBlank(conf.get("custom.msg.platform.app-id"))
|
||||
&& conf.getBoolean("msg.platform.IntelligenceMode", false))) {
|
||||
smsService.sendWechatTextByAccountOrMobile(loginName,sysMsg.getNote());
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
return sysMsg;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSendStatus(String id) {
|
||||
List<String> fields = redisService.hmget(SEND_KEY_PREFIX + id, "status", "deadline");
|
||||
String status = fields.get(0);
|
||||
if ("sending".equals(status) && Long.parseLong(fields.get(1)) <= System.currentTimeMillis()) {
|
||||
return "failed";
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean resend(String id) {
|
||||
Sys_msg msg = fetch(id);
|
||||
if (msg == null || Boolean.TRUE.equals(msg.getDelFlag()) || !"show".equals(msg.getSendType())) {
|
||||
return false;
|
||||
}
|
||||
List<Sys_msg_user> recipients = sysMsgUserService.query(Cnd.where(Sys_msg_user::getMsgId, "=", id));
|
||||
return startSend(msg, recipients, "retry");
|
||||
}
|
||||
|
||||
private boolean startSend(Sys_msg msg, List<Sys_msg_user> recipients, String action) {
|
||||
String key = SEND_KEY_PREFIX + msg.getId();
|
||||
String attempt = R.UU32();
|
||||
long now = System.currentTimeMillis();
|
||||
Number claimed = (Number) redisService.eval(CLAIM_SEND, 1, key, action,
|
||||
Long.toString(now), Long.toString(now + SEND_LEASE_MILLIS), attempt);
|
||||
if (claimed.intValue() == 0) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
ThreadUtil.execute(() -> sendExternally(msg, recipients, key, attempt));
|
||||
} catch (RuntimeException e) {
|
||||
updateSend(key, attempt, "status", "failed");
|
||||
log.error("无法提交消息发送任务,消息ID:" + msg.getId(), e);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void sendExternally(Sys_msg msg, List<Sys_msg_user> recipients, String key, String attempt) {
|
||||
boolean sent = false;
|
||||
try {
|
||||
boolean zjnu = Strings.isNotBlank(conf.get("custom.msg.platform.app-id"));
|
||||
if (!conf.getBoolean("msg.platform.enabled", false)) {
|
||||
log.warn("消息未外发,msg.platform.enabled 未启用,消息ID:" + msg.getId());
|
||||
return;
|
||||
}
|
||||
if (!Globals.MyConfig.getBoolean("AppSms", false)) {
|
||||
log.warn("消息未外发,系统参数 AppSms 未启用,消息ID:" + msg.getId());
|
||||
return;
|
||||
}
|
||||
if (!zjnu && !Globals.sso) {
|
||||
log.warn("消息未外发,普通短信分支要求 cas.enable 启用,消息ID:" + msg.getId());
|
||||
return;
|
||||
}
|
||||
boolean intelligent = zjnu && conf.getBoolean("msg.platform.IntelligenceMode", false);
|
||||
sent = !recipients.isEmpty();
|
||||
for (Sys_msg_user recipient : recipients) {
|
||||
String loginname = recipient.getLoginname();
|
||||
sent &= sendChannel(key, attempt, recipient.getId(), intelligent ? "intelligent" : "sms",
|
||||
() -> smsService.sendSmsByAccount(loginname, msg.getNote()));
|
||||
if (!intelligent) {
|
||||
sent &= sendChannel(key, attempt, recipient.getId(), "wechat",
|
||||
() -> smsService.sendWechatTextByAccountOrMobile(loginname, msg.getNote()));
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
sent = false;
|
||||
log.error("消息发送任务失败,消息ID:" + msg.getId(), e);
|
||||
} finally {
|
||||
updateSend(key, attempt, "status", sent ? "sent" : "failed");
|
||||
}
|
||||
}
|
||||
|
||||
private boolean sendChannel(String key, String attempt, String recipientId, String channel,
|
||||
Supplier<MsgPlatformResponse> send) {
|
||||
if (!updateSend(key, attempt, "deadline", Long.toString(System.currentTimeMillis() + SEND_LEASE_MILLIS))) {
|
||||
return false;
|
||||
}
|
||||
String field = channel + ":" + recipientId;
|
||||
if ("sent".equals(redisService.hget(key, field))) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
MsgPlatformResponse result = send.get();
|
||||
Integer httpStatus = result == null ? null : result.getHttpStatus();
|
||||
if (httpStatus != null && httpStatus >= 200 && httpStatus < 300
|
||||
&& Integer.valueOf(0).equals(result.getCode()) && !Boolean.FALSE.equals(result.getResult())) {
|
||||
return updateSend(key, attempt, field, "sent");
|
||||
}
|
||||
log.warn("消息发送失败,渠道:" + channel + ",接收记录ID:" + recipientId
|
||||
+ ",返回结果:" + (result == null ? "无响应" : result.getMsg()));
|
||||
} catch (RuntimeException e) {
|
||||
log.error("消息发送异常,渠道:" + channel + ",接收记录ID:" + recipientId, e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean updateSend(String key, String attempt, String field, String value) {
|
||||
return ((Number) redisService.eval(UPDATE_SEND, 1, key, attempt, field, value)).intValue() == 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Aop(TransAop.READ_COMMITTED)
|
||||
public void deleteMsg(String id) {
|
||||
this.delete(id);
|
||||
List<Sys_msg_user> msgUsers = sysMsgUserService.query(Cnd.where(Sys_msg_user::getMsgId, "=", id));
|
||||
sysMsgUserService.clear(Cnd.where("msgId", "=", id));
|
||||
redisService.del(SEND_KEY_PREFIX + id);
|
||||
sysMsgUserService.clearCache();
|
||||
for (Sys_msg_user msgUser : msgUsers) {
|
||||
getMsg(msgUser.getLoginname());
|
||||
|
||||
@@ -58,25 +58,27 @@ custom:
|
||||
token-enabled: false
|
||||
grant_type: password
|
||||
scope: read
|
||||
username: 3848A3C738EFBB2C2E76E0D59B419DACA16A80F3AB0354CD
|
||||
password: 3848A3C738EFBB2C2E76E0D59B419DACA16A80F3AB0354CD
|
||||
token-url: https://bd.whcp.zjnu.edu.cn/sjjkfwpt/api/bd-api/oauth/token
|
||||
username: ''
|
||||
password: ''
|
||||
token-url: https://localhost:3000/sjjkfwpt/api/bd-api/oauth/token
|
||||
urls:
|
||||
teacher: http://localhost:3000/do/api/call/lxyxt_jzgjbxx
|
||||
unit: http://localhost:3000/do/api/call/lxyxt_dwxx
|
||||
msg:
|
||||
platform:
|
||||
enabled: false
|
||||
IntelligenceMode: false
|
||||
base-url: https://msg.zjnu.cug.edu.cn
|
||||
tp-name: nwszl.cug.edu.cn
|
||||
default-send-user-id: 790036
|
||||
default-send-user-name: 周斐霏
|
||||
default-send-unit-id: 421
|
||||
default-send-unit-name: 工会
|
||||
enabled: true
|
||||
IntelligenceMode: true
|
||||
app-id: 'test'
|
||||
app-password: 'test'
|
||||
base-url: http://127.0.0.1:3001
|
||||
tp-name: nwszl.zjnu.edu.cn
|
||||
default-send-user-id: ''
|
||||
default-send-user-name: ''
|
||||
default-send-unit-id: ''
|
||||
default-send-unit-name: ''
|
||||
default-send-user-sign: ''
|
||||
default-template-id: 1978744168869937153
|
||||
raw-secret-key: Z21kbDlwYWJ4c2Vtbnk4NjlxeQ==
|
||||
default-template-id: ''
|
||||
raw-secret-key: ''
|
||||
encrypted-secret-key: ''
|
||||
connect-timeout: 5000
|
||||
read-timeout: 10000
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
framework:
|
||||
server:
|
||||
port: 8080
|
||||
host: 0.0.0.0
|
||||
nutz:
|
||||
application:
|
||||
name: zhgh_zjnu
|
||||
tomcat:
|
||||
contextPath: ""
|
||||
staticPathLocal: ''
|
||||
redis:
|
||||
host: 127.0.0.1
|
||||
port: 6379
|
||||
database: 4
|
||||
mode: normal
|
||||
password: dd3s@Redis#2026
|
||||
jdbc:
|
||||
url: jdbc:mysql://127.0.0.1:3306/zhgh_zjnu_v4?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
|
||||
username: root
|
||||
password: dd3s@#2022
|
||||
beetl:
|
||||
RESOURCE:
|
||||
rootLocal: ''
|
||||
|
||||
sdk:
|
||||
wxwork:
|
||||
enable: true
|
||||
corpId: 'ww5386df99fd3b6b0f'
|
||||
corpSecret: 'HpSptE9wKZRq_c_kemAPJc0AfXkNSevpfYCJd1TTgrI'
|
||||
agentId: ''
|
||||
redirectUri: /platform/qywechat/getCode
|
||||
wx:
|
||||
enable: false
|
||||
appID: 'MOCK_ZJNU_WX_APP_ID'
|
||||
appSecret: 'MOCK_ZJNU_WX_APP_SECRET'
|
||||
redirectUri: /platform/wx/oauth2/callback
|
||||
cas:
|
||||
enable: true
|
||||
server-url-prefix: https://authserver.zjnu.edu.cn/authserver
|
||||
server-login-url: https://authserver.zjnu.edu.cn/authserver/login
|
||||
qi-wx-server-login-url: https://authserver.zjnu.edu.cn/authserver/login
|
||||
client-host-url: https://zhgh.zjnu.edu.cn
|
||||
client-call-back-url: /platform/sso/login
|
||||
validation-type: cas
|
||||
minio:
|
||||
accessKey: minioadmin
|
||||
secretKey: Minio@2026Admin
|
||||
endPoint: http://localhost:9000
|
||||
bucket: zjnu
|
||||
|
||||
custom:
|
||||
spdb:
|
||||
bab7:
|
||||
url: http://localhost:8888/supplierOpenApi/pointOrder/queryOrderInfo
|
||||
sm4cbc:
|
||||
keyHex: 00112233445566778899aabbccddeeff
|
||||
ivHex: 0102030405060708090a0b0c0d0e0f10
|
||||
data-center:
|
||||
token-enabled: false
|
||||
grant_type: password
|
||||
scope: read
|
||||
username: 3848A3C738EFBB2C2E76E0D59B419DACA16A80F3AB0354CD
|
||||
password: 3848A3C738EFBB2C2E76E0D59B419DACA16A80F3AB0354CD
|
||||
token-url: https://bd.whcp.zjnu.edu.cn/sjjkfwpt/api/bd-api/oauth/token
|
||||
urls:
|
||||
teacher: http://mdm.zjnu.edu.cn/do/api/call/lxyxt_jzgjbxx
|
||||
unit: http://mdm.zjnu.edu.cn/do/api/call/lxyxt_dwxx
|
||||
msg:
|
||||
platform:
|
||||
enabled: true
|
||||
IntelligenceMode: true
|
||||
app-id: 'MSG45363193'
|
||||
app-password: 'OGQxNzVmOTJkZjM5NzJhZDg1MDNiZGM0MDQ5ZTJlNDY'
|
||||
base-url: http://xxt.zjnu.edu.cn
|
||||
tp-name: ''
|
||||
default-send-user-id: ''
|
||||
default-send-user-name: ''
|
||||
default-send-unit-id: ''
|
||||
default-send-unit-name: ''
|
||||
default-send-user-sign: ''
|
||||
default-template-id: ''
|
||||
raw-secret-key: ''
|
||||
encrypted-secret-key: ''
|
||||
connect-timeout: 5000
|
||||
read-timeout: 10000
|
||||
invoice:
|
||||
tencent:
|
||||
# 发票 OCR 使用腾讯云 SecretId/SecretKey;为空时会回退读取 secret-file 指向的 csv。
|
||||
secret-id: AKID1473y253saFsMelgS4TjnfLofMrAHDyX
|
||||
secret-key: TlrlTzIRNjtIj296riPuISbmqplnhQDy
|
||||
secret-file: C:/Users/Administrator/Desktop
|
||||
@@ -195,6 +195,8 @@ msg:
|
||||
IntelligenceMode: '${custom.msg.platform.IntelligenceMode}'
|
||||
# 浙江师范大学通讯平台基础地址,默认对接正式地址
|
||||
base-url: '${custom.msg.platform.base-url}'
|
||||
app-id: '${custom.msg.platform.app-id}'
|
||||
app-password: '${custom.msg.platform.app-password}'
|
||||
# 授权系统名称,对应文档中的 tp_name
|
||||
tp-name: '${custom.msg.platform.tp-name}'
|
||||
# 便捷发送方法默认发送人工号,controller 只传接收人和内容时会读取这里
|
||||
|
||||
@@ -29,7 +29,7 @@ const SYS_MENU_RECOMMEND_SETTING_COMPONENT = {
|
||||
<el-table-column type="index"></el-table-column>
|
||||
<el-table-column label="名称" prop="name"></el-table-column>
|
||||
<el-table-column label="图标" prop="icon">
|
||||
<template scope="{row}">
|
||||
<template slot-scope="{row}">
|
||||
<svg-icon :name="row.icon" v-if="platform==='PC'"></svg-icon>
|
||||
<img v-else :src="row.icon" alt="" style="width: 30px;height: 30px">
|
||||
</template>
|
||||
|
||||
@@ -61,14 +61,19 @@ layout("/layouts/platform.html"){
|
||||
<el-table-column header-align="center" label="发送人" prop="createdAt" sortable>
|
||||
<template slot-scope="scope">{{scope.row.username}}</template>
|
||||
</el-table-column>
|
||||
<el-table-column align="center" header-align="center" label="消息状态" prop="delFlag" sortable>
|
||||
<el-table-column align="center" header-align="center" label="消息状态">
|
||||
<template slot-scope="scope">
|
||||
<el-tag size="mini" type="error" v-if="scope.row.delFlag">已删除</el-tag>
|
||||
<el-tag size="mini" type="success" v-if="!scope.row.delFlag">已发送</el-tag>
|
||||
<el-tag size="mini" type="danger" v-if="scope.row.delFlag">已删除</el-tag>
|
||||
<el-tag size="mini" type="warning" v-else-if="scope.row.sendStatus === 'sending'">发送中</el-tag>
|
||||
<el-tag size="mini" type="danger" v-else-if="scope.row.sendStatus === 'failed'">发送失败</el-tag>
|
||||
<el-tag size="mini" type="success" v-else-if="scope.row.sendStatus === 'sent'">已发送</el-tag>
|
||||
<el-tag size="mini" type="info" v-else>状态未知</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="120">
|
||||
<el-table-column label="操作" width="250">
|
||||
<template slot-scope="scope">
|
||||
<el-button v-if="!scope.row.delFlag && scope.row.sendStatus === 'failed' && $auth.hasPermission('sys.manager.msg.add')"
|
||||
size="mini" type="primary" :loading="!!resending[scope.row.id]" @click="resend(scope.row)">重新发送</el-button>
|
||||
<el-button size="mini" type="danger" @click="deleteDo(scope.row.id, scope.row.title)">删除</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
@@ -114,7 +119,10 @@ layout("/layouts/platform.html"){
|
||||
unionList: [],
|
||||
unitList: [],
|
||||
noteVisible: false,
|
||||
nodeData: {}
|
||||
nodeData: {},
|
||||
sendStatusTimer: null,
|
||||
pageRequestId: 0,
|
||||
resending: {}
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
@@ -134,13 +142,37 @@ layout("/layouts/platform.html"){
|
||||
this.pageData()
|
||||
},
|
||||
async pageData() {
|
||||
clearTimeout(this.sendStatusTimer)
|
||||
const requestId = ++this.pageRequestId
|
||||
try {
|
||||
const resp = await this.$axios.post("/platform/sys/msg/data", this.pageForm)
|
||||
if (requestId !== this.pageRequestId) return
|
||||
if (resp.code === 0) {
|
||||
this.tableData = resp.data.list
|
||||
this.pageForm.totalCount = resp.data.totalCount
|
||||
} else {
|
||||
this.$message.warning(resp.msg)
|
||||
}
|
||||
} finally {
|
||||
if (requestId === this.pageRequestId && this.tableData.some(row => row.sendStatus === "sending")) {
|
||||
this.sendStatusTimer = setTimeout(() => this.pageData(), 2000)
|
||||
}
|
||||
}
|
||||
},
|
||||
async resend(row) {
|
||||
if (this.resending[row.id]) return
|
||||
this.$set(this.resending, row.id, true)
|
||||
try {
|
||||
const resp = await this.$axios.post("/platform/sys/msg/resend/" + row.id)
|
||||
if (resp.code === 0) {
|
||||
this.$message.success(resp.msg)
|
||||
} else {
|
||||
this.$message.warning(resp.msg)
|
||||
}
|
||||
await this.pageData()
|
||||
} finally {
|
||||
this.$delete(this.resending, row.id)
|
||||
}
|
||||
},
|
||||
openAdd() {
|
||||
this.$refs.guava.edit()
|
||||
@@ -173,6 +205,10 @@ layout("/layouts/platform.html"){
|
||||
this.unitList = await this.$businessTool.listUnit()
|
||||
this.unionList = await this.$businessTool.listUnion()
|
||||
this.pageData()
|
||||
},
|
||||
beforeDestroy() {
|
||||
clearTimeout(this.sendStatusTimer)
|
||||
this.pageRequestId++
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
'use strict';
|
||||
|
||||
const http = require('node:http');
|
||||
|
||||
const host = '127.0.0.1';
|
||||
const port = 3001;
|
||||
const tokenPath = '/msg/getThirdAPIToken';
|
||||
const sendPath = '/message/sendMessageApi';
|
||||
const maxBodySize = 1024 * 1024;
|
||||
|
||||
function sendJson(response, status, body) {
|
||||
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
|
||||
response.end(JSON.stringify(body));
|
||||
}
|
||||
|
||||
function logRequest(method, path, params) {
|
||||
for (const field of ['token', 'appPassword']) {
|
||||
if (Object.hasOwn(params, field)) {
|
||||
params[field] = '[已脱敏]';
|
||||
}
|
||||
}
|
||||
|
||||
console.log(JSON.stringify({
|
||||
请求接口: path,
|
||||
请求方式: method,
|
||||
请求参数: params
|
||||
}, null, 2));
|
||||
}
|
||||
|
||||
async function handleRequest(request, response) {
|
||||
const { pathname, searchParams } = new URL(request.url, 'http://127.0.0.1');
|
||||
if (pathname === tokenPath && request.method === 'GET') {
|
||||
logRequest(request.method, pathname, Object.fromEntries(searchParams));
|
||||
sendJson(response, 200, {
|
||||
rspCode: 0,
|
||||
rspMsg: 'success',
|
||||
resultData: { token: 'mock-zjnu-msg-token' }
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname !== sendPath || request.method !== 'POST') {
|
||||
sendJson(response, 404, { rspCode: 404, rspMsg: '接口不存在' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (request.headers['content-type']?.split(';')[0].trim() !== 'application/x-www-form-urlencoded') {
|
||||
sendJson(response, 415, { rspCode: 415, rspMsg: '请求体必须为 URL 编码表单' });
|
||||
return;
|
||||
}
|
||||
|
||||
const chunks = [];
|
||||
let bodySize = 0;
|
||||
try {
|
||||
for await (const chunk of request) {
|
||||
bodySize += chunk.length;
|
||||
if (bodySize <= maxBodySize) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
sendJson(response, 400, { rspCode: 400, rspMsg: '无法读取请求体' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (bodySize > maxBodySize) {
|
||||
sendJson(response, 413, { rspCode: 413, rspMsg: '请求体超过 1 MB' });
|
||||
return;
|
||||
}
|
||||
|
||||
const form = new URLSearchParams(Buffer.concat(chunks).toString('utf8'));
|
||||
let receivers;
|
||||
try {
|
||||
receivers = JSON.parse(form.get('receivers'));
|
||||
} catch {
|
||||
logRequest(request.method, pathname, Object.fromEntries(form));
|
||||
sendJson(response, 400, { rspCode: 400, rspMsg: 'receivers 必须为 JSON 数组' });
|
||||
return;
|
||||
}
|
||||
|
||||
logRequest(request.method, pathname, {
|
||||
...Object.fromEntries(form),
|
||||
...(form.has('receivers') ? { receivers } : {})
|
||||
});
|
||||
|
||||
const requiredFields = ['token', 'msgContent', 'sendChannel', 'sendMode'];
|
||||
if (requiredFields.some(field => !form.get(field)?.trim())
|
||||
|| !Array.isArray(receivers) || receivers.length === 0) {
|
||||
sendJson(response, 400, { rspCode: 400, rspMsg: '缺少发送参数或接收人' });
|
||||
return;
|
||||
}
|
||||
|
||||
sendJson(response, 200, { rspCode: 0, rspMsg: 'success' });
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
http.createServer(handleRequest).listen(port, host, () => {
|
||||
console.log('模拟浙师大消息平台 http://' + host + ':' + port);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { handleRequest };
|
||||
Reference in New Issue
Block a user