功能:消息中心通道配置后台化
This commit is contained in:
@@ -3,8 +3,13 @@ package com.xiaowang.messagehub;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
/**
|
||||
* MessageHub应用启动类
|
||||
* MessageHub application entry.
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
@@ -13,7 +18,32 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
public class MessageHubApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
configureNacosRuntimePaths();
|
||||
SpringApplication.run(MessageHubApplication.class, args);
|
||||
}
|
||||
|
||||
private static void configureNacosRuntimePaths() {
|
||||
configurePathIfAbsent("JM.LOG.PATH", resolveRuntimePath("logs", true));
|
||||
configurePathIfAbsent("JM.SNAPSHOT.PATH", resolveRuntimePath("nacos-snapshot", false));
|
||||
}
|
||||
|
||||
private static String resolveRuntimePath(String child, boolean includeNacosDir) {
|
||||
Path path = Paths.get(System.getProperty("user.dir"), child);
|
||||
try {
|
||||
Files.createDirectories(path);
|
||||
if (includeNacosDir) {
|
||||
Files.createDirectories(path.resolve("nacos"));
|
||||
}
|
||||
} catch (IOException exception) {
|
||||
throw new IllegalStateException("Failed to prepare runtime directory: " + path, exception);
|
||||
}
|
||||
return path.toAbsolutePath().toString();
|
||||
}
|
||||
|
||||
private static void configurePathIfAbsent(String key, String value) {
|
||||
String currentValue = System.getProperty(key);
|
||||
if (currentValue == null || currentValue.trim().isEmpty()) {
|
||||
System.setProperty(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
package com.xiaowang.messagehub.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 邮件配置类
|
||||
* 用于存储和管理邮件相关的配置信息
|
||||
* 使用@ConfigurationProperties注解将配置文件中以"email"为前缀的属性自动绑定到该类的字段上
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "email")
|
||||
public class EmailConfig {
|
||||
|
||||
private String platform = "gmail"; // 默认邮件平台为gmail
|
||||
|
||||
private GmailConfig gmail; // Gmail邮件配置对象
|
||||
|
||||
private QQMailConfig qqmail; // QQ邮件配置对象
|
||||
|
||||
/**
|
||||
* Gmail邮件配置内部类
|
||||
* 包含Gmail邮件服务所需的所有配置参数
|
||||
*/
|
||||
@Data
|
||||
public static class GmailConfig {
|
||||
private String host = "smtp.gmail.com"; // Gmail SMTP服务器地址
|
||||
private Integer port = 587; // Gmail SMTP服务器端口
|
||||
private String username; // Gmail用户名
|
||||
private String password; // Gmail密码
|
||||
private Boolean auth = true; // 是否需要认证
|
||||
private Boolean starttls = true; // 是否启用STARTTLS
|
||||
private Boolean ssl = false; // 是否启用SSL
|
||||
private String from; // 发件人地址
|
||||
}
|
||||
|
||||
/**
|
||||
* QQ邮件配置内部类
|
||||
* 包含QQ邮件服务所需的所有配置参数
|
||||
*/
|
||||
@Data
|
||||
public static class QQMailConfig {
|
||||
private String host = "smtp.qq.com"; // QQ SMTP服务器地址
|
||||
private Integer port = 587; // QQ SMTP服务器端口
|
||||
private String username; // QQ邮箱用户名
|
||||
private String password; // QQ邮箱密码
|
||||
private Boolean auth = true; // 是否需要认证
|
||||
private Boolean starttls = true; // 是否启用STARTTLS
|
||||
private Boolean ssl = false; // 是否启用SSL
|
||||
private String from; // 发件人地址
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.xiaowang.messagehub.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "messagehub.channel")
|
||||
public class MessageChannelProperties {
|
||||
|
||||
private Security security = new Security();
|
||||
|
||||
private Mock mock = new Mock();
|
||||
|
||||
@Data
|
||||
public static class Security {
|
||||
private String encryptionKey = "MessageHub-Change-Me-2026";
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Mock {
|
||||
private boolean autoBootstrap = true;
|
||||
private List<String> profiles = new ArrayList<>(List.of("dev", "local", "test"));
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package com.xiaowang.messagehub.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "sms")
|
||||
public class SmsConfig {
|
||||
|
||||
private String platform = "spug";
|
||||
|
||||
private SpugConfig spug;
|
||||
|
||||
@Data
|
||||
public static class SpugConfig {
|
||||
private String baseUrl = "https://push.spug.cc";
|
||||
private String apiKey;
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.xiaowang.messagehub.controller;
|
||||
|
||||
import com.xiaowang.messagehub.dto.common.ApiResponse;
|
||||
import org.springframework.jdbc.BadSqlGrammarException;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
import javax.validation.ConstraintViolationException;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ApiResponse<Void> handleMethodArgumentNotValid(MethodArgumentNotValidException exception) {
|
||||
String message = exception.getBindingResult().getFieldErrors().stream()
|
||||
.map(error -> error.getDefaultMessage() == null ? error.getField() + "不合法" : error.getDefaultMessage())
|
||||
.collect(Collectors.joining(";"));
|
||||
return ApiResponse.error(message);
|
||||
}
|
||||
|
||||
@ExceptionHandler(BindException.class)
|
||||
public ApiResponse<Void> handleBindException(BindException exception) {
|
||||
String message = exception.getBindingResult().getFieldErrors().stream()
|
||||
.map(error -> error.getDefaultMessage() == null ? error.getField() + "不合法" : error.getDefaultMessage())
|
||||
.collect(Collectors.joining(";"));
|
||||
return ApiResponse.error(message);
|
||||
}
|
||||
|
||||
@ExceptionHandler(ConstraintViolationException.class)
|
||||
public ApiResponse<Void> handleConstraintViolation(ConstraintViolationException exception) {
|
||||
return ApiResponse.error(exception.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||
public ApiResponse<Void> handleNotReadable(HttpMessageNotReadableException exception) {
|
||||
return ApiResponse.error("请求体格式不正确");
|
||||
}
|
||||
|
||||
@ExceptionHandler(IllegalArgumentException.class)
|
||||
public ApiResponse<Void> handleIllegalArgument(IllegalArgumentException exception) {
|
||||
return ApiResponse.error(exception.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(BadSqlGrammarException.class)
|
||||
public ApiResponse<Void> handleBadSqlGrammar(BadSqlGrammarException exception) {
|
||||
String message = exception.getMessage();
|
||||
if (message != null && message.contains("message_channel_config") && message.contains("doesn't exist")) {
|
||||
return ApiResponse.error("缺少消息通道配置表,请先执行 2026-03-23_message_channel_management_patch.sql");
|
||||
}
|
||||
return ApiResponse.error("数据库语句执行失败,请检查 MessageHub 初始化 SQL");
|
||||
}
|
||||
|
||||
@ExceptionHandler(RuntimeException.class)
|
||||
public ApiResponse<Void> handleRuntime(RuntimeException exception) {
|
||||
return ApiResponse.error(exception.getMessage());
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.xiaowang.messagehub.controller;
|
||||
|
||||
import com.xiaowang.messagehub.dto.admin.ChannelConfigSaveRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.ChannelConfigTestRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.ChannelConfigView;
|
||||
import com.xiaowang.messagehub.dto.admin.ChannelStatusUpdateRequest;
|
||||
import com.xiaowang.messagehub.dto.common.ApiResponse;
|
||||
import com.xiaowang.messagehub.service.channel.MessageChannelService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.util.List;
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@RequestMapping("/admin/api/channels")
|
||||
public class MessageChannelAdminController {
|
||||
|
||||
private final MessageChannelService messageChannelService;
|
||||
|
||||
public MessageChannelAdminController(MessageChannelService messageChannelService) {
|
||||
this.messageChannelService = messageChannelService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<List<ChannelConfigView>> listChannels() {
|
||||
return ApiResponse.success(messageChannelService.listChannels());
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ApiResponse<ChannelConfigView> getChannel(@PathVariable Long id) {
|
||||
return ApiResponse.success(messageChannelService.getChannel(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ApiResponse<ChannelConfigView> createChannel(@Valid @RequestBody ChannelConfigSaveRequest request) {
|
||||
return ApiResponse.success("创建成功", messageChannelService.createChannel(request));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ApiResponse<ChannelConfigView> updateChannel(@PathVariable Long id,
|
||||
@Valid @RequestBody ChannelConfigSaveRequest request) {
|
||||
return ApiResponse.success("更新成功", messageChannelService.updateChannel(id, request));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/status")
|
||||
public ApiResponse<ChannelConfigView> updateStatus(@PathVariable Long id,
|
||||
@Valid @RequestBody ChannelStatusUpdateRequest request) {
|
||||
return ApiResponse.success("状态更新成功", messageChannelService.updateChannelStatus(id, request.getEnabled()));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/health-check")
|
||||
public ApiResponse<ChannelConfigView> runHealthCheck(@PathVariable Long id) {
|
||||
return ApiResponse.success("检测完成", messageChannelService.runHealthCheck(id));
|
||||
}
|
||||
|
||||
@PostMapping("/test-send")
|
||||
public ApiResponse<String> testSend(@Valid @RequestBody ChannelConfigTestRequest request) {
|
||||
return ApiResponse.success(messageChannelService.sendTest(request));
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.xiaowang.messagehub.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
@Controller
|
||||
public class MessageHubAdminPageController {
|
||||
|
||||
@GetMapping({"/messagehub-admin", "/messagehub-admin/"})
|
||||
public String index() {
|
||||
return "redirect:/messagehub-admin/index.html";
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class ChannelConfigSaveRequest {
|
||||
|
||||
@NotBlank(message = "通道类型不能为空")
|
||||
private String channelType;
|
||||
|
||||
@NotBlank(message = "提供方不能为空")
|
||||
private String providerCode;
|
||||
|
||||
@NotBlank(message = "通道名称不能为空")
|
||||
private String channelName;
|
||||
|
||||
@NotNull(message = "启用状态不能为空")
|
||||
private Boolean enabled = Boolean.TRUE;
|
||||
|
||||
@NotNull(message = "默认通道标记不能为空")
|
||||
private Boolean isDefault = Boolean.FALSE;
|
||||
|
||||
private Map<String, Object> config = new LinkedHashMap<>();
|
||||
|
||||
private Map<String, String> secretConfig = new LinkedHashMap<>();
|
||||
|
||||
private String remark;
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class ChannelConfigTestRequest {
|
||||
|
||||
@NotNull(message = "通道ID不能为空")
|
||||
private Long channelId;
|
||||
|
||||
@NotBlank(message = "接收目标不能为空")
|
||||
private String receiver;
|
||||
|
||||
private String subject;
|
||||
|
||||
private String content;
|
||||
|
||||
private String templateCode;
|
||||
|
||||
private Map<String, Object> templateParams = new LinkedHashMap<>();
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class ChannelConfigView {
|
||||
|
||||
private Long id;
|
||||
|
||||
private String channelType;
|
||||
|
||||
private String providerCode;
|
||||
|
||||
private String providerName;
|
||||
|
||||
private String channelName;
|
||||
|
||||
private Map<String, Object> config;
|
||||
|
||||
private Map<String, String> secretConfigMask;
|
||||
|
||||
private boolean enabled;
|
||||
|
||||
private boolean isDefault;
|
||||
|
||||
private String healthStatus;
|
||||
|
||||
private String healthMessage;
|
||||
|
||||
private LocalDateTime lastHealthCheckTime;
|
||||
|
||||
private String remark;
|
||||
|
||||
private LocalDateTime createTime;
|
||||
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
@Data
|
||||
public class ChannelStatusUpdateRequest {
|
||||
|
||||
@NotNull(message = "启用状态不能为空")
|
||||
private Boolean enabled;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.xiaowang.messagehub.dto.common;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class ApiResponse<T> {
|
||||
|
||||
private int code;
|
||||
|
||||
private String message;
|
||||
|
||||
private T data;
|
||||
|
||||
public static <T> ApiResponse<T> success(T data) {
|
||||
ApiResponse<T> response = new ApiResponse<>();
|
||||
response.setCode(0);
|
||||
response.setMessage("success");
|
||||
response.setData(data);
|
||||
return response;
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> success(String message, T data) {
|
||||
ApiResponse<T> response = success(data);
|
||||
response.setMessage(message);
|
||||
return response;
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> error(String message) {
|
||||
ApiResponse<T> response = new ApiResponse<>();
|
||||
response.setCode(1);
|
||||
response.setMessage(message);
|
||||
return response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.xiaowang.messagehub.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("message_channel_config")
|
||||
public class MessageChannelConfigDO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("channel_type")
|
||||
private String channelType;
|
||||
|
||||
@TableField("provider_code")
|
||||
private String providerCode;
|
||||
|
||||
@TableField("channel_name")
|
||||
private String channelName;
|
||||
|
||||
@TableField("config_json")
|
||||
private String configJson;
|
||||
|
||||
@TableField("secret_json")
|
||||
private String secretJson;
|
||||
|
||||
@TableField("enabled")
|
||||
private Integer enabled;
|
||||
|
||||
@TableField("is_default")
|
||||
private Integer isDefault;
|
||||
|
||||
@TableField("health_status")
|
||||
private String healthStatus;
|
||||
|
||||
@TableField("health_message")
|
||||
private String healthMessage;
|
||||
|
||||
@TableField("last_health_check_time")
|
||||
private LocalDateTime lastHealthCheckTime;
|
||||
|
||||
@TableField("remark")
|
||||
private String remark;
|
||||
|
||||
@TableLogic
|
||||
@TableField("deleted")
|
||||
private Integer deleted;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.xiaowang.messagehub.enums;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum ChannelHealthStatusEnum {
|
||||
|
||||
UNKNOWN("UNKNOWN", "待检测"),
|
||||
HEALTHY("HEALTHY", "正常"),
|
||||
UNHEALTHY("UNHEALTHY", "异常");
|
||||
|
||||
private final String code;
|
||||
|
||||
private final String label;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.xiaowang.messagehub.enums;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum ChannelProviderCodeEnum {
|
||||
|
||||
SPUG("SPUG", ChannelTypeEnum.SMS.getCode(), "Spug短信"),
|
||||
MOCK_SMS("MOCK_SMS", ChannelTypeEnum.SMS.getCode(), "开发Mock短信"),
|
||||
GMAIL("GMAIL", ChannelTypeEnum.EMAIL.getCode(), "Gmail SMTP"),
|
||||
QQMAIL("QQMAIL", ChannelTypeEnum.EMAIL.getCode(), "QQ邮箱 SMTP"),
|
||||
MOCK_EMAIL("MOCK_EMAIL", ChannelTypeEnum.EMAIL.getCode(), "开发Mock邮件");
|
||||
|
||||
private final String code;
|
||||
|
||||
private final String channelType;
|
||||
|
||||
private final String label;
|
||||
|
||||
public static ChannelProviderCodeEnum fromCode(String code) {
|
||||
for (ChannelProviderCodeEnum value : values()) {
|
||||
if (value.code.equalsIgnoreCase(code)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("不支持的通道提供方: " + code);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.xiaowang.messagehub.enums;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum ChannelTypeEnum {
|
||||
|
||||
SMS("SMS", "短信"),
|
||||
EMAIL("EMAIL", "邮件");
|
||||
|
||||
private final String code;
|
||||
|
||||
private final String label;
|
||||
|
||||
public static ChannelTypeEnum fromCode(String code) {
|
||||
for (ChannelTypeEnum value : values()) {
|
||||
if (value.code.equalsIgnoreCase(code)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("不支持的通道类型: " + code);
|
||||
}
|
||||
}
|
||||
+29
-40
@@ -1,6 +1,7 @@
|
||||
package com.xiaowang.messagehub.listener;
|
||||
|
||||
import com.xiaowang.messagehub.health.ConnectionHealthChecker;
|
||||
import com.xiaowang.messagehub.service.channel.MessageChannelService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -8,79 +9,67 @@ import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 应用启动监听器
|
||||
* 该类实现了Spring的ApplicationListener接口,用于在应用启动完成后执行特定的初始化操作
|
||||
* 主要功能是在服务启动完成后,检查各个关键组件的连接状态
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Component // 将此类标记为Spring组件,使其成为Spring容器中的一个Bean
|
||||
@Component
|
||||
public class ApplicationStartupListener implements ApplicationListener<ApplicationReadyEvent> {
|
||||
|
||||
// 使用SLF4J日志记录器,用于记录应用运行时的日志信息
|
||||
private static final Logger logger = LoggerFactory.getLogger(ApplicationStartupListener.class);
|
||||
|
||||
// 自动注入连接健康检查器,用于检查各个组件的连接状态
|
||||
@Autowired
|
||||
private ConnectionHealthChecker connectionHealthChecker;
|
||||
|
||||
/**
|
||||
* 重写ApplicationListener接口的onApplicationEvent方法
|
||||
* 当Spring Boot应用完全启动并准备就绪时,会触发ApplicationReadyEvent事件
|
||||
* 此方法会在事件触发后被调用,执行服务启动后的初始化检查
|
||||
*
|
||||
* @param event 应用准备就绪事件,包含应用启动完成的信息
|
||||
*/
|
||||
@Autowired
|
||||
private MessageChannelService messageChannelService;
|
||||
|
||||
@Override
|
||||
public void onApplicationEvent(ApplicationReadyEvent event) {
|
||||
// 打印服务启动完成的分隔线信息
|
||||
logger.info("========================================");
|
||||
logger.info("MessageHub服务启动完成,开始检查各组件连接状态...");
|
||||
logger.info("MessageHub 服务启动完成,开始检查关键依赖...");
|
||||
logger.info("========================================");
|
||||
|
||||
// 初始化连接状态标志,默认为true,表示所有连接检查都成功
|
||||
boolean allSuccess = true;
|
||||
|
||||
// 检查MySQL连接
|
||||
logger.info("");
|
||||
logger.info("【1/3】检查MySQL连接...");
|
||||
logger.info("[1/3] 检查 MySQL 连接...");
|
||||
if (connectionHealthChecker.checkMySQL()) {
|
||||
logger.info("✓ MySQL连接检查通过");
|
||||
logger.info("MySQL 连接检查通过");
|
||||
} else {
|
||||
logger.error("✗ MySQL连接检查失败");
|
||||
allSuccess = false; // 如果MySQL连接失败,设置标志为false
|
||||
logger.error("MySQL 连接检查失败");
|
||||
allSuccess = false;
|
||||
}
|
||||
|
||||
// 检查RabbitMQ连接
|
||||
logger.info("");
|
||||
logger.info("【2/3】检查RabbitMQ连接...");
|
||||
logger.info("[2/3] 检查 RabbitMQ 连接...");
|
||||
if (connectionHealthChecker.checkRabbitMQ()) {
|
||||
logger.info("✓ RabbitMQ连接检查通过");
|
||||
logger.info("RabbitMQ 连接检查通过");
|
||||
} else {
|
||||
logger.error("✗ RabbitMQ连接检查失败");
|
||||
allSuccess = false; // 如果RabbitMQ连接失败,设置标志为false
|
||||
logger.error("RabbitMQ 连接检查失败");
|
||||
allSuccess = false;
|
||||
}
|
||||
|
||||
// 检查Nacos连接
|
||||
logger.info("");
|
||||
logger.info("【3/3】检查Nacos连接...");
|
||||
logger.info("[3/3] 检查 Nacos 连接...");
|
||||
if (connectionHealthChecker.checkNacos()) {
|
||||
logger.info("✓ Nacos连接检查通过");
|
||||
logger.info("Nacos 连接检查通过");
|
||||
} else {
|
||||
logger.error("✗ Nacos连接检查失败");
|
||||
allSuccess = false; // 如果Nacos连接失败,设置标志为false
|
||||
logger.error("Nacos 连接检查失败");
|
||||
allSuccess = false;
|
||||
}
|
||||
|
||||
try {
|
||||
messageChannelService.bootstrapMockChannelsIfNecessary();
|
||||
messageChannelService.runStartupHealthChecks();
|
||||
logger.info("消息通道初始化与健康检查完成");
|
||||
} catch (Exception exception) {
|
||||
logger.warn("消息通道初始化或健康检查失败: {}", exception.getMessage());
|
||||
}
|
||||
|
||||
// 输出最终检查结果
|
||||
logger.info("");
|
||||
logger.info("========================================");
|
||||
if (allSuccess) {
|
||||
logger.info("所有组件连接检查完成,状态:全部成功");
|
||||
logger.info("MessageHub服务已就绪,可以正常使用");
|
||||
logger.info("基础依赖连接检查完成,状态:全部成功");
|
||||
logger.info("MessageHub 服务已就绪");
|
||||
} else {
|
||||
logger.error("部分组件连接检查失败,请检查日志并确认配置");
|
||||
logger.error("部分基础依赖连接检查失败,请检查日志与配置");
|
||||
}
|
||||
logger.info("========================================");
|
||||
}
|
||||
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.xiaowang.messagehub.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.messagehub.entity.MessageChannelConfigDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface MessageChannelConfigMapper extends BaseMapper<MessageChannelConfigDO> {
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.xiaowang.messagehub.model;
|
||||
|
||||
import com.xiaowang.messagehub.enums.ChannelHealthStatusEnum;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class ChannelHealthCheckResult {
|
||||
|
||||
private String status;
|
||||
|
||||
private String message;
|
||||
|
||||
public static ChannelHealthCheckResult healthy(String message) {
|
||||
return new ChannelHealthCheckResult(ChannelHealthStatusEnum.HEALTHY.getCode(), message);
|
||||
}
|
||||
|
||||
public static ChannelHealthCheckResult unhealthy(String message) {
|
||||
return new ChannelHealthCheckResult(ChannelHealthStatusEnum.UNHEALTHY.getCode(), message);
|
||||
}
|
||||
|
||||
public static ChannelHealthCheckResult unknown(String message) {
|
||||
return new ChannelHealthCheckResult(ChannelHealthStatusEnum.UNKNOWN.getCode(), message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.xiaowang.messagehub.model;
|
||||
|
||||
import com.xiaowang.messagehub.entity.MessageChannelConfigDO;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
public record ManagedChannelConfig(
|
||||
MessageChannelConfigDO entity,
|
||||
Map<String, Object> config,
|
||||
Map<String, Object> secretConfig
|
||||
) {
|
||||
|
||||
public ManagedChannelConfig {
|
||||
config = config == null ? Collections.emptyMap() : config;
|
||||
secretConfig = secretConfig == null ? Collections.emptyMap() : secretConfig;
|
||||
}
|
||||
|
||||
public String getStringConfig(String key) {
|
||||
Object value = config.get(key);
|
||||
return value == null ? null : String.valueOf(value).trim();
|
||||
}
|
||||
|
||||
public String getStringSecret(String key) {
|
||||
Object value = secretConfig.get(key);
|
||||
return value == null ? null : String.valueOf(value).trim();
|
||||
}
|
||||
|
||||
public boolean getBooleanConfig(String key, boolean defaultValue) {
|
||||
Object value = config.get(key);
|
||||
if (value == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (value instanceof Boolean booleanValue) {
|
||||
return booleanValue;
|
||||
}
|
||||
return Boolean.parseBoolean(String.valueOf(value));
|
||||
}
|
||||
|
||||
public int getIntConfig(String key, int defaultValue) {
|
||||
Object value = config.get(key);
|
||||
if (value == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (value instanceof Number number) {
|
||||
return number.intValue();
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(String.valueOf(value));
|
||||
} catch (NumberFormatException exception) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.xiaowang.messagehub.model;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class SmsDispatchRequest {
|
||||
|
||||
private String receiver;
|
||||
|
||||
private String templateCode;
|
||||
|
||||
private String templateExternalId;
|
||||
|
||||
private String content;
|
||||
|
||||
private Map<String, Object> templateParams = new LinkedHashMap<>();
|
||||
}
|
||||
@@ -1,41 +1,21 @@
|
||||
package com.xiaowang.messagehub.service;
|
||||
|
||||
import com.xiaowang.messagehub.config.EmailConfig;
|
||||
import com.xiaowang.messagehub.service.channel.MessageChannelService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class EmailSendService {
|
||||
|
||||
@Autowired
|
||||
private EmailConfig emailConfig;
|
||||
private final MessageChannelService messageChannelService;
|
||||
|
||||
@Autowired
|
||||
private List<EmailSender> emailSenders;
|
||||
public EmailSendService(MessageChannelService messageChannelService) {
|
||||
this.messageChannelService = messageChannelService;
|
||||
}
|
||||
|
||||
public void sendEmail(String to, String subject, String content) {
|
||||
String platform = emailConfig.getPlatform();
|
||||
|
||||
EmailSender sender = emailSenders.stream()
|
||||
.filter(s -> s.getPlatformName().equalsIgnoreCase(platform))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new RuntimeException("不支持的邮件平台: " + platform));
|
||||
|
||||
log.info("使用{}平台发送邮件,收件人: {}, 主题: {}", platform, to, subject);
|
||||
sender.sendEmail(to, subject, content);
|
||||
}
|
||||
|
||||
public void sendEmail(String to, String subject, String content, String platform) {
|
||||
EmailSender sender = emailSenders.stream()
|
||||
.filter(s -> s.getPlatformName().equalsIgnoreCase(platform))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new RuntimeException("不支持的邮件平台: " + platform));
|
||||
|
||||
log.info("使用{}平台发送邮件,收件人: {}, 主题: {}", platform, to, subject);
|
||||
sender.sendEmail(to, subject, content);
|
||||
log.info("准备通过数据库配置的邮件通道发送消息,收件人: {}, 主题: {}", to, subject);
|
||||
messageChannelService.sendEmail(to, subject, content);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.xiaowang.messagehub.service;
|
||||
|
||||
public interface EmailSender {
|
||||
|
||||
void sendEmail(String to, String subject, String content);
|
||||
|
||||
String getPlatformName();
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package com.xiaowang.messagehub.service.channel;
|
||||
|
||||
import com.xiaowang.messagehub.config.MessageChannelProperties;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
|
||||
@Service
|
||||
public class ChannelCryptoService {
|
||||
|
||||
private static final String PREFIX = "v1:";
|
||||
private static final int GCM_TAG_LENGTH = 128;
|
||||
private static final int GCM_IV_LENGTH = 12;
|
||||
|
||||
private final MessageChannelProperties properties;
|
||||
|
||||
private final SecureRandom secureRandom = new SecureRandom();
|
||||
|
||||
public ChannelCryptoService(MessageChannelProperties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
public String encrypt(String plaintext) {
|
||||
if (!StringUtils.hasText(plaintext)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
byte[] iv = new byte[GCM_IV_LENGTH];
|
||||
secureRandom.nextBytes(iv);
|
||||
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, buildSecretKey(), new GCMParameterSpec(GCM_TAG_LENGTH, iv));
|
||||
byte[] encrypted = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
byte[] payload = new byte[iv.length + encrypted.length];
|
||||
System.arraycopy(iv, 0, payload, 0, iv.length);
|
||||
System.arraycopy(encrypted, 0, payload, iv.length, encrypted.length);
|
||||
return PREFIX + Base64.getEncoder().encodeToString(payload);
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("通道敏感配置加密失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
public String decrypt(String ciphertext) {
|
||||
if (!StringUtils.hasText(ciphertext)) {
|
||||
return null;
|
||||
}
|
||||
if (!ciphertext.startsWith(PREFIX)) {
|
||||
return ciphertext;
|
||||
}
|
||||
try {
|
||||
byte[] payload = Base64.getDecoder().decode(ciphertext.substring(PREFIX.length()));
|
||||
byte[] iv = Arrays.copyOfRange(payload, 0, GCM_IV_LENGTH);
|
||||
byte[] encrypted = Arrays.copyOfRange(payload, GCM_IV_LENGTH, payload.length);
|
||||
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, buildSecretKey(), new GCMParameterSpec(GCM_TAG_LENGTH, iv));
|
||||
byte[] decrypted = cipher.doFinal(encrypted);
|
||||
return new String(decrypted, StandardCharsets.UTF_8);
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("通道敏感配置解密失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
public String mask(String value) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return "";
|
||||
}
|
||||
if (value.length() <= 4) {
|
||||
return "****";
|
||||
}
|
||||
return value.substring(0, 2) + "****" + value.substring(value.length() - 2);
|
||||
}
|
||||
|
||||
private SecretKeySpec buildSecretKey() throws Exception {
|
||||
String key = properties.getSecurity().getEncryptionKey();
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
byte[] hashed = digest.digest(key.getBytes(StandardCharsets.UTF_8));
|
||||
return new SecretKeySpec(Arrays.copyOf(hashed, 16), "AES");
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.xiaowang.messagehub.service.channel;
|
||||
|
||||
import com.xiaowang.messagehub.config.MessageChannelProperties;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class ChannelEnvironmentService {
|
||||
|
||||
private final Environment environment;
|
||||
|
||||
private final MessageChannelProperties properties;
|
||||
|
||||
public ChannelEnvironmentService(Environment environment, MessageChannelProperties properties) {
|
||||
this.environment = environment;
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
public boolean isDevelopmentEnvironment() {
|
||||
String[] activeProfiles = environment.getActiveProfiles();
|
||||
if (activeProfiles == null || activeProfiles.length == 0) {
|
||||
return true;
|
||||
}
|
||||
Set<String> devProfiles = properties.getMock().getProfiles().stream()
|
||||
.map(profile -> profile.toLowerCase(Locale.ROOT))
|
||||
.collect(Collectors.toSet());
|
||||
return Arrays.stream(activeProfiles)
|
||||
.map(profile -> profile.toLowerCase(Locale.ROOT))
|
||||
.anyMatch(devProfiles::contains);
|
||||
}
|
||||
}
|
||||
+473
@@ -0,0 +1,473 @@
|
||||
package com.xiaowang.messagehub.service.channel;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.messagehub.config.MessageChannelProperties;
|
||||
import com.xiaowang.messagehub.dto.admin.ChannelConfigSaveRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.ChannelConfigTestRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.ChannelConfigView;
|
||||
import com.xiaowang.messagehub.entity.MessageChannelConfigDO;
|
||||
import com.xiaowang.messagehub.entity.PushTemplateDO;
|
||||
import com.xiaowang.messagehub.enums.ChannelHealthStatusEnum;
|
||||
import com.xiaowang.messagehub.enums.ChannelProviderCodeEnum;
|
||||
import com.xiaowang.messagehub.enums.ChannelTypeEnum;
|
||||
import com.xiaowang.messagehub.mapper.MessageChannelConfigMapper;
|
||||
import com.xiaowang.messagehub.mapper.PushTemplateMapper;
|
||||
import com.xiaowang.messagehub.model.ChannelHealthCheckResult;
|
||||
import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
import com.xiaowang.messagehub.model.SmsDispatchRequest;
|
||||
import com.xiaowang.messagehub.service.channel.email.EmailChannelProvider;
|
||||
import com.xiaowang.messagehub.service.channel.sms.SmsChannelProvider;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class MessageChannelService {
|
||||
|
||||
private final MessageChannelConfigMapper channelConfigMapper;
|
||||
private final PushTemplateMapper pushTemplateMapper;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ChannelCryptoService cryptoService;
|
||||
private final ChannelEnvironmentService environmentService;
|
||||
private final MessageChannelProperties properties;
|
||||
private final List<EmailChannelProvider> emailProviders;
|
||||
private final List<SmsChannelProvider> smsProviders;
|
||||
|
||||
public MessageChannelService(MessageChannelConfigMapper channelConfigMapper,
|
||||
PushTemplateMapper pushTemplateMapper,
|
||||
ObjectMapper objectMapper,
|
||||
ChannelCryptoService cryptoService,
|
||||
ChannelEnvironmentService environmentService,
|
||||
MessageChannelProperties properties,
|
||||
List<EmailChannelProvider> emailProviders,
|
||||
List<SmsChannelProvider> smsProviders) {
|
||||
this.channelConfigMapper = channelConfigMapper;
|
||||
this.pushTemplateMapper = pushTemplateMapper;
|
||||
this.objectMapper = objectMapper;
|
||||
this.cryptoService = cryptoService;
|
||||
this.environmentService = environmentService;
|
||||
this.properties = properties;
|
||||
this.emailProviders = emailProviders;
|
||||
this.smsProviders = smsProviders;
|
||||
}
|
||||
|
||||
public List<ChannelConfigView> listChannels() {
|
||||
return listChannelEntities().stream().map(this::toView).toList();
|
||||
}
|
||||
|
||||
public ChannelConfigView getChannel(Long id) {
|
||||
return toView(requireChannel(id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ChannelConfigView createChannel(ChannelConfigSaveRequest request) {
|
||||
validateProvider(request.getChannelType(), request.getProviderCode());
|
||||
MessageChannelConfigDO entity = new MessageChannelConfigDO();
|
||||
applyRequest(entity, request, null);
|
||||
channelConfigMapper.insert(entity);
|
||||
if (Boolean.TRUE.equals(request.getEnabled())) {
|
||||
persistHealth(entity, checkHealth(buildManagedChannel(entity)));
|
||||
}
|
||||
return toView(requireChannel(entity.getId()));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ChannelConfigView updateChannel(Long id, ChannelConfigSaveRequest request) {
|
||||
MessageChannelConfigDO entity = requireChannel(id);
|
||||
validateProvider(request.getChannelType(), request.getProviderCode());
|
||||
applyRequest(entity, request, entity);
|
||||
channelConfigMapper.updateById(entity);
|
||||
if (Boolean.TRUE.equals(request.getEnabled())) {
|
||||
persistHealth(entity, checkHealth(buildManagedChannel(entity)));
|
||||
} else {
|
||||
markUnknown(entity, "Channel disabled");
|
||||
channelConfigMapper.updateById(entity);
|
||||
}
|
||||
return toView(requireChannel(id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ChannelConfigView updateChannelStatus(Long id, boolean enabled) {
|
||||
MessageChannelConfigDO entity = requireChannel(id);
|
||||
entity.setEnabled(enabled ? 1 : 0);
|
||||
if (!enabled) {
|
||||
entity.setIsDefault(0);
|
||||
markUnknown(entity, "Channel disabled");
|
||||
} else {
|
||||
if (!existsEnabledDefault(entity.getChannelType(), id)) {
|
||||
clearDefaultByChannelType(entity.getChannelType(), id);
|
||||
entity.setIsDefault(1);
|
||||
}
|
||||
persistHealth(entity, checkHealth(buildManagedChannel(entity)));
|
||||
}
|
||||
channelConfigMapper.updateById(entity);
|
||||
return toView(requireChannel(id));
|
||||
}
|
||||
|
||||
public ChannelConfigView runHealthCheck(Long id) {
|
||||
MessageChannelConfigDO entity = requireChannel(id);
|
||||
persistHealth(entity, checkHealth(buildManagedChannel(entity)));
|
||||
return toView(requireChannel(id));
|
||||
}
|
||||
|
||||
public void runStartupHealthChecks() {
|
||||
for (MessageChannelConfigDO entity : listEnabledChannelEntities()) {
|
||||
persistHealth(entity, checkHealth(buildManagedChannel(entity)));
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void bootstrapMockChannelsIfNecessary() {
|
||||
if (!properties.getMock().isAutoBootstrap() || !environmentService.isDevelopmentEnvironment()) {
|
||||
return;
|
||||
}
|
||||
ensureMockChannel(ChannelTypeEnum.SMS, ChannelProviderCodeEnum.MOCK_SMS, "Dev Mock SMS Channel");
|
||||
ensureMockChannel(ChannelTypeEnum.EMAIL, ChannelProviderCodeEnum.MOCK_EMAIL, "Dev Mock Email Channel");
|
||||
}
|
||||
|
||||
public String sendTest(ChannelConfigTestRequest request) {
|
||||
ManagedChannelConfig channelConfig = buildManagedChannel(requireChannel(request.getChannelId()));
|
||||
ChannelTypeEnum channelType = ChannelTypeEnum.fromCode(channelConfig.entity().getChannelType());
|
||||
if (channelType == ChannelTypeEnum.EMAIL) {
|
||||
String subject = StringUtils.hasText(request.getSubject()) ? request.getSubject() : "MessageHub Test Email";
|
||||
String content = StringUtils.hasText(request.getContent()) ? request.getContent() : "This is a test email from MessageHub.";
|
||||
resolveEmailProvider(channelConfig.entity().getProviderCode()).send(channelConfig, request.getReceiver(), subject, content);
|
||||
return "Email test message sent";
|
||||
}
|
||||
|
||||
SmsDispatchRequest smsDispatchRequest = new SmsDispatchRequest();
|
||||
smsDispatchRequest.setReceiver(request.getReceiver());
|
||||
smsDispatchRequest.setContent(request.getContent());
|
||||
smsDispatchRequest.setTemplateCode(request.getTemplateCode());
|
||||
smsDispatchRequest.setTemplateParams(request.getTemplateParams() == null
|
||||
? new LinkedHashMap<>()
|
||||
: new LinkedHashMap<>(request.getTemplateParams()));
|
||||
|
||||
if (ChannelProviderCodeEnum.SPUG.getCode().equalsIgnoreCase(channelConfig.entity().getProviderCode())) {
|
||||
if (!StringUtils.hasText(request.getTemplateCode())) {
|
||||
throw new IllegalArgumentException("Spug SMS test requires templateCode");
|
||||
}
|
||||
smsDispatchRequest.setTemplateExternalId(requireTemplateExternalId(request.getTemplateCode()));
|
||||
}
|
||||
|
||||
if (!StringUtils.hasText(smsDispatchRequest.getContent())) {
|
||||
smsDispatchRequest.setContent("This is a test SMS from MessageHub.");
|
||||
}
|
||||
resolveSmsProvider(channelConfig.entity().getProviderCode()).send(channelConfig, smsDispatchRequest);
|
||||
return "SMS test message sent";
|
||||
}
|
||||
|
||||
public void sendEmail(String to, String subject, String content) {
|
||||
ManagedChannelConfig channelConfig = selectActiveChannel(ChannelTypeEnum.EMAIL);
|
||||
resolveEmailProvider(channelConfig.entity().getProviderCode()).send(channelConfig, to, subject, content);
|
||||
}
|
||||
|
||||
public void sendSms(SmsDispatchRequest request) {
|
||||
ManagedChannelConfig channelConfig = selectActiveChannel(ChannelTypeEnum.SMS);
|
||||
if (ChannelProviderCodeEnum.SPUG.getCode().equalsIgnoreCase(channelConfig.entity().getProviderCode())
|
||||
&& !StringUtils.hasText(request.getTemplateExternalId())) {
|
||||
request.setTemplateExternalId(requireTemplateExternalId(request.getTemplateCode()));
|
||||
}
|
||||
resolveSmsProvider(channelConfig.entity().getProviderCode()).send(channelConfig, request);
|
||||
}
|
||||
|
||||
private ChannelHealthCheckResult checkHealth(ManagedChannelConfig channelConfig) {
|
||||
ChannelTypeEnum channelType = ChannelTypeEnum.fromCode(channelConfig.entity().getChannelType());
|
||||
if (channelType == ChannelTypeEnum.EMAIL) {
|
||||
return resolveEmailProvider(channelConfig.entity().getProviderCode()).checkHealth(channelConfig);
|
||||
}
|
||||
return resolveSmsProvider(channelConfig.entity().getProviderCode()).checkHealth(channelConfig);
|
||||
}
|
||||
|
||||
private void applyRequest(MessageChannelConfigDO target,
|
||||
ChannelConfigSaveRequest request,
|
||||
MessageChannelConfigDO existingEntity) {
|
||||
ChannelTypeEnum channelType = ChannelTypeEnum.fromCode(request.getChannelType());
|
||||
ChannelProviderCodeEnum provider = ChannelProviderCodeEnum.fromCode(request.getProviderCode());
|
||||
boolean enabled = Boolean.TRUE.equals(request.getEnabled());
|
||||
boolean isDefault = enabled && Boolean.TRUE.equals(request.getIsDefault());
|
||||
|
||||
Map<String, Object> mergedConfig = request.getConfig() == null
|
||||
? new LinkedHashMap<>()
|
||||
: new LinkedHashMap<>(request.getConfig());
|
||||
Map<String, Object> mergedSecretConfig = mergeSecretConfig(existingEntity, request.getSecretConfig());
|
||||
|
||||
ManagedChannelConfig managedChannelConfig = new ManagedChannelConfig(target, mergedConfig, mergedSecretConfig);
|
||||
if (channelType == ChannelTypeEnum.EMAIL) {
|
||||
resolveEmailProvider(provider.getCode()).validate(managedChannelConfig);
|
||||
} else {
|
||||
resolveSmsProvider(provider.getCode()).validate(managedChannelConfig);
|
||||
}
|
||||
|
||||
target.setChannelType(channelType.getCode());
|
||||
target.setProviderCode(provider.getCode());
|
||||
target.setChannelName(request.getChannelName().trim());
|
||||
target.setConfigJson(writeJson(mergedConfig));
|
||||
target.setSecretJson(writeSecretJson(mergedSecretConfig));
|
||||
target.setEnabled(enabled ? 1 : 0);
|
||||
target.setIsDefault(isDefault ? 1 : 0);
|
||||
target.setRemark(StringUtils.hasText(request.getRemark()) ? request.getRemark().trim() : null);
|
||||
if (target.getHealthStatus() == null) {
|
||||
target.setHealthStatus(ChannelHealthStatusEnum.UNKNOWN.getCode());
|
||||
}
|
||||
if (isDefault) {
|
||||
clearDefaultByChannelType(channelType.getCode(), existingEntity == null ? null : existingEntity.getId());
|
||||
} else if (enabled && !existsEnabledDefault(channelType.getCode(), existingEntity == null ? null : existingEntity.getId())) {
|
||||
clearDefaultByChannelType(channelType.getCode(), existingEntity == null ? null : existingEntity.getId());
|
||||
target.setIsDefault(1);
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureMockChannel(ChannelTypeEnum channelType, ChannelProviderCodeEnum providerCode, String channelName) {
|
||||
LambdaQueryWrapper<MessageChannelConfigDO> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(MessageChannelConfigDO::getChannelType, channelType.getCode())
|
||||
.eq(MessageChannelConfigDO::getProviderCode, providerCode.getCode());
|
||||
if (channelConfigMapper.selectCount(queryWrapper) > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
boolean noEnabledChannel = countEnabledChannels(channelType.getCode()) == 0;
|
||||
MessageChannelConfigDO entity = new MessageChannelConfigDO();
|
||||
entity.setChannelType(channelType.getCode());
|
||||
entity.setProviderCode(providerCode.getCode());
|
||||
entity.setChannelName(channelName);
|
||||
entity.setConfigJson(writeJson(Collections.singletonMap("environment", "dev")));
|
||||
entity.setSecretJson(null);
|
||||
entity.setEnabled(noEnabledChannel ? 1 : 0);
|
||||
entity.setIsDefault(noEnabledChannel ? 1 : 0);
|
||||
entity.setHealthStatus(ChannelHealthStatusEnum.UNKNOWN.getCode());
|
||||
entity.setHealthMessage("Pending");
|
||||
entity.setRemark("Auto-generated mock channel for development");
|
||||
channelConfigMapper.insert(entity);
|
||||
}
|
||||
|
||||
private MessageChannelConfigDO requireChannel(Long id) {
|
||||
MessageChannelConfigDO entity = channelConfigMapper.selectById(id);
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Channel not found: " + id);
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
private ManagedChannelConfig buildManagedChannel(MessageChannelConfigDO entity) {
|
||||
return new ManagedChannelConfig(entity, readJsonMap(entity.getConfigJson()), readSecretJson(entity.getSecretJson()));
|
||||
}
|
||||
|
||||
private ManagedChannelConfig selectActiveChannel(ChannelTypeEnum channelType) {
|
||||
List<MessageChannelConfigDO> enabledChannels = listEnabledChannelEntities(channelType.getCode());
|
||||
if (enabledChannels.isEmpty()) {
|
||||
throw new IllegalStateException(channelType.getCode() + " channel is not configured");
|
||||
}
|
||||
|
||||
MessageChannelConfigDO selected = null;
|
||||
for (MessageChannelConfigDO entity : enabledChannels) {
|
||||
if (!ChannelHealthStatusEnum.UNHEALTHY.getCode().equalsIgnoreCase(entity.getHealthStatus())) {
|
||||
selected = entity;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (selected == null) {
|
||||
selected = enabledChannels.get(0);
|
||||
}
|
||||
return buildManagedChannel(selected);
|
||||
}
|
||||
|
||||
private EmailChannelProvider resolveEmailProvider(String providerCode) {
|
||||
return emailProviders.stream()
|
||||
.filter(provider -> provider.supports(providerCode))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("Email provider not found: " + providerCode));
|
||||
}
|
||||
|
||||
private SmsChannelProvider resolveSmsProvider(String providerCode) {
|
||||
return smsProviders.stream()
|
||||
.filter(provider -> provider.supports(providerCode))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("SMS provider not found: " + providerCode));
|
||||
}
|
||||
|
||||
private void validateProvider(String channelType, String providerCode) {
|
||||
ChannelTypeEnum typeEnum = ChannelTypeEnum.fromCode(channelType);
|
||||
ChannelProviderCodeEnum providerCodeEnum = ChannelProviderCodeEnum.fromCode(providerCode);
|
||||
if (!providerCodeEnum.getChannelType().equalsIgnoreCase(typeEnum.getCode())) {
|
||||
throw new IllegalArgumentException("Provider and channelType do not match");
|
||||
}
|
||||
}
|
||||
|
||||
private void persistHealth(MessageChannelConfigDO entity, ChannelHealthCheckResult result) {
|
||||
entity.setHealthStatus(result.getStatus());
|
||||
entity.setHealthMessage(result.getMessage());
|
||||
entity.setLastHealthCheckTime(LocalDateTime.now());
|
||||
channelConfigMapper.updateById(entity);
|
||||
}
|
||||
|
||||
private void markUnknown(MessageChannelConfigDO entity, String message) {
|
||||
entity.setHealthStatus(ChannelHealthStatusEnum.UNKNOWN.getCode());
|
||||
entity.setHealthMessage(message);
|
||||
entity.setLastHealthCheckTime(LocalDateTime.now());
|
||||
}
|
||||
|
||||
private void clearDefaultByChannelType(String channelType, Long excludeId) {
|
||||
LambdaUpdateWrapper<MessageChannelConfigDO> updateWrapper = new LambdaUpdateWrapper<>();
|
||||
updateWrapper.eq(MessageChannelConfigDO::getChannelType, channelType)
|
||||
.eq(MessageChannelConfigDO::getIsDefault, 1)
|
||||
.set(MessageChannelConfigDO::getIsDefault, 0);
|
||||
if (excludeId != null) {
|
||||
updateWrapper.ne(MessageChannelConfigDO::getId, excludeId);
|
||||
}
|
||||
channelConfigMapper.update(null, updateWrapper);
|
||||
}
|
||||
|
||||
private boolean existsEnabledDefault(String channelType, Long excludeId) {
|
||||
LambdaQueryWrapper<MessageChannelConfigDO> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(MessageChannelConfigDO::getChannelType, channelType)
|
||||
.eq(MessageChannelConfigDO::getEnabled, 1)
|
||||
.eq(MessageChannelConfigDO::getIsDefault, 1);
|
||||
if (excludeId != null) {
|
||||
queryWrapper.ne(MessageChannelConfigDO::getId, excludeId);
|
||||
}
|
||||
return channelConfigMapper.selectCount(queryWrapper) > 0;
|
||||
}
|
||||
|
||||
private long countEnabledChannels(String channelType) {
|
||||
LambdaQueryWrapper<MessageChannelConfigDO> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(MessageChannelConfigDO::getChannelType, channelType)
|
||||
.eq(MessageChannelConfigDO::getEnabled, 1);
|
||||
return channelConfigMapper.selectCount(queryWrapper);
|
||||
}
|
||||
|
||||
private List<MessageChannelConfigDO> listEnabledChannelEntities() {
|
||||
LambdaQueryWrapper<MessageChannelConfigDO> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(MessageChannelConfigDO::getEnabled, 1)
|
||||
.orderByDesc(MessageChannelConfigDO::getIsDefault)
|
||||
.orderByAsc(MessageChannelConfigDO::getChannelType)
|
||||
.orderByDesc(MessageChannelConfigDO::getUpdateTime);
|
||||
return channelConfigMapper.selectList(queryWrapper);
|
||||
}
|
||||
|
||||
private List<MessageChannelConfigDO> listEnabledChannelEntities(String channelType) {
|
||||
LambdaQueryWrapper<MessageChannelConfigDO> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(MessageChannelConfigDO::getChannelType, channelType)
|
||||
.eq(MessageChannelConfigDO::getEnabled, 1)
|
||||
.orderByDesc(MessageChannelConfigDO::getIsDefault)
|
||||
.orderByDesc(MessageChannelConfigDO::getUpdateTime);
|
||||
return channelConfigMapper.selectList(queryWrapper);
|
||||
}
|
||||
|
||||
private List<MessageChannelConfigDO> listChannelEntities() {
|
||||
LambdaQueryWrapper<MessageChannelConfigDO> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.orderByAsc(MessageChannelConfigDO::getChannelType)
|
||||
.orderByDesc(MessageChannelConfigDO::getIsDefault)
|
||||
.orderByDesc(MessageChannelConfigDO::getEnabled)
|
||||
.orderByDesc(MessageChannelConfigDO::getUpdateTime);
|
||||
return channelConfigMapper.selectList(queryWrapper);
|
||||
}
|
||||
|
||||
private String requireTemplateExternalId(String templateCode) {
|
||||
PushTemplateDO template = pushTemplateMapper.selectByTemplateCode(templateCode);
|
||||
if (template == null || template.getIsEnable() == null || template.getIsEnable() != 1) {
|
||||
throw new IllegalArgumentException("Template is missing or disabled: " + templateCode);
|
||||
}
|
||||
if (!StringUtils.hasText(template.getExternalId())) {
|
||||
throw new IllegalArgumentException("Template externalId is empty: " + templateCode);
|
||||
}
|
||||
return template.getExternalId();
|
||||
}
|
||||
|
||||
private Map<String, Object> mergeSecretConfig(MessageChannelConfigDO existingEntity, Map<String, String> updates) {
|
||||
Map<String, Object> existing = existingEntity == null
|
||||
? new LinkedHashMap<>()
|
||||
: new LinkedHashMap<>(readSecretJson(existingEntity.getSecretJson()));
|
||||
if (updates == null || updates.isEmpty()) {
|
||||
return existing;
|
||||
}
|
||||
updates.forEach((key, value) -> {
|
||||
if (StringUtils.hasText(value)) {
|
||||
existing.put(key, value.trim());
|
||||
}
|
||||
});
|
||||
return existing;
|
||||
}
|
||||
|
||||
private String writeJson(Map<String, ?> value) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(value == null ? Collections.emptyMap() : value);
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("Failed to serialize channel config", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private String writeSecretJson(Map<String, ?> secretValue) {
|
||||
if (secretValue == null || secretValue.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return cryptoService.encrypt(writeJson(secretValue));
|
||||
}
|
||||
|
||||
private Map<String, Object> readJsonMap(String json) {
|
||||
if (!StringUtils.hasText(json)) {
|
||||
return new LinkedHashMap<>();
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(json, new TypeReference<>() {
|
||||
});
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("Failed to deserialize channel config", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> readSecretJson(String encryptedJson) {
|
||||
if (!StringUtils.hasText(encryptedJson)) {
|
||||
return new LinkedHashMap<>();
|
||||
}
|
||||
return readJsonMap(cryptoService.decrypt(encryptedJson));
|
||||
}
|
||||
|
||||
private ChannelConfigView toView(MessageChannelConfigDO entity) {
|
||||
ManagedChannelConfig managedChannelConfig = buildManagedChannel(entity);
|
||||
ChannelConfigView view = new ChannelConfigView();
|
||||
view.setId(entity.getId());
|
||||
view.setChannelType(entity.getChannelType());
|
||||
view.setProviderCode(entity.getProviderCode());
|
||||
view.setProviderName(providerLabel(entity.getProviderCode()));
|
||||
view.setChannelName(entity.getChannelName());
|
||||
view.setConfig(managedChannelConfig.config());
|
||||
view.setSecretConfigMask(maskSecrets(managedChannelConfig.secretConfig()));
|
||||
view.setEnabled(entity.getEnabled() != null && entity.getEnabled() == 1);
|
||||
view.setDefault(entity.getIsDefault() != null && entity.getIsDefault() == 1);
|
||||
view.setHealthStatus(entity.getHealthStatus());
|
||||
view.setHealthMessage(entity.getHealthMessage());
|
||||
view.setLastHealthCheckTime(entity.getLastHealthCheckTime());
|
||||
view.setRemark(entity.getRemark());
|
||||
view.setCreateTime(entity.getCreateTime());
|
||||
view.setUpdateTime(entity.getUpdateTime());
|
||||
return view;
|
||||
}
|
||||
|
||||
private Map<String, String> maskSecrets(Map<String, Object> secretConfig) {
|
||||
if (secretConfig == null || secretConfig.isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
Map<String, String> masked = new LinkedHashMap<>();
|
||||
secretConfig.forEach((key, value) -> masked.put(key, cryptoService.mask(String.valueOf(value))));
|
||||
return masked;
|
||||
}
|
||||
|
||||
private String providerLabel(String providerCode) {
|
||||
try {
|
||||
return ChannelProviderCodeEnum.fromCode(providerCode).getLabel();
|
||||
} catch (IllegalArgumentException exception) {
|
||||
return providerCode.toUpperCase(Locale.ROOT);
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.xiaowang.messagehub.service.channel.email;
|
||||
|
||||
import com.xiaowang.messagehub.model.ChannelHealthCheckResult;
|
||||
import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
|
||||
public interface EmailChannelProvider {
|
||||
|
||||
boolean supports(String providerCode);
|
||||
|
||||
void validate(ManagedChannelConfig channelConfig);
|
||||
|
||||
void send(ManagedChannelConfig channelConfig, String to, String subject, String content);
|
||||
|
||||
ChannelHealthCheckResult checkHealth(ManagedChannelConfig channelConfig);
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.xiaowang.messagehub.service.channel.email;
|
||||
|
||||
import com.xiaowang.messagehub.enums.ChannelProviderCodeEnum;
|
||||
import com.xiaowang.messagehub.model.ChannelHealthCheckResult;
|
||||
import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
import com.xiaowang.messagehub.service.channel.ChannelEnvironmentService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class MockEmailChannelProvider implements EmailChannelProvider {
|
||||
|
||||
private final ChannelEnvironmentService environmentService;
|
||||
|
||||
public MockEmailChannelProvider(ChannelEnvironmentService environmentService) {
|
||||
this.environmentService = environmentService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(String providerCode) {
|
||||
return ChannelProviderCodeEnum.MOCK_EMAIL.getCode().equalsIgnoreCase(providerCode);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(ManagedChannelConfig channelConfig) {
|
||||
if (!environmentService.isDevelopmentEnvironment()) {
|
||||
throw new IllegalArgumentException("Mock 邮件通道仅允许在开发环境使用");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(ManagedChannelConfig channelConfig, String to, String subject, String content) {
|
||||
validate(channelConfig);
|
||||
log.info("[MockEmail] to={}, subject={}, content={}", to, subject, content);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChannelHealthCheckResult checkHealth(ManagedChannelConfig channelConfig) {
|
||||
if (!environmentService.isDevelopmentEnvironment()) {
|
||||
return ChannelHealthCheckResult.unhealthy("当前环境不是开发环境,Mock 邮件通道不可用");
|
||||
}
|
||||
return ChannelHealthCheckResult.healthy("开发环境 Mock 邮件通道可用");
|
||||
}
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package com.xiaowang.messagehub.service.channel.email;
|
||||
|
||||
import com.xiaowang.messagehub.enums.ChannelProviderCodeEnum;
|
||||
import com.xiaowang.messagehub.model.ChannelHealthCheckResult;
|
||||
import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.mail.Session;
|
||||
import javax.mail.Transport;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import java.util.Properties;
|
||||
|
||||
@Service
|
||||
public class SmtpEmailChannelProvider implements EmailChannelProvider {
|
||||
|
||||
@Override
|
||||
public boolean supports(String providerCode) {
|
||||
return ChannelProviderCodeEnum.GMAIL.getCode().equalsIgnoreCase(providerCode)
|
||||
|| ChannelProviderCodeEnum.QQMAIL.getCode().equalsIgnoreCase(providerCode);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(ManagedChannelConfig channelConfig) {
|
||||
requireText(channelConfig.getStringConfig("host"), "SMTP 主机不能为空");
|
||||
if (channelConfig.getIntConfig("port", 0) <= 0) {
|
||||
throw new IllegalArgumentException("SMTP 端口不能为空");
|
||||
}
|
||||
requireText(channelConfig.getStringConfig("username"), "SMTP 用户名不能为空");
|
||||
requireText(channelConfig.getStringConfig("fromAddress"), "发件人地址不能为空");
|
||||
requireText(channelConfig.getStringSecret("password"), "SMTP 密码不能为空");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(ManagedChannelConfig channelConfig, String to, String subject, String content) {
|
||||
validate(channelConfig);
|
||||
requireText(to, "收件人不能为空");
|
||||
requireText(subject, "测试邮件主题不能为空");
|
||||
requireText(content, "测试邮件内容不能为空");
|
||||
|
||||
try {
|
||||
MimeMessage message = new MimeMessage(buildSession(channelConfig));
|
||||
message.setFrom(new InternetAddress(channelConfig.getStringConfig("fromAddress")));
|
||||
message.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to));
|
||||
message.setSubject(subject, "UTF-8");
|
||||
message.setText(content, "UTF-8");
|
||||
Transport.send(message);
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("邮件发送失败: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChannelHealthCheckResult checkHealth(ManagedChannelConfig channelConfig) {
|
||||
try {
|
||||
Session session = buildSession(channelConfig);
|
||||
Transport transport = session.getTransport("smtp");
|
||||
transport.connect(
|
||||
channelConfig.getStringConfig("host"),
|
||||
channelConfig.getIntConfig("port", 25),
|
||||
channelConfig.getStringConfig("username"),
|
||||
channelConfig.getStringSecret("password")
|
||||
);
|
||||
transport.close();
|
||||
return ChannelHealthCheckResult.healthy("SMTP 连接成功");
|
||||
} catch (Exception exception) {
|
||||
return ChannelHealthCheckResult.unhealthy("SMTP 连接失败: " + exception.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private Session buildSession(ManagedChannelConfig channelConfig) {
|
||||
Properties props = new Properties();
|
||||
props.put("mail.smtp.host", channelConfig.getStringConfig("host"));
|
||||
props.put("mail.smtp.port", channelConfig.getIntConfig("port", 25));
|
||||
props.put("mail.smtp.auth", channelConfig.getBooleanConfig("auth", true));
|
||||
props.put("mail.smtp.starttls.enable", channelConfig.getBooleanConfig("starttls", true));
|
||||
props.put("mail.smtp.ssl.enable", channelConfig.getBooleanConfig("ssl", false));
|
||||
props.put("mail.smtp.connectiontimeout", "5000");
|
||||
props.put("mail.smtp.timeout", "5000");
|
||||
props.put("mail.smtp.writetimeout", "5000");
|
||||
return Session.getInstance(props, new javax.mail.Authenticator() {
|
||||
@Override
|
||||
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
|
||||
return new javax.mail.PasswordAuthentication(
|
||||
channelConfig.getStringConfig("username"),
|
||||
channelConfig.getStringSecret("password")
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void requireText(String value, String message) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.xiaowang.messagehub.service.channel.sms;
|
||||
|
||||
import com.xiaowang.messagehub.enums.ChannelProviderCodeEnum;
|
||||
import com.xiaowang.messagehub.model.ChannelHealthCheckResult;
|
||||
import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
import com.xiaowang.messagehub.model.SmsDispatchRequest;
|
||||
import com.xiaowang.messagehub.service.channel.ChannelEnvironmentService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class MockSmsChannelProvider implements SmsChannelProvider {
|
||||
|
||||
private final ChannelEnvironmentService environmentService;
|
||||
|
||||
public MockSmsChannelProvider(ChannelEnvironmentService environmentService) {
|
||||
this.environmentService = environmentService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(String providerCode) {
|
||||
return ChannelProviderCodeEnum.MOCK_SMS.getCode().equalsIgnoreCase(providerCode);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(ManagedChannelConfig channelConfig) {
|
||||
if (!environmentService.isDevelopmentEnvironment()) {
|
||||
throw new IllegalArgumentException("Mock 短信通道仅允许在开发环境使用");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(ManagedChannelConfig channelConfig, SmsDispatchRequest request) {
|
||||
validate(channelConfig);
|
||||
log.info("[MockSms] receiver={}, templateCode={}, content={}, params={}",
|
||||
request.getReceiver(),
|
||||
request.getTemplateCode(),
|
||||
request.getContent(),
|
||||
request.getTemplateParams());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChannelHealthCheckResult checkHealth(ManagedChannelConfig channelConfig) {
|
||||
if (!environmentService.isDevelopmentEnvironment()) {
|
||||
return ChannelHealthCheckResult.unhealthy("当前环境不是开发环境,Mock 短信通道不可用");
|
||||
}
|
||||
return ChannelHealthCheckResult.healthy("开发环境 Mock 短信通道可用");
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.xiaowang.messagehub.service.channel.sms;
|
||||
|
||||
import com.xiaowang.messagehub.model.ChannelHealthCheckResult;
|
||||
import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
import com.xiaowang.messagehub.model.SmsDispatchRequest;
|
||||
|
||||
public interface SmsChannelProvider {
|
||||
|
||||
boolean supports(String providerCode);
|
||||
|
||||
void validate(ManagedChannelConfig channelConfig);
|
||||
|
||||
void send(ManagedChannelConfig channelConfig, SmsDispatchRequest request);
|
||||
|
||||
ChannelHealthCheckResult checkHealth(ManagedChannelConfig channelConfig);
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package com.xiaowang.messagehub.service.channel.sms;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.messagehub.enums.ChannelProviderCodeEnum;
|
||||
import com.xiaowang.messagehub.model.ChannelHealthCheckResult;
|
||||
import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
import com.xiaowang.messagehub.model.SmsDispatchRequest;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class SpugSmsChannelProvider implements SmsChannelProvider {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public SpugSmsChannelProvider(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(String providerCode) {
|
||||
return ChannelProviderCodeEnum.SPUG.getCode().equalsIgnoreCase(providerCode);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(ManagedChannelConfig channelConfig) {
|
||||
requireText(channelConfig.getStringConfig("baseUrl"), "Spug 基础地址不能为空");
|
||||
requireText(channelConfig.getStringSecret("apiKey"), "Spug API Key 不能为空");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(ManagedChannelConfig channelConfig, SmsDispatchRequest request) {
|
||||
validate(channelConfig);
|
||||
requireText(request.getReceiver(), "短信接收手机号不能为空");
|
||||
requireText(request.getTemplateExternalId(), "Spug 模板外部ID不能为空");
|
||||
|
||||
HttpURLConnection connection = null;
|
||||
try {
|
||||
String baseUrl = channelConfig.getStringConfig("baseUrl");
|
||||
String url = trimTrailingSlash(baseUrl) + "/sms/" + request.getTemplateExternalId();
|
||||
Map<String, Object> payload = new LinkedHashMap<>(request.getTemplateParams());
|
||||
payload.put("to", request.getReceiver());
|
||||
|
||||
connection = (HttpURLConnection) new URL(url).openConnection();
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setRequestProperty("Content-Type", "application/json");
|
||||
connection.setRequestProperty("X-API-Key", channelConfig.getStringSecret("apiKey"));
|
||||
connection.setDoOutput(true);
|
||||
connection.setConnectTimeout(5000);
|
||||
connection.setReadTimeout(10000);
|
||||
|
||||
try (OutputStream outputStream = connection.getOutputStream()) {
|
||||
outputStream.write(objectMapper.writeValueAsBytes(payload));
|
||||
}
|
||||
|
||||
int responseCode = connection.getResponseCode();
|
||||
if (responseCode != HttpURLConnection.HTTP_OK) {
|
||||
throw new IllegalStateException("Spug 请求失败,HTTP 状态码: " + responseCode);
|
||||
}
|
||||
|
||||
try (BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
while (reader.readLine() != null) {
|
||||
// Drain response stream to complete request lifecycle.
|
||||
}
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("Spug 短信发送失败: " + exception.getMessage(), exception);
|
||||
} finally {
|
||||
if (connection != null) {
|
||||
connection.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChannelHealthCheckResult checkHealth(ManagedChannelConfig channelConfig) {
|
||||
try {
|
||||
validate(channelConfig);
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL(channelConfig.getStringConfig("baseUrl"))
|
||||
.openConnection();
|
||||
connection.setRequestMethod("GET");
|
||||
connection.setRequestProperty("X-API-Key", channelConfig.getStringSecret("apiKey"));
|
||||
connection.setConnectTimeout(3000);
|
||||
connection.setReadTimeout(3000);
|
||||
int responseCode = connection.getResponseCode();
|
||||
connection.disconnect();
|
||||
if (responseCode >= 200 && responseCode < 500) {
|
||||
return ChannelHealthCheckResult.healthy("Spug 服务可达,HTTP 状态码: " + responseCode);
|
||||
}
|
||||
return ChannelHealthCheckResult.unhealthy("Spug 服务返回异常状态码: " + responseCode);
|
||||
} catch (Exception exception) {
|
||||
return ChannelHealthCheckResult.unhealthy("Spug 服务不可达: " + exception.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private String trimTrailingSlash(String value) {
|
||||
return value.endsWith("/") ? value.substring(0, value.length() - 1) : value;
|
||||
}
|
||||
|
||||
private void requireText(String value, String message) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
package com.xiaowang.messagehub.service.impl;
|
||||
|
||||
import com.xiaowang.messagehub.config.EmailConfig;
|
||||
import com.xiaowang.messagehub.service.EmailSender;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.mail.javamail.JavaMailSenderImpl;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
import javax.mail.Session;
|
||||
import javax.mail.Transport;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import java.util.Properties;
|
||||
|
||||
@Slf4j
|
||||
@Service("gmailSender")
|
||||
public class GmailSender implements EmailSender {
|
||||
|
||||
@Autowired
|
||||
private EmailConfig emailConfig;
|
||||
|
||||
private Session session;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
EmailConfig.GmailConfig config = emailConfig.getGmail();
|
||||
|
||||
Properties props = new Properties();
|
||||
props.put("mail.smtp.host", config.getHost());
|
||||
props.put("mail.smtp.port", config.getPort());
|
||||
props.put("mail.smtp.auth", config.getAuth());
|
||||
props.put("mail.smtp.starttls.enable", config.getStarttls());
|
||||
props.put("mail.smtp.ssl.enable", config.getSsl());
|
||||
props.put("mail.smtp.connectiontimeout", "5000");
|
||||
props.put("mail.smtp.timeout", "5000");
|
||||
props.put("mail.smtp.writetimeout", "5000");
|
||||
|
||||
session = Session.getInstance(props, new javax.mail.Authenticator() {
|
||||
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
|
||||
return new javax.mail.PasswordAuthentication(config.getUsername(), config.getPassword());
|
||||
}
|
||||
});
|
||||
|
||||
log.info("Gmail邮件发送器初始化完成,发件人: {}", config.getFrom());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendEmail(String to, String subject, String content) {
|
||||
try {
|
||||
MimeMessage message = new MimeMessage(session);
|
||||
message.setFrom(new InternetAddress(emailConfig.getGmail().getFrom()));
|
||||
message.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to));
|
||||
message.setSubject(subject, "UTF-8");
|
||||
message.setText(content, "UTF-8");
|
||||
|
||||
Transport.send(message);
|
||||
log.info("Gmail邮件发送成功,收件人: {}, 主题: {}", to, subject);
|
||||
} catch (Exception e) {
|
||||
log.error("Gmail邮件发送失败,收件人: {}, 主题: {}", to, subject, e);
|
||||
throw new RuntimeException("邮件发送失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPlatformName() {
|
||||
return "Gmail";
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void destroy() {
|
||||
log.info("Gmail邮件发送器已关闭");
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
package com.xiaowang.messagehub.service.impl;
|
||||
|
||||
import com.xiaowang.messagehub.config.EmailConfig;
|
||||
import com.xiaowang.messagehub.service.EmailSender;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
import javax.mail.Session;
|
||||
import javax.mail.Transport;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import java.util.Properties;
|
||||
|
||||
@Slf4j
|
||||
@Service("qqmailSender")
|
||||
public class QQMailSender implements EmailSender {
|
||||
|
||||
@Autowired
|
||||
private EmailConfig emailConfig;
|
||||
|
||||
private Session session;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
EmailConfig.QQMailConfig config = emailConfig.getQqmail();
|
||||
|
||||
Properties props = new Properties();
|
||||
props.put("mail.smtp.host", config.getHost());
|
||||
props.put("mail.smtp.port", config.getPort());
|
||||
props.put("mail.smtp.auth", config.getAuth());
|
||||
props.put("mail.smtp.starttls.enable", config.getStarttls());
|
||||
props.put("mail.smtp.ssl.enable", config.getSsl());
|
||||
props.put("mail.smtp.connectiontimeout", "5000");
|
||||
props.put("mail.smtp.timeout", "5000");
|
||||
props.put("mail.smtp.writetimeout", "5000");
|
||||
|
||||
session = Session.getInstance(props, new javax.mail.Authenticator() {
|
||||
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
|
||||
return new javax.mail.PasswordAuthentication(config.getUsername(), config.getPassword());
|
||||
}
|
||||
});
|
||||
|
||||
log.info("QQMail邮件发送器初始化完成,发件人: {}", config.getFrom());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendEmail(String to, String subject, String content) {
|
||||
try {
|
||||
MimeMessage message = new MimeMessage(session);
|
||||
message.setFrom(new InternetAddress(emailConfig.getQqmail().getFrom()));
|
||||
message.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to));
|
||||
message.setSubject(subject, "UTF-8");
|
||||
message.setText(content, "UTF-8");
|
||||
|
||||
Transport.send(message);
|
||||
log.info("QQMail邮件发送成功,收件人: {}, 主题: {}", to, subject);
|
||||
} catch (Exception e) {
|
||||
log.error("QQMail邮件发送失败,收件人: {}, 主题: {}", to, subject, e);
|
||||
throw new RuntimeException("邮件发送失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPlatformName() {
|
||||
return "QQMail";
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void destroy() {
|
||||
log.info("QQMail邮件发送器已关闭");
|
||||
}
|
||||
}
|
||||
+20
-104
@@ -2,130 +2,46 @@ package com.xiaowang.messagehub.service.impl;
|
||||
|
||||
import com.xiaowang.messagehub.dto.SmsMessageDTO;
|
||||
import com.xiaowang.messagehub.entity.PushTemplateDO;
|
||||
import com.xiaowang.messagehub.model.SmsDispatchRequest;
|
||||
import com.xiaowang.messagehub.service.SmsSendService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.messagehub.service.channel.MessageChannelService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 短信发送服务实现类
|
||||
* 实现了SmsSendService接口,提供短信发送功能
|
||||
*/
|
||||
@Service
|
||||
public class SmsSendServiceImpl implements SmsSendService {
|
||||
|
||||
// 注入短信服务基础URL配置
|
||||
@Value("${sms.spug.base-url}")
|
||||
private String spugBaseUrl;
|
||||
|
||||
@Value("${sms.spug.api-key}")
|
||||
// 注入短信服务API密钥配置
|
||||
private String spugApiKey;
|
||||
|
||||
private final MessageHandleService messageHandleService;
|
||||
// 消息处理服务,用于获取短信模板等信息
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SmsSendServiceImpl.class);
|
||||
// 日志记录器,用于记录服务运行日志
|
||||
/**
|
||||
* 构造函数,通过依赖注入方式初始化MessageHandleService
|
||||
* @param messageHandleService 消息处理服务
|
||||
*/
|
||||
public SmsSendServiceImpl(MessageHandleService messageHandleService) {
|
||||
|
||||
private final MessageHandleService messageHandleService;
|
||||
private final MessageChannelService messageChannelService;
|
||||
|
||||
public SmsSendServiceImpl(MessageHandleService messageHandleService,
|
||||
MessageChannelService messageChannelService) {
|
||||
this.messageHandleService = messageHandleService;
|
||||
this.messageChannelService = messageChannelService;
|
||||
}
|
||||
/**
|
||||
* 发送短信方法实现
|
||||
* @param smsMessage 短信消息DTO,包含模板代码、发送方式和模板参数等信息
|
||||
* @throws RuntimeException 当短信模板不存在或发送失败时抛出
|
||||
*/
|
||||
|
||||
@Override
|
||||
public void sendSms(SmsMessageDTO smsMessage) {
|
||||
try {
|
||||
// 根据模板代码获取短信模板
|
||||
PushTemplateDO templateByCode = messageHandleService.getTemplateByCode(smsMessage.getTemplateCode());
|
||||
if (templateByCode == null) {
|
||||
logger.error("短信模板不存在: {},消息发送失败", smsMessage.getTemplateCode());
|
||||
throw new RuntimeException("短信模板不存在: " + smsMessage.getTemplateCode());
|
||||
}
|
||||
// 根据发送方式调用不同的发送逻辑
|
||||
if ("SPUG".equals(smsMessage.getSendMethod())){
|
||||
String result = sendSmsBySpug(smsMessage,templateByCode);
|
||||
logger.info("短信发送结果: {}", result);
|
||||
}
|
||||
// TODO: 实现其他短信发送逻辑
|
||||
} catch (Exception e) {
|
||||
logger.error("短信发送失败: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("短信发送失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 通过SPUG平台发送短信
|
||||
* @param message 短信消息DTO
|
||||
* @return 发送结果字符串
|
||||
*/
|
||||
private String sendSmsBySpug(SmsMessageDTO message,PushTemplateDO templateByCode) {
|
||||
HttpURLConnection conn = null;
|
||||
BufferedReader br = null;
|
||||
try {
|
||||
// 构建请求URL
|
||||
String url = spugBaseUrl + "/sms/" + templateByCode.getExternalId();
|
||||
// 将模板参数转换为JSON字符串
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
Map<String, Object> templateParams = message.getTemplateParams();
|
||||
templateParams.put("to",message.getReceiver());
|
||||
String json = objectMapper.writeValueAsString(templateParams);
|
||||
|
||||
// 创建HTTP连接
|
||||
conn = (HttpURLConnection) new URL(url).openConnection();
|
||||
conn.setRequestMethod("POST");
|
||||
conn.setRequestProperty("Content-Type", "application/json");
|
||||
conn.setDoOutput(true);
|
||||
// 设置连接和读取超时时间
|
||||
conn.setConnectTimeout(5000);
|
||||
conn.setReadTimeout(10000);
|
||||
SmsDispatchRequest dispatchRequest = new SmsDispatchRequest();
|
||||
dispatchRequest.setReceiver(smsMessage.getReceiver());
|
||||
dispatchRequest.setTemplateCode(smsMessage.getTemplateCode());
|
||||
dispatchRequest.setTemplateExternalId(templateByCode.getExternalId());
|
||||
dispatchRequest.setTemplateParams(smsMessage.getTemplateParams());
|
||||
|
||||
// 发送请求
|
||||
try (OutputStream os = conn.getOutputStream()) {
|
||||
os.write(json.getBytes());
|
||||
}
|
||||
|
||||
// 获取响应状态码
|
||||
int responseCode = conn.getResponseCode();
|
||||
if (responseCode != HttpURLConnection.HTTP_OK) {
|
||||
logger.error("HTTP请求失败,状态码: {}", responseCode);
|
||||
throw new IOException("HTTP请求失败,状态码: " + responseCode);
|
||||
}
|
||||
// 读取响应内容
|
||||
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
|
||||
StringBuilder response = new StringBuilder();
|
||||
String line;
|
||||
while ((line = br.readLine()) != null) {
|
||||
response.append(line);
|
||||
}
|
||||
|
||||
return response.toString();
|
||||
} catch (Exception e) {
|
||||
logger.error("通过SPUG发送短信失败: {}", e.getMessage(), e);
|
||||
return "发送失败: " + e.getMessage();
|
||||
} finally {
|
||||
// 关闭资源
|
||||
if (br != null) {
|
||||
try {
|
||||
br.close();
|
||||
} catch (IOException e) {
|
||||
logger.error("关闭 BufferedReader 失败", e);
|
||||
}
|
||||
}
|
||||
if (conn != null) {
|
||||
conn.disconnect();
|
||||
}
|
||||
messageChannelService.sendSms(dispatchRequest);
|
||||
logger.info("短信发送成功,模板: {}, 手机号: {}", smsMessage.getTemplateCode(), smsMessage.getReceiver());
|
||||
} catch (Exception exception) {
|
||||
logger.error("短信发送失败: {}", exception.getMessage(), exception);
|
||||
throw new RuntimeException("短信发送失败: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
spring:
|
||||
application:
|
||||
name: MessageHub
|
||||
|
||||
messagehub:
|
||||
channel:
|
||||
security:
|
||||
encryption-key: ${MESSAGE_HUB_MASTER_KEY:MessageHub-Change-Me-2026}
|
||||
mock:
|
||||
auto-bootstrap: true
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
CREATE TABLE IF NOT EXISTS `message_channel_config` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT 'Primary key',
|
||||
`channel_type` VARCHAR(20) NOT NULL COMMENT 'SMS / EMAIL',
|
||||
`provider_code` VARCHAR(50) NOT NULL COMMENT 'SPUG / GMAIL / QQMAIL / MOCK_SMS / MOCK_EMAIL',
|
||||
`channel_name` VARCHAR(100) NOT NULL COMMENT 'Display name',
|
||||
`config_json` TEXT NULL COMMENT 'Public config JSON',
|
||||
`secret_json` TEXT NULL COMMENT 'Encrypted secret JSON',
|
||||
`enabled` TINYINT NOT NULL DEFAULT 1 COMMENT '1 enabled, 0 disabled',
|
||||
`is_default` TINYINT NOT NULL DEFAULT 0 COMMENT '1 default, 0 non-default',
|
||||
`health_status` VARCHAR(20) NOT NULL DEFAULT 'UNKNOWN' COMMENT 'UNKNOWN / HEALTHY / UNHEALTHY',
|
||||
`health_message` VARCHAR(255) NULL COMMENT 'Last health message',
|
||||
`last_health_check_time` DATETIME NULL COMMENT 'Last health check time',
|
||||
`remark` VARCHAR(255) NULL COMMENT 'Remark',
|
||||
`deleted` TINYINT NOT NULL DEFAULT 0 COMMENT 'Logical delete flag',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Create time',
|
||||
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Update time',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_message_channel_type_provider` (`channel_type`, `provider_code`),
|
||||
KEY `idx_message_channel_enabled_default` (`channel_type`, `enabled`, `is_default`),
|
||||
KEY `idx_message_channel_deleted` (`deleted`),
|
||||
KEY `idx_message_channel_name` (`channel_name`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Message channel management';
|
||||
@@ -0,0 +1,427 @@
|
||||
const PROVIDERS = {
|
||||
SMS: {
|
||||
SPUG: {
|
||||
label: "Spug短信",
|
||||
configFields: [
|
||||
{ key: "baseUrl", label: "基础地址", placeholder: "https://push.spug.cc", required: true }
|
||||
],
|
||||
secretFields: [
|
||||
{ key: "apiKey", label: "API Key", required: true }
|
||||
]
|
||||
},
|
||||
MOCK_SMS: {
|
||||
label: "开发Mock短信",
|
||||
configFields: [],
|
||||
secretFields: []
|
||||
}
|
||||
},
|
||||
EMAIL: {
|
||||
GMAIL: {
|
||||
label: "Gmail SMTP",
|
||||
configFields: [
|
||||
{ key: "host", label: "SMTP主机", placeholder: "smtp.gmail.com", required: true, defaultValue: "smtp.gmail.com" },
|
||||
{ key: "port", label: "SMTP端口", placeholder: "587", required: true, defaultValue: "587" },
|
||||
{ key: "username", label: "SMTP用户名", placeholder: "your-account@gmail.com", required: true },
|
||||
{ key: "fromAddress", label: "发件人地址", placeholder: "your-account@gmail.com", required: true },
|
||||
{ key: "auth", label: "启用认证", type: "checkbox", defaultValue: true },
|
||||
{ key: "starttls", label: "启用 STARTTLS", type: "checkbox", defaultValue: true },
|
||||
{ key: "ssl", label: "启用 SSL", type: "checkbox", defaultValue: false }
|
||||
],
|
||||
secretFields: [
|
||||
{ key: "password", label: "SMTP密码 / 授权码", required: true }
|
||||
]
|
||||
},
|
||||
QQMAIL: {
|
||||
label: "QQ邮箱 SMTP",
|
||||
configFields: [
|
||||
{ key: "host", label: "SMTP主机", placeholder: "smtp.qq.com", required: true, defaultValue: "smtp.qq.com" },
|
||||
{ key: "port", label: "SMTP端口", placeholder: "587", required: true, defaultValue: "587" },
|
||||
{ key: "username", label: "SMTP用户名", placeholder: "your-account@qq.com", required: true },
|
||||
{ key: "fromAddress", label: "发件人地址", placeholder: "your-account@qq.com", required: true },
|
||||
{ key: "auth", label: "启用认证", type: "checkbox", defaultValue: true },
|
||||
{ key: "starttls", label: "启用 STARTTLS", type: "checkbox", defaultValue: true },
|
||||
{ key: "ssl", label: "启用 SSL", type: "checkbox", defaultValue: false }
|
||||
],
|
||||
secretFields: [
|
||||
{ key: "password", label: "SMTP密码 / 授权码", required: true }
|
||||
]
|
||||
},
|
||||
MOCK_EMAIL: {
|
||||
label: "开发Mock邮件",
|
||||
configFields: [
|
||||
{ key: "fromAddress", label: "模拟发件人", placeholder: "mock@messagehub.local", defaultValue: "mock@messagehub.local" }
|
||||
],
|
||||
secretFields: []
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const state = {
|
||||
channels: [],
|
||||
editingChannel: null
|
||||
};
|
||||
|
||||
const elements = {
|
||||
channelTableBody: document.getElementById("channelTableBody"),
|
||||
channelEmptyState: document.getElementById("channelEmptyState"),
|
||||
refreshButton: document.getElementById("refreshButton"),
|
||||
createButton: document.getElementById("createButton"),
|
||||
resetButton: document.getElementById("resetButton"),
|
||||
channelForm: document.getElementById("channelForm"),
|
||||
channelId: document.getElementById("channelId"),
|
||||
channelType: document.getElementById("channelType"),
|
||||
providerCode: document.getElementById("providerCode"),
|
||||
channelName: document.getElementById("channelName"),
|
||||
remark: document.getElementById("remark"),
|
||||
enabled: document.getElementById("enabled"),
|
||||
isDefault: document.getElementById("isDefault"),
|
||||
dynamicFields: document.getElementById("dynamicFields"),
|
||||
formTitle: document.getElementById("formTitle"),
|
||||
formSubtitle: document.getElementById("formSubtitle"),
|
||||
testForm: document.getElementById("testForm"),
|
||||
testChannelId: document.getElementById("testChannelId"),
|
||||
testReceiver: document.getElementById("testReceiver"),
|
||||
testSubject: document.getElementById("testSubject"),
|
||||
testTemplateCode: document.getElementById("testTemplateCode"),
|
||||
testContent: document.getElementById("testContent"),
|
||||
testTemplateParams: document.getElementById("testTemplateParams"),
|
||||
toast: document.getElementById("toast")
|
||||
};
|
||||
|
||||
function showToast(message, isError = false) {
|
||||
elements.toast.hidden = false;
|
||||
elements.toast.textContent = message;
|
||||
elements.toast.style.background = isError ? "rgba(146, 34, 34, 0.92)" : "rgba(44, 35, 24, 0.92)";
|
||||
clearTimeout(showToast.timer);
|
||||
showToast.timer = setTimeout(() => {
|
||||
elements.toast.hidden = true;
|
||||
}, 2800);
|
||||
}
|
||||
|
||||
async function request(url, options = {}) {
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(options.headers || {})
|
||||
},
|
||||
...options
|
||||
});
|
||||
const payload = await response.json().catch(() => ({ code: 1, message: "服务响应解析失败" }));
|
||||
if (!response.ok || payload.code !== 0) {
|
||||
throw new Error(payload.message || "请求失败");
|
||||
}
|
||||
return payload.data;
|
||||
}
|
||||
|
||||
function providerSchema(channelType, providerCode) {
|
||||
return PROVIDERS[channelType][providerCode];
|
||||
}
|
||||
|
||||
function fillProviderOptions() {
|
||||
const channelType = elements.channelType.value;
|
||||
const options = Object.entries(PROVIDERS[channelType]).map(([code, schema]) => {
|
||||
const selected = code === elements.providerCode.value ? "selected" : "";
|
||||
return `<option value="${code}" ${selected}>${schema.label}</option>`;
|
||||
});
|
||||
elements.providerCode.innerHTML = options.join("");
|
||||
if (!PROVIDERS[channelType][elements.providerCode.value]) {
|
||||
elements.providerCode.value = Object.keys(PROVIDERS[channelType])[0];
|
||||
}
|
||||
renderDynamicFields();
|
||||
}
|
||||
|
||||
function renderDynamicFields() {
|
||||
const schema = providerSchema(elements.channelType.value, elements.providerCode.value);
|
||||
const config = state.editingChannel?.config || {};
|
||||
const secretMask = state.editingChannel?.secretConfigMask || {};
|
||||
|
||||
const configFields = schema.configFields.map((field) => {
|
||||
const value = config[field.key] ?? field.defaultValue ?? "";
|
||||
if (field.type === "checkbox") {
|
||||
return `
|
||||
<label class="checkbox">
|
||||
<input data-role="config" data-key="${field.key}" type="checkbox" ${value ? "checked" : ""}>
|
||||
<span>${field.label}</span>
|
||||
</label>
|
||||
`;
|
||||
}
|
||||
return `
|
||||
<label>
|
||||
<span>${field.label}</span>
|
||||
<input
|
||||
data-role="config"
|
||||
data-key="${field.key}"
|
||||
type="text"
|
||||
${field.required ? "required" : ""}
|
||||
placeholder="${field.placeholder || ""}"
|
||||
value="${String(value).replaceAll('"', """)}"
|
||||
>
|
||||
</label>
|
||||
`;
|
||||
});
|
||||
|
||||
const secretFields = schema.secretFields.map((field) => {
|
||||
const placeholder = secretMask[field.key] ? `当前值:${secretMask[field.key]};留空则保持不变` : "";
|
||||
return `
|
||||
<label>
|
||||
<span>${field.label}</span>
|
||||
<input
|
||||
data-role="secret"
|
||||
data-key="${field.key}"
|
||||
type="password"
|
||||
${state.editingChannel ? "" : field.required ? "required" : ""}
|
||||
placeholder="${placeholder}"
|
||||
>
|
||||
<p class="field-hint">敏感信息会在数据库中加密保存。</p>
|
||||
</label>
|
||||
`;
|
||||
});
|
||||
|
||||
elements.dynamicFields.innerHTML = [...configFields, ...secretFields].join("");
|
||||
}
|
||||
|
||||
function resetForm(channel = null) {
|
||||
state.editingChannel = channel;
|
||||
elements.channelId.value = channel?.id || "";
|
||||
elements.channelType.value = channel?.channelType || "SMS";
|
||||
fillProviderOptions();
|
||||
elements.providerCode.value = channel?.providerCode || elements.providerCode.value;
|
||||
elements.channelName.value = channel?.channelName || "";
|
||||
elements.remark.value = channel?.remark || "";
|
||||
elements.enabled.checked = channel?.enabled ?? true;
|
||||
elements.isDefault.checked = channel?.isDefault ?? false;
|
||||
elements.formTitle.textContent = channel ? "编辑通道" : "新增通道";
|
||||
elements.formSubtitle.textContent = channel ? "留空的敏感字段会保留原值。" : "保存后即可加入发送主链路。";
|
||||
renderDynamicFields();
|
||||
}
|
||||
|
||||
function statusBadge(channel) {
|
||||
if (!channel.enabled) {
|
||||
return `<span class="badge warn">已停用</span>`;
|
||||
}
|
||||
return channel.isDefault
|
||||
? `<span class="badge good">已启用 / 默认</span>`
|
||||
: `<span class="badge warn">已启用</span>`;
|
||||
}
|
||||
|
||||
function healthBadge(channel) {
|
||||
if (channel.healthStatus === "HEALTHY") {
|
||||
return `<span class="badge good">正常</span>`;
|
||||
}
|
||||
if (channel.healthStatus === "UNHEALTHY") {
|
||||
return `<span class="badge bad">异常</span>`;
|
||||
}
|
||||
return `<span class="badge warn">待检测</span>`;
|
||||
}
|
||||
|
||||
function renderChannelTable() {
|
||||
elements.channelTableBody.innerHTML = "";
|
||||
elements.channelEmptyState.hidden = state.channels.length > 0;
|
||||
|
||||
state.channels.forEach((channel) => {
|
||||
const row = document.createElement("tr");
|
||||
row.innerHTML = `
|
||||
<td>
|
||||
<strong>${channel.channelName}</strong>
|
||||
${channel.remark ? `<div class="table-note">${channel.remark}</div>` : ""}
|
||||
</td>
|
||||
<td>${channel.channelType === "SMS" ? "短信" : "邮件"}</td>
|
||||
<td>${channel.providerName}</td>
|
||||
<td>${statusBadge(channel)}</td>
|
||||
<td>
|
||||
${healthBadge(channel)}
|
||||
${channel.healthMessage ? `<div class="table-note">${channel.healthMessage}</div>` : ""}
|
||||
</td>
|
||||
<td>${channel.lastHealthCheckTime ? new Date(channel.lastHealthCheckTime).toLocaleString() : "-"}</td>
|
||||
<td>
|
||||
<div class="actions">
|
||||
<button class="ghost-button small" data-action="edit" data-id="${channel.id}">编辑</button>
|
||||
<button class="ghost-button small" data-action="status" data-id="${channel.id}">
|
||||
${channel.enabled ? "停用" : "启用"}
|
||||
</button>
|
||||
<button class="ghost-button small" data-action="health" data-id="${channel.id}">体检</button>
|
||||
<button class="ghost-button small" data-action="test" data-id="${channel.id}">测试</button>
|
||||
</div>
|
||||
</td>
|
||||
`;
|
||||
elements.channelTableBody.appendChild(row);
|
||||
});
|
||||
|
||||
fillTestChannelOptions();
|
||||
}
|
||||
|
||||
function fillTestChannelOptions(selectedId = "") {
|
||||
const options = state.channels.map((channel) => {
|
||||
const selected = String(channel.id) === String(selectedId) ? "selected" : "";
|
||||
return `<option value="${channel.id}" ${selected}>${channel.channelName} / ${channel.providerName}</option>`;
|
||||
});
|
||||
elements.testChannelId.innerHTML = options.join("");
|
||||
if (!elements.testChannelId.value && state.channels[0]) {
|
||||
elements.testChannelId.value = state.channels[0].id;
|
||||
}
|
||||
syncTestFormVisibility();
|
||||
}
|
||||
|
||||
function collectDynamicValues(role) {
|
||||
const nodes = elements.dynamicFields.querySelectorAll(`[data-role="${role}"]`);
|
||||
const result = {};
|
||||
nodes.forEach((node) => {
|
||||
const key = node.dataset.key;
|
||||
if (node.type === "checkbox") {
|
||||
result[key] = node.checked;
|
||||
return;
|
||||
}
|
||||
if (node.value.trim()) {
|
||||
result[key] = node.value.trim();
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
async function loadChannels() {
|
||||
const channels = await request("/admin/api/channels");
|
||||
state.channels = channels;
|
||||
renderChannelTable();
|
||||
}
|
||||
|
||||
async function onTableClick(event) {
|
||||
const target = event.target.closest("button[data-action]");
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
const channelId = target.dataset.id;
|
||||
const action = target.dataset.action;
|
||||
|
||||
if (action === "edit") {
|
||||
const detail = await request(`/admin/api/channels/${channelId}`);
|
||||
resetForm(detail);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "status") {
|
||||
const channel = state.channels.find((item) => String(item.id) === String(channelId));
|
||||
const payload = { enabled: !channel.enabled };
|
||||
await request(`/admin/api/channels/${channelId}/status`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
showToast(channel.enabled ? "通道已停用" : "通道已启用");
|
||||
await loadChannels();
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "health") {
|
||||
await request(`/admin/api/channels/${channelId}/health-check`, { method: "POST" });
|
||||
showToast("健康检查已完成");
|
||||
await loadChannels();
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "test") {
|
||||
fillTestChannelOptions(channelId);
|
||||
elements.testReceiver.focus();
|
||||
}
|
||||
}
|
||||
|
||||
async function onSubmitForm(event) {
|
||||
event.preventDefault();
|
||||
const payload = {
|
||||
channelType: elements.channelType.value,
|
||||
providerCode: elements.providerCode.value,
|
||||
channelName: elements.channelName.value.trim(),
|
||||
remark: elements.remark.value.trim(),
|
||||
enabled: elements.enabled.checked,
|
||||
isDefault: elements.isDefault.checked,
|
||||
config: collectDynamicValues("config"),
|
||||
secretConfig: collectDynamicValues("secret")
|
||||
};
|
||||
|
||||
const channelId = elements.channelId.value;
|
||||
if (channelId) {
|
||||
await request(`/admin/api/channels/${channelId}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
showToast("通道已更新");
|
||||
} else {
|
||||
await request("/admin/api/channels", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
showToast("通道已创建");
|
||||
}
|
||||
|
||||
resetForm();
|
||||
await loadChannels();
|
||||
}
|
||||
|
||||
function syncTestFormVisibility() {
|
||||
const selectedId = elements.testChannelId.value;
|
||||
const channel = state.channels.find((item) => String(item.id) === String(selectedId));
|
||||
const emailOnly = document.querySelectorAll(".test-only-email");
|
||||
const smsOnly = document.querySelectorAll(".test-only-sms");
|
||||
|
||||
if (!channel) {
|
||||
emailOnly.forEach((node) => { node.hidden = true; });
|
||||
smsOnly.forEach((node) => { node.hidden = true; });
|
||||
return;
|
||||
}
|
||||
|
||||
const isEmail = channel.channelType === "EMAIL";
|
||||
emailOnly.forEach((node) => { node.hidden = !isEmail; });
|
||||
smsOnly.forEach((node) => { node.hidden = isEmail; });
|
||||
}
|
||||
|
||||
async function onSubmitTest(event) {
|
||||
event.preventDefault();
|
||||
let templateParams = {};
|
||||
const rawTemplateParams = elements.testTemplateParams.value.trim();
|
||||
if (rawTemplateParams) {
|
||||
try {
|
||||
templateParams = JSON.parse(rawTemplateParams);
|
||||
} catch (error) {
|
||||
showToast("模板参数 JSON 解析失败", true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const payload = {
|
||||
channelId: Number(elements.testChannelId.value),
|
||||
receiver: elements.testReceiver.value.trim(),
|
||||
subject: elements.testSubject.value.trim(),
|
||||
content: elements.testContent.value.trim(),
|
||||
templateCode: elements.testTemplateCode.value.trim(),
|
||||
templateParams
|
||||
};
|
||||
|
||||
const message = await request("/admin/api/channels/test-send", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
showToast(message || "测试消息已发送");
|
||||
}
|
||||
|
||||
function bindEvents() {
|
||||
elements.refreshButton.addEventListener("click", () => loadChannels().catch(handleError));
|
||||
elements.createButton.addEventListener("click", () => resetForm());
|
||||
elements.resetButton.addEventListener("click", () => resetForm());
|
||||
elements.channelType.addEventListener("change", fillProviderOptions);
|
||||
elements.providerCode.addEventListener("change", renderDynamicFields);
|
||||
elements.channelForm.addEventListener("submit", (event) => onSubmitForm(event).catch(handleError));
|
||||
elements.channelTableBody.addEventListener("click", (event) => onTableClick(event).catch(handleError));
|
||||
elements.testChannelId.addEventListener("change", syncTestFormVisibility);
|
||||
elements.testForm.addEventListener("submit", (event) => onSubmitTest(event).catch(handleError));
|
||||
}
|
||||
|
||||
function handleError(error) {
|
||||
console.error(error);
|
||||
showToast(error.message || "操作失败", true);
|
||||
}
|
||||
|
||||
async function bootstrap() {
|
||||
bindEvents();
|
||||
resetForm();
|
||||
await loadChannels();
|
||||
}
|
||||
|
||||
bootstrap().catch(handleError);
|
||||
@@ -0,0 +1,142 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>MessageHub 通道管理</title>
|
||||
<link rel="stylesheet" href="./styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="page-shell">
|
||||
<header class="hero">
|
||||
<div>
|
||||
<p class="eyebrow">MessageHub Admin</p>
|
||||
<h1>短信 / 邮件通道管理</h1>
|
||||
<p class="subtitle">在这里维护数据库通道配置、执行健康检查,并直接发送测试消息。</p>
|
||||
</div>
|
||||
<div class="hero-actions">
|
||||
<button id="refreshButton" class="ghost-button">刷新列表</button>
|
||||
<button id="createButton" class="primary-button">新增通道</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="content-grid">
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2>通道列表</h2>
|
||||
<p>支持启停、默认通道切换与单通道健康检查。</p>
|
||||
</div>
|
||||
</div>
|
||||
<div id="channelEmptyState" class="empty-state" hidden>暂无通道数据。</div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>名称</th>
|
||||
<th>类型</th>
|
||||
<th>提供方</th>
|
||||
<th>状态</th>
|
||||
<th>健康检查</th>
|
||||
<th>最近检测</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="channelTableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<aside class="side-stack">
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2 id="formTitle">新增通道</h2>
|
||||
<p id="formSubtitle">保存后即可加入发送主链路。</p>
|
||||
</div>
|
||||
<button id="resetButton" class="ghost-button small">重置</button>
|
||||
</div>
|
||||
<form id="channelForm" class="form-grid">
|
||||
<input type="hidden" id="channelId">
|
||||
<label>
|
||||
<span>通道类型</span>
|
||||
<select id="channelType" required>
|
||||
<option value="SMS">短信</option>
|
||||
<option value="EMAIL">邮件</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>提供方</span>
|
||||
<select id="providerCode" required></select>
|
||||
</label>
|
||||
<label>
|
||||
<span>通道名称</span>
|
||||
<input id="channelName" type="text" maxlength="100" required placeholder="例如:生产短信主通道">
|
||||
</label>
|
||||
<label>
|
||||
<span>备注</span>
|
||||
<input id="remark" type="text" maxlength="255" placeholder="可选">
|
||||
</label>
|
||||
<div class="inline-checks">
|
||||
<label class="checkbox">
|
||||
<input id="enabled" type="checkbox" checked>
|
||||
<span>启用</span>
|
||||
</label>
|
||||
<label class="checkbox">
|
||||
<input id="isDefault" type="checkbox">
|
||||
<span>设为默认</span>
|
||||
</label>
|
||||
</div>
|
||||
<div id="dynamicFields" class="dynamic-fields"></div>
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="primary-button">保存通道</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2>测试发送</h2>
|
||||
<p>支持按通道直接发测试短信或测试邮件。</p>
|
||||
</div>
|
||||
</div>
|
||||
<form id="testForm" class="form-grid">
|
||||
<label>
|
||||
<span>选择通道</span>
|
||||
<select id="testChannelId" required></select>
|
||||
</label>
|
||||
<label>
|
||||
<span>接收目标</span>
|
||||
<input id="testReceiver" type="text" required placeholder="手机号或邮箱">
|
||||
</label>
|
||||
<label class="test-only-email">
|
||||
<span>邮件主题</span>
|
||||
<input id="testSubject" type="text" placeholder="留空则使用默认主题">
|
||||
</label>
|
||||
<label class="test-only-sms">
|
||||
<span>模板编码</span>
|
||||
<input id="testTemplateCode" type="text" placeholder="Spug 短信测试时必填">
|
||||
</label>
|
||||
<label class="full-width">
|
||||
<span>消息内容 / 说明</span>
|
||||
<textarea id="testContent" rows="4" placeholder="短信 mock 会直接记录这里的内容;邮件会作为正文"></textarea>
|
||||
</label>
|
||||
<label class="full-width test-only-sms">
|
||||
<span>模板参数 JSON</span>
|
||||
<textarea id="testTemplateParams" rows="4" placeholder='例如:{"code":"123456","minutes":"5"}'></textarea>
|
||||
</label>
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="primary-button">发送测试消息</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
</aside>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<div id="toast" class="toast" hidden></div>
|
||||
|
||||
<script src="./app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,328 @@
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--bg: #f4efe5;
|
||||
--panel: rgba(255, 252, 246, 0.9);
|
||||
--panel-strong: #fffdfa;
|
||||
--line: #d9c8a7;
|
||||
--text: #2c2318;
|
||||
--muted: #74624a;
|
||||
--accent: #b85b2f;
|
||||
--accent-dark: #8e4020;
|
||||
--good: #23734c;
|
||||
--warn: #b87921;
|
||||
--bad: #b74230;
|
||||
--shadow: 0 20px 50px rgba(71, 49, 15, 0.12);
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
font-family: "Microsoft YaHei", "PingFang SC", sans-serif;
|
||||
color: var(--text);
|
||||
background:
|
||||
radial-gradient(circle at top left, rgba(255, 255, 255, 0.65), transparent 28%),
|
||||
radial-gradient(circle at right 20%, rgba(232, 188, 141, 0.35), transparent 26%),
|
||||
linear-gradient(180deg, #efe7d7 0%, #f7f2e7 54%, #f3ede2 100%);
|
||||
}
|
||||
|
||||
.page-shell {
|
||||
width: min(1440px, calc(100vw - 32px));
|
||||
margin: 0 auto;
|
||||
padding: 24px 0 40px;
|
||||
}
|
||||
|
||||
.hero {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 24px;
|
||||
align-items: flex-end;
|
||||
padding: 28px 32px;
|
||||
border: 1px solid rgba(114, 83, 38, 0.15);
|
||||
border-radius: 28px;
|
||||
background: linear-gradient(135deg, rgba(255, 252, 246, 0.96), rgba(245, 233, 212, 0.88));
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
margin: 0 0 6px;
|
||||
font-size: 12px;
|
||||
letter-spacing: 0.18em;
|
||||
text-transform: uppercase;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.hero h1 {
|
||||
margin: 0;
|
||||
font-size: clamp(28px, 4vw, 42px);
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
margin: 10px 0 0;
|
||||
max-width: 760px;
|
||||
color: var(--muted);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.hero-actions {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.content-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1.35fr 0.95fr;
|
||||
gap: 24px;
|
||||
margin-top: 24px;
|
||||
}
|
||||
|
||||
.side-stack {
|
||||
display: grid;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.panel {
|
||||
border: 1px solid rgba(114, 83, 38, 0.15);
|
||||
border-radius: 24px;
|
||||
padding: 24px;
|
||||
background: var(--panel);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 16px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.panel-header h2 {
|
||||
margin: 0;
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
.panel-header p {
|
||||
margin: 6px 0 0;
|
||||
color: var(--muted);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.table-wrap {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
padding: 14px 12px;
|
||||
border-bottom: 1px solid rgba(114, 83, 38, 0.12);
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
th {
|
||||
color: var(--muted);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
tbody tr:hover {
|
||||
background: rgba(255, 255, 255, 0.55);
|
||||
}
|
||||
|
||||
.table-note {
|
||||
margin-top: 6px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 4px 10px;
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.badge.good {
|
||||
color: var(--good);
|
||||
background: rgba(35, 115, 76, 0.12);
|
||||
}
|
||||
|
||||
.badge.warn {
|
||||
color: var(--warn);
|
||||
background: rgba(184, 121, 33, 0.12);
|
||||
}
|
||||
|
||||
.badge.bad {
|
||||
color: var(--bad);
|
||||
background: rgba(183, 66, 48, 0.12);
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
button {
|
||||
appearance: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
border-radius: 12px;
|
||||
padding: 11px 16px;
|
||||
font-size: 14px;
|
||||
transition: transform 0.15s ease, box-shadow 0.15s ease, background 0.15s ease;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.primary-button {
|
||||
color: #fffaf3;
|
||||
background: linear-gradient(135deg, var(--accent), var(--accent-dark));
|
||||
box-shadow: 0 14px 28px rgba(184, 91, 47, 0.28);
|
||||
}
|
||||
|
||||
.ghost-button {
|
||||
color: var(--text);
|
||||
background: rgba(255, 255, 255, 0.65);
|
||||
border: 1px solid rgba(114, 83, 38, 0.18);
|
||||
}
|
||||
|
||||
.small {
|
||||
padding: 8px 12px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.form-grid {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.form-grid label,
|
||||
.field-group {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.form-grid span {
|
||||
font-size: 13px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
width: 100%;
|
||||
padding: 12px 14px;
|
||||
border-radius: 14px;
|
||||
border: 1px solid rgba(114, 83, 38, 0.18);
|
||||
background: var(--panel-strong);
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.inline-checks {
|
||||
display: flex;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.checkbox {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.checkbox input {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.dynamic-fields {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.field-hint {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.full-width {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
padding: 18px;
|
||||
border: 1px dashed rgba(114, 83, 38, 0.24);
|
||||
border-radius: 18px;
|
||||
color: var(--muted);
|
||||
background: rgba(255, 255, 255, 0.45);
|
||||
}
|
||||
|
||||
.toast {
|
||||
position: fixed;
|
||||
right: 24px;
|
||||
bottom: 24px;
|
||||
min-width: 240px;
|
||||
max-width: min(420px, calc(100vw - 32px));
|
||||
padding: 14px 16px;
|
||||
border-radius: 16px;
|
||||
color: #fffaf2;
|
||||
background: rgba(44, 35, 24, 0.92);
|
||||
box-shadow: var(--shadow);
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
.content-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.hero {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.page-shell {
|
||||
width: min(100vw, calc(100vw - 20px));
|
||||
padding-top: 12px;
|
||||
}
|
||||
|
||||
.hero,
|
||||
.panel {
|
||||
padding: 20px;
|
||||
border-radius: 20px;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
padding: 12px 8px;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user