├── src ├── test │ └── java │ │ └── com │ │ └── insight │ │ └── common │ │ └── message │ │ └── MessageApplicationTests.java └── main │ ├── java │ └── com │ │ └── insight │ │ ├── common │ │ └── message │ │ │ ├── common │ │ │ ├── dto │ │ │ │ ├── CodeDto.java │ │ │ │ ├── ScheduleCall.java │ │ │ │ ├── TemplateDto.java │ │ │ │ ├── MessageListDto.java │ │ │ │ ├── NormalMessage.java │ │ │ │ ├── SceneDto.java │ │ │ │ ├── ScheduleListDto.java │ │ │ │ ├── UserMessageDto.java │ │ │ │ ├── CustomMessage.java │ │ │ │ └── SceneConfigDto.java │ │ │ ├── client │ │ │ │ ├── RabbitClient.java │ │ │ │ ├── AuthClient.java │ │ │ │ ├── TaskClient.java │ │ │ │ ├── LogServiceClient.java │ │ │ │ ├── LogClient.java │ │ │ │ └── AliyunClient.java │ │ │ ├── config │ │ │ │ ├── RabbitClient.java │ │ │ │ ├── SmsChannel.java │ │ │ │ ├── FeignClientConfig.java │ │ │ │ ├── TopicExchangeConfig.java │ │ │ │ └── GlobalExceptionHandler.java │ │ │ ├── entity │ │ │ │ ├── OperateType.java │ │ │ │ ├── SubscribeMessage.java │ │ │ │ ├── PushMessage.java │ │ │ │ ├── Scene.java │ │ │ │ └── SceneConfig.java │ │ │ ├── Listener.java │ │ │ ├── ScheduleTask.java │ │ │ ├── MessageDal.java │ │ │ ├── mapper │ │ │ │ ├── SceneMapper.java │ │ │ │ └── MessageMapper.java │ │ │ └── Core.java │ │ │ ├── schedule │ │ │ ├── ScheduleService.java │ │ │ ├── ScheduleController.java │ │ │ └── ScheduleServiceImpl.java │ │ │ ├── message │ │ │ ├── MessageService.java │ │ │ ├── MessageController.java │ │ │ └── MessageServiceImpl.java │ │ │ └── scene │ │ │ ├── SceneService.java │ │ │ ├── SceneServiceImpl.java │ │ │ └── SceneController.java │ │ └── MessageApplication.java │ └── resources │ └── application.yml ├── .gitignore ├── pom.xml └── LICENSE /src/test/java/com/insight/common/message/MessageApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | public class MessageApplicationTests { 8 | 9 | @Test 10 | public void contextLoads() { 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/dto/CodeDto.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.dto; 2 | 3 | import com.insight.utils.pojo.base.BaseXo; 4 | 5 | /** 6 | * @author 宣炳刚 7 | * @date 2023/3/15 8 | * @remark CodeDTO 9 | */ 10 | public class CodeDto extends BaseXo { 11 | 12 | /** 13 | * 用户登录账号 14 | */ 15 | private String account; 16 | 17 | public CodeDto(String account) { 18 | this.account = account; 19 | } 20 | 21 | public Integer getType() { 22 | return 0; 23 | } 24 | 25 | public String getAccount() { 26 | return account; 27 | } 28 | 29 | public void setAccount(String account) { 30 | this.account = account; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/client/RabbitClient.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.client; 2 | 3 | import com.insight.utils.common.ApplicationContextHolder; 4 | import com.insight.utils.pojo.message.Schedule; 5 | import org.springframework.amqp.rabbit.core.RabbitTemplate; 6 | 7 | /** 8 | * @author 宣炳刚 9 | * @date 2019-09-03 10 | * @remark RabbitMQ客户端 11 | */ 12 | public class RabbitClient { 13 | private static final RabbitTemplate TEMPLATE = ApplicationContextHolder.getContext().getBean(RabbitTemplate.class); 14 | 15 | /** 16 | * 发送计划任务数据到队列 17 | * 18 | * @param schedule 计划任务DTO 19 | */ 20 | public static void sendTopic(String key, Schedule schedule) { 21 | TEMPLATE.convertAndSend("amq.topic", key, schedule); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/config/RabbitClient.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.config; 2 | 3 | import com.insight.utils.Json; 4 | import com.insight.utils.common.ApplicationContextHolder; 5 | import org.springframework.amqp.rabbit.core.RabbitTemplate; 6 | 7 | /** 8 | * @author 宣炳刚 9 | * @date 2023-1-4 10 | * @remark RabbitMQ客户端 11 | */ 12 | public class RabbitClient { 13 | private static final RabbitTemplate TEMPLATE = ApplicationContextHolder.getContext().getBean(RabbitTemplate.class); 14 | 15 | /** 16 | * 发送资源数据到队列 17 | * 18 | * @param data 用户DTO 19 | */ 20 | public static void sendResources(Object data) { 21 | Object object = Json.clone(data, Object.class); 22 | TEMPLATE.convertAndSend("amq.topic", "hxb.resources", object); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: common-message 4 | cloud: 5 | consul: 6 | config: 7 | defaultContext: ${spring.application.name} 8 | format: yaml 9 | prefixes: config 10 | --- 11 | spring: 12 | cloud: 13 | consul: 14 | host: localhost 15 | config: 16 | activate: 17 | on-profile: pro 18 | import: optional:consul:localhost:8500 19 | --- 20 | spring: 21 | cloud: 22 | consul: 23 | host: 192.168.1.94 24 | config: 25 | activate: 26 | on-profile: test 27 | import: optional:consul:192.168.1.94:8500 28 | --- 29 | spring: 30 | cloud: 31 | consul: 32 | config: 33 | acl-token: 877ceaf8-e219-8474-dbb5-f92200235f92 34 | host: 192.168.160.8 35 | config: 36 | activate: 37 | on-profile: dev 38 | import: optional:consul:192.168.160.8:8500 -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/client/AuthClient.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.client; 2 | 3 | import com.insight.common.message.common.config.FeignClientConfig; 4 | import com.insight.common.message.common.dto.CodeDto; 5 | import com.insight.utils.pojo.base.Reply; 6 | import org.springframework.cloud.openfeign.FeignClient; 7 | import org.springframework.web.bind.annotation.PostMapping; 8 | import org.springframework.web.bind.annotation.RequestBody; 9 | 10 | /** 11 | * @author 宣炳刚 12 | * @date 2019-08-31 13 | * @remark Feign客户端 14 | */ 15 | @FeignClient(name = "base-auth", configuration = FeignClientConfig.class) 16 | public interface AuthClient { 17 | 18 | /** 19 | * 获取日志列表 20 | * 21 | * @param dto CodeDTO 22 | * @return Reply 23 | */ 24 | @PostMapping("/base/auth/v1.0/codes") 25 | Reply getCode(@RequestBody CodeDto dto); 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/config/SmsChannel.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.config; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * @author 宣炳刚 7 | * @date 2022/11/25 8 | * @remark 短信通道接口 9 | */ 10 | public interface SmsChannel { 11 | 12 | /** 13 | * 发送模版短信 14 | * 15 | * @param phone 手机号 16 | * @param code 模版代码 17 | * @param param 模版参数 18 | * @param sign 签名 19 | */ 20 | void sendTemplateMessage(String phone, String code, Object param, String sign) throws Exception; 21 | 22 | /** 23 | * 发送自定义内容短信 24 | * 25 | * @param phone 手机号 26 | * @param content 内容 27 | * @param sign 签名 28 | */ 29 | void sendFreeMessage(String phone, String content, String sign) throws Exception; 30 | 31 | /** 32 | * 群发自定义内容短信 33 | * 34 | * @param phones 手机号集合 35 | * @param content 内容 36 | * @param sign 签名 37 | */ 38 | void sendMultiFreeMessage(List phones, String content, String sign) throws Exception; 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/insight/MessageApplication.java: -------------------------------------------------------------------------------- 1 | package com.insight; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6 | import org.springframework.cloud.openfeign.EnableFeignClients; 7 | import org.springframework.scheduling.annotation.EnableAsync; 8 | import org.springframework.scheduling.annotation.EnableScheduling; 9 | import org.springframework.transaction.annotation.EnableTransactionManagement; 10 | 11 | /** 12 | * @author 宣炳刚 13 | * @date 2017/9/15 14 | * @remark 应用入口程序 15 | */ 16 | @SpringBootApplication 17 | @EnableDiscoveryClient 18 | @EnableFeignClients 19 | @EnableAsync 20 | @EnableScheduling 21 | @EnableTransactionManagement 22 | public class MessageApplication { 23 | 24 | /** 25 | * 应用入口方法 26 | * 27 | * @param args 启动参数 28 | */ 29 | public static void main(String[] args) { 30 | SpringApplication.run(MessageApplication.class, args); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/entity/OperateType.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.entity; 2 | 3 | /** 4 | * @author 宣炳刚 5 | * @date 2019-09-13 6 | * @remark 7 | */ 8 | public enum OperateType { 9 | 10 | /** 11 | * 查询操作 12 | */ 13 | SELETE("查询数据"), 14 | 15 | /** 16 | * 新增操作 17 | */ 18 | NEW("新增数据"), 19 | 20 | /** 21 | * 编辑操作 22 | */ 23 | EDIT("修改数据"), 24 | 25 | /** 26 | * 编辑操作 27 | */ 28 | DISABLE("禁用数据"), 29 | 30 | /** 31 | * 编辑操作 32 | */ 33 | ENABLE("启用数据"), 34 | 35 | /** 36 | * 删除操作 37 | */ 38 | DELETE("删除数据"); 39 | 40 | /** 41 | * 操作名称 42 | */ 43 | private final String name; 44 | 45 | /** 46 | * 构造方法 47 | * 48 | * @param name 操作名称 49 | */ 50 | OperateType(String name) { 51 | this.name = name; 52 | } 53 | 54 | /** 55 | * 获取操作名称 56 | * 57 | * @return 操作名称 58 | */ 59 | public String getName() { 60 | return name; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/client/TaskClient.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.client; 2 | 3 | import com.insight.utils.pojo.base.Reply; 4 | import feign.RequestLine; 5 | 6 | import java.net.URI; 7 | 8 | /** 9 | * @author 宣炳刚 10 | * @date 2019-08-31 11 | * @remark 消息中心Feign客户端 12 | */ 13 | public interface TaskClient { 14 | 15 | /** 16 | * POST方法 17 | * 18 | * @param uri URI 19 | * @return Reply 20 | */ 21 | @RequestLine("GET") 22 | Reply get(URI uri); 23 | 24 | /** 25 | * POST方法 26 | * 27 | * @param uri URI 28 | * @param dto DTO 29 | * @return Reply 30 | */ 31 | @RequestLine("POST") 32 | Reply post(URI uri, Object dto); 33 | 34 | /** 35 | * PUT方法 36 | * 37 | * @param uri URI 38 | * @param dto DTO 39 | * @return Reply 40 | */ 41 | @RequestLine("PUT") 42 | Reply put(URI uri, Object dto); 43 | 44 | /** 45 | * DELETE方法 46 | * 47 | * @param uri URI 48 | * @param dto DTO 49 | * @return Reply 50 | */ 51 | @RequestLine("DELETE") 52 | Reply delete(URI uri, Object dto); 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/client/LogServiceClient.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.client; 2 | 3 | 4 | import com.insight.common.message.common.config.FeignClientConfig; 5 | import com.insight.utils.pojo.base.Reply; 6 | import org.springframework.cloud.openfeign.FeignClient; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.PathVariable; 9 | import org.springframework.web.bind.annotation.RequestParam; 10 | 11 | /** 12 | * @author 宣炳刚 13 | * @date 2019-08-31 14 | * @remark 消息中心Feign客户端 15 | */ 16 | @FeignClient(name = "common-basedata", configuration = FeignClientConfig.class) 17 | public interface LogServiceClient { 18 | 19 | /** 20 | * 获取日志列表 21 | * 22 | * @param id 业务ID 23 | * @param code 业务代码 24 | * @param keyword 查询关键词 25 | * @return Reply 26 | */ 27 | @GetMapping("/common/log/v1.0/logs") 28 | Reply getLogs(@RequestParam Long id, @RequestParam String code, @RequestParam String keyword); 29 | 30 | /** 31 | * 获取日志详情 32 | * 33 | * @param id 日志ID 34 | * @return Reply 35 | */ 36 | @GetMapping("/common/log/v1.0/logs/{id}") 37 | Reply getLog(@PathVariable Long id); 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/entity/SubscribeMessage.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.entity; 2 | 3 | import com.insight.utils.pojo.base.BaseXo; 4 | 5 | import java.time.LocalDateTime; 6 | 7 | /** 8 | * @author 宣炳刚 9 | * @date 2019/9/21 10 | * @remark 订阅消息DTO 11 | */ 12 | public class SubscribeMessage extends BaseXo { 13 | 14 | /** 15 | * UUID主键 16 | */ 17 | private Long id; 18 | 19 | /** 20 | * 消息ID 21 | */ 22 | private Long messageId; 23 | 24 | /** 25 | * 用户ID 26 | */ 27 | private Long userId; 28 | 29 | /** 30 | * 创建时间 31 | */ 32 | private LocalDateTime createdTime; 33 | 34 | public Long getId() { 35 | return id; 36 | } 37 | 38 | public void setId(Long id) { 39 | this.id = id; 40 | } 41 | 42 | public Long getMessageId() { 43 | return messageId; 44 | } 45 | 46 | public void setMessageId(Long messageId) { 47 | this.messageId = messageId; 48 | } 49 | 50 | public Long getUserId() { 51 | return userId; 52 | } 53 | 54 | public void setUserId(Long userId) { 55 | this.userId = userId; 56 | } 57 | 58 | public LocalDateTime getCreatedTime() { 59 | return createdTime; 60 | } 61 | 62 | public void setCreatedTime(LocalDateTime createdTime) { 63 | this.createdTime = createdTime; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/config/FeignClientConfig.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.config; 2 | 3 | import feign.RequestInterceptor; 4 | import feign.RequestTemplate; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.web.context.request.RequestContextHolder; 7 | import org.springframework.web.context.request.ServletRequestAttributes; 8 | 9 | /** 10 | * @author 宣炳刚 11 | * @date 2023-1-4 12 | * @remark Feign配置类 13 | */ 14 | @Configuration 15 | public class FeignClientConfig implements RequestInterceptor { 16 | private static final String REGULAR = "fingerprint|requestid|logininfo"; 17 | 18 | /** 19 | * 应用配置 20 | * 21 | * @param template RequestTemplate 22 | */ 23 | @Override 24 | public void apply(RequestTemplate template) { 25 | var requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 26 | if (requestAttributes == null) { 27 | return; 28 | } 29 | 30 | var request = requestAttributes.getRequest(); 31 | var headers = request.getHeaderNames(); 32 | while (headers.hasMoreElements()) { 33 | var name = headers.nextElement(); 34 | if (name.toLowerCase().matches(REGULAR)) { 35 | var values = request.getHeader(name); 36 | template.header(name, values); 37 | } 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/client/LogClient.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.client; 2 | 3 | import com.insight.common.message.common.entity.OperateType; 4 | import com.insight.utils.Json; 5 | import com.insight.utils.common.ApplicationContextHolder; 6 | import com.insight.utils.pojo.auth.LoginInfo; 7 | import com.insight.utils.pojo.message.Log; 8 | import org.springframework.amqp.rabbit.core.RabbitTemplate; 9 | 10 | /** 11 | * @author 宣炳刚 12 | * @date 2019-09-03 13 | * @remark RabbitMQ客户端 14 | */ 15 | public class LogClient { 16 | private static final RabbitTemplate TEMPLATE = ApplicationContextHolder.getContext().getBean(RabbitTemplate.class); 17 | 18 | /** 19 | * 记录操作日志 20 | * 21 | * @param info 用户关键信息 22 | * @param business 业务类型 23 | * @param type 操作类型 24 | * @param id 业务ID 25 | * @param content 日志内容 26 | */ 27 | public static void writeLog(LoginInfo info, String business, OperateType type, Long id, Object content) { 28 | Log log = new Log(); 29 | log.setAppId(info.getAppId()); 30 | log.setTenantId(info.getTenantId()); 31 | log.setType(type.toString()); 32 | log.setBusiness(business); 33 | log.setBusinessId(id); 34 | log.setContent(Json.clone(content, Object.class)); 35 | log.setCreator(info.getName()); 36 | log.setCreatorId(info.getId()); 37 | 38 | TEMPLATE.convertAndSend("amq.topic", "insight.log", log); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/schedule/ScheduleService.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.schedule; 2 | 3 | import com.insight.utils.pojo.auth.LoginInfo; 4 | import com.insight.utils.pojo.base.Reply; 5 | import com.insight.utils.pojo.base.Search; 6 | import com.insight.utils.pojo.message.Schedule; 7 | 8 | /** 9 | * @author 宣炳刚 10 | * @date 2019-08-28 11 | * @remark 计划任务服务接口 12 | */ 13 | public interface ScheduleService { 14 | 15 | /** 16 | * 获取计划任务列表 17 | * 18 | * @param search 查询实体类 19 | * @return Reply 20 | */ 21 | Reply getSchedules(Search search); 22 | 23 | /** 24 | * 获取计划任务详情 25 | * 26 | * @param id 计划任务ID 27 | * @return Reply 28 | */ 29 | Schedule getSchedule(Long id); 30 | 31 | /** 32 | * 新增计划任务 33 | * 34 | * @param dto 计划任务DTO 35 | * @return Reply 36 | */ 37 | Long newSchedule(Schedule dto); 38 | 39 | /** 40 | * 立即执行计划任务 41 | * 42 | * @param info 用户关键信息 43 | * @param id 计划任务ID 44 | */ 45 | void executeSchedule(LoginInfo info, Long id); 46 | 47 | /** 48 | * 删除计划任务 49 | * 50 | * @param info 用户关键信息 51 | * @param id 计划任务ID 52 | */ 53 | void deleteSchedule(LoginInfo info, Long id); 54 | 55 | /** 56 | * 禁用/启用计划任务 57 | * 58 | * @param info 用户关键信息 59 | * @param id 计划任务ID 60 | * @param status 禁用/启用状态 61 | */ 62 | void changeScheduleStatus(LoginInfo info, Long id, boolean status); 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/entity/PushMessage.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.entity; 2 | 3 | import com.insight.utils.pojo.base.BaseXo; 4 | 5 | import java.time.LocalDateTime; 6 | 7 | /** 8 | * @author 宣炳刚 9 | * @date 2019/9/21 10 | * @remark 推送消息DTO 11 | */ 12 | public class PushMessage extends BaseXo { 13 | 14 | /** 15 | * UUID主键 16 | */ 17 | private Long id; 18 | 19 | /** 20 | * 消息ID 21 | */ 22 | private Long messageId; 23 | 24 | /** 25 | * 用户ID 26 | */ 27 | private String userId; 28 | 29 | /** 30 | * 是否已读 31 | */ 32 | private Boolean read; 33 | 34 | /** 35 | * 阅读时间 36 | */ 37 | private LocalDateTime readTime; 38 | 39 | public Long getId() { 40 | return id; 41 | } 42 | 43 | public void setId(Long id) { 44 | this.id = id; 45 | } 46 | 47 | public Long getMessageId() { 48 | return messageId; 49 | } 50 | 51 | public void setMessageId(Long messageId) { 52 | this.messageId = messageId; 53 | } 54 | 55 | public String getUserId() { 56 | return userId; 57 | } 58 | 59 | public void setUserId(String userId) { 60 | this.userId = userId; 61 | } 62 | 63 | public Boolean getRead() { 64 | return read; 65 | } 66 | 67 | public void setRead(Boolean read) { 68 | this.read = read; 69 | } 70 | 71 | public LocalDateTime getReadTime() { 72 | return readTime; 73 | } 74 | 75 | public void setReadTime(LocalDateTime readTime) { 76 | this.readTime = readTime; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/dto/ScheduleCall.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.dto; 2 | 3 | import com.insight.utils.pojo.base.BaseXo; 4 | 5 | import java.util.Map; 6 | 7 | /** 8 | * @author 宣炳刚 9 | * @date 2019/9/25 10 | * @remark 计划任务调用DTO 11 | */ 12 | public class ScheduleCall extends BaseXo { 13 | 14 | /** 15 | * 请求方法 16 | */ 17 | private String method; 18 | 19 | /** 20 | * 服务名/域名 21 | */ 22 | private String service; 23 | 24 | /** 25 | * URL 26 | */ 27 | private String url; 28 | 29 | /** 30 | * 请求头数据 31 | */ 32 | private Map headers; 33 | 34 | /** 35 | * 请求体数据 36 | */ 37 | private Object body; 38 | 39 | public String getMethod() { 40 | return method; 41 | } 42 | 43 | public void setMethod(String method) { 44 | this.method = method; 45 | } 46 | 47 | public String getService() { 48 | return service; 49 | } 50 | 51 | public void setService(String service) { 52 | this.service = service; 53 | } 54 | 55 | public String getUrl() { 56 | return url; 57 | } 58 | 59 | public void setUrl(String url) { 60 | this.url = url; 61 | } 62 | 63 | public Map getHeaders() { 64 | return headers; 65 | } 66 | 67 | public void setHeaders(Map headers) { 68 | this.headers = headers; 69 | } 70 | 71 | public Object getBody() { 72 | return body; 73 | } 74 | 75 | public void setBody(Object body) { 76 | this.body = body; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/dto/TemplateDto.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.dto; 2 | 3 | import com.insight.utils.pojo.base.BaseXo; 4 | 5 | /** 6 | * @author 宣炳刚 7 | * @date 2020/11/24 8 | * @remark 9 | */ 10 | public class TemplateDto extends BaseXo { 11 | 12 | /** 13 | * 发送类型:0.未定义;1.仅消息(0001);2.仅推送(0010);3.推送+消息(0011);4.仅短信(0100);8.仅邮件(1000) 14 | */ 15 | private Integer type; 16 | 17 | /** 18 | * 消息标题 19 | */ 20 | private String title; 21 | 22 | /** 23 | * 消息标签 24 | */ 25 | private String tag; 26 | 27 | /** 28 | * 消息内容 29 | */ 30 | private String content; 31 | 32 | /** 33 | * 签名 34 | */ 35 | private String sign; 36 | 37 | /** 38 | * 消息有效时长(分钟) 39 | */ 40 | private Integer expire; 41 | 42 | public Integer getType() { 43 | return type; 44 | } 45 | 46 | public void setType(Integer type) { 47 | this.type = type; 48 | } 49 | 50 | public String getTitle() { 51 | return title; 52 | } 53 | 54 | public void setTitle(String title) { 55 | this.title = title; 56 | } 57 | 58 | public String getTag() { 59 | return tag; 60 | } 61 | 62 | public void setTag(String tag) { 63 | this.tag = tag; 64 | } 65 | 66 | public String getContent() { 67 | return content; 68 | } 69 | 70 | public void setContent(String content) { 71 | this.content = content; 72 | } 73 | 74 | public String getSign() { 75 | return sign; 76 | } 77 | 78 | public void setSign(String sign) { 79 | this.sign = sign; 80 | } 81 | 82 | public Integer getExpire() { 83 | return expire; 84 | } 85 | 86 | public void setExpire(Integer expire) { 87 | this.expire = expire; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/dto/MessageListDto.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.dto; 2 | 3 | import com.insight.utils.pojo.base.BaseXo; 4 | 5 | import java.time.LocalDateTime; 6 | 7 | /** 8 | * @author 宣炳刚 9 | * @date 2019/9/20 10 | * @remark 消息DTO 11 | */ 12 | public class MessageListDto extends BaseXo { 13 | 14 | /** 15 | * UUID主键 16 | */ 17 | private Long id; 18 | 19 | /** 20 | * 消息标签 21 | */ 22 | private String tag; 23 | 24 | /** 25 | * 消息标题 26 | */ 27 | private String title; 28 | 29 | /** 30 | * 是否已读 31 | */ 32 | private Boolean read; 33 | 34 | /** 35 | * 创建人 36 | */ 37 | private String creator; 38 | 39 | /** 40 | * 创建时间 41 | */ 42 | private LocalDateTime createdTime; 43 | 44 | public Long getId() { 45 | return id; 46 | } 47 | 48 | public void setId(Long id) { 49 | this.id = id; 50 | } 51 | 52 | public String getTag() { 53 | return tag; 54 | } 55 | 56 | public void setTag(String tag) { 57 | this.tag = tag; 58 | } 59 | 60 | public String getTitle() { 61 | return title; 62 | } 63 | 64 | public void setTitle(String title) { 65 | this.title = title; 66 | } 67 | 68 | public Boolean getRead() { 69 | return read; 70 | } 71 | 72 | public void setRead(Boolean read) { 73 | this.read = read; 74 | } 75 | 76 | public String getCreator() { 77 | return creator; 78 | } 79 | 80 | public void setCreator(String creator) { 81 | this.creator = creator; 82 | } 83 | 84 | public LocalDateTime getCreatedTime() { 85 | return createdTime; 86 | } 87 | 88 | public void setCreatedTime(LocalDateTime createdTime) { 89 | this.createdTime = createdTime; 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/message/MessageService.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.message; 2 | 3 | import com.insight.common.message.common.dto.CustomMessage; 4 | import com.insight.common.message.common.dto.NormalMessage; 5 | import com.insight.common.message.common.dto.UserMessageDto; 6 | import com.insight.utils.pojo.auth.LoginInfo; 7 | import com.insight.utils.pojo.base.Reply; 8 | import com.insight.utils.pojo.base.Search; 9 | import com.insight.utils.pojo.message.SmsCode; 10 | 11 | /** 12 | * @author 宣炳刚 13 | * @date 2019-08-28 14 | * @remark 短信服务接口 15 | */ 16 | public interface MessageService { 17 | 18 | /** 19 | * 生成短信验证码 20 | * 21 | * @param dto 验证码 22 | */ 23 | void seedSmsCode(SmsCode dto); 24 | 25 | /** 26 | * 验证短信验证码 27 | * 28 | * @param key 验证参数,MD5(type + mobile + code) 29 | * @param isCheck 是否检验模式:true.检验模式,验证后验证码不失效;false.验证模式,验证后验证码失效 30 | * @return Reply 31 | */ 32 | String verifySmsCode(String key, Boolean isCheck); 33 | 34 | /** 35 | * 发送送标准消息 36 | * 37 | * @param info 用户关键信息 38 | * @param dto 标准信息DTO 39 | */ 40 | void sendNormalMessage(LoginInfo info, NormalMessage dto); 41 | 42 | /** 43 | * 发送自定义消息 44 | * 45 | * @param info 用户关键信息 46 | * @param dto 标准信息DTO 47 | */ 48 | void sendCustomMessage(LoginInfo info, CustomMessage dto); 49 | 50 | /** 51 | * 获取用户消息列表 52 | * 53 | * @param info 用户关键信息 54 | * @param search 查询实体类 55 | * @return Reply 56 | */ 57 | Reply getUserMessages(LoginInfo info, Search search); 58 | 59 | /** 60 | * 获取用户消息详情 61 | * 62 | * @param messageId 消息ID 63 | * @param userId 用户ID 64 | * @return Reply 65 | */ 66 | UserMessageDto getUserMessage(Long messageId, Long userId); 67 | 68 | /** 69 | * 删除用户消息 70 | * 71 | * @param messageId 消息ID 72 | * @param userId 用户ID 73 | */ 74 | void deleteUserMessage(Long messageId, Long userId); 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/dto/NormalMessage.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.dto; 2 | 3 | import com.insight.utils.Util; 4 | import com.insight.utils.pojo.base.BaseXo; 5 | import jakarta.validation.constraints.NotEmpty; 6 | import jakarta.validation.constraints.NotNull; 7 | 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | /** 12 | * @author 宣炳刚 13 | * @date 2019/9/20 14 | * @remark 标准消息DTO 15 | */ 16 | public class NormalMessage extends BaseXo { 17 | 18 | /** 19 | * 场景编码 20 | */ 21 | @NotEmpty(message = "场景编码不能为空") 22 | private String sceneCode; 23 | 24 | /** 25 | * 合作伙伴编码 26 | */ 27 | private String partnerCode; 28 | 29 | /** 30 | * 接收人,多个接收人使用逗号分隔 31 | */ 32 | @NotEmpty(message = "接收人不能为空") 33 | private List receivers; 34 | 35 | /** 36 | * 自定义参数 37 | */ 38 | private Map params; 39 | 40 | /** 41 | * 是否广播消息 42 | */ 43 | @NotNull(message = "广播设置不能为空") 44 | private Boolean broadcast; 45 | 46 | public String getSceneCode() { 47 | return sceneCode; 48 | } 49 | 50 | public void setSceneCode(String sceneCode) { 51 | this.sceneCode = sceneCode; 52 | } 53 | 54 | public String getPartnerCode() { 55 | return partnerCode; 56 | } 57 | 58 | public void setPartnerCode(String partnerCode) { 59 | this.partnerCode = partnerCode; 60 | } 61 | 62 | public List getReceivers() { 63 | return receivers; 64 | } 65 | 66 | public void setReceivers(String receivers) { 67 | this.receivers = Util.toStringList(receivers); 68 | } 69 | 70 | public Map getParams() { 71 | return params; 72 | } 73 | 74 | public void setParams(Map params) { 75 | this.params = params; 76 | } 77 | 78 | public Boolean getBroadcast() { 79 | return broadcast; 80 | } 81 | 82 | public void setBroadcast(Boolean broadcast) { 83 | this.broadcast = broadcast; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/client/AliyunClient.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.client; 2 | 3 | import com.aliyun.dysmsapi20170525.Client; 4 | import com.aliyun.dysmsapi20170525.models.SendSmsRequest; 5 | import com.aliyun.teaopenapi.models.Config; 6 | import com.aliyun.teautil.models.RuntimeOptions; 7 | import com.insight.utils.EnvUtil; 8 | import com.insight.utils.Json; 9 | import com.insight.utils.pojo.base.BusinessException; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | 13 | /** 14 | * @author 宣炳刚 15 | * @date 2022/11/25 16 | * @remark 17 | */ 18 | public class AliyunClient { 19 | private static final Logger logger = LoggerFactory.getLogger(AliyunClient.class); 20 | 21 | /** 22 | * 初始化Client 23 | * 24 | * @return Client 25 | */ 26 | public static Client createClient() throws Exception { 27 | String accessKeyId = EnvUtil.getValue("insight.sms.aliyun.accessKeyId"); 28 | String accessKeySecret = EnvUtil.getValue("insight.sms.aliyun.accessKeySecret"); 29 | Config config = new Config().setAccessKeyId(accessKeyId).setAccessKeySecret(accessKeySecret); 30 | config.endpoint = "dysmsapi.aliyuncs.com"; 31 | 32 | return new Client(config); 33 | } 34 | 35 | /** 36 | * 发送短信 37 | * 38 | * @param phone 手机号 39 | * @param code 模版代码 40 | * @param param 模版参数 41 | * @param sign 签名 42 | */ 43 | public static void sendTemplateMessage(String phone, String code, Object param, String sign) throws Exception { 44 | Client client = createClient(); 45 | SendSmsRequest request = new SendSmsRequest() 46 | .setPhoneNumbers(phone) 47 | .setTemplateCode(code) 48 | .setTemplateParam(Json.toJson(param)) 49 | .setSignName(sign); 50 | 51 | var response = client.sendSmsWithOptions(request, new RuntimeOptions()); 52 | if (!response.statusCode.equals(200) || !response.body.code.equals("OK")) { 53 | throw new BusinessException(response.body.message); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/config/TopicExchangeConfig.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.config; 2 | 3 | import org.springframework.amqp.core.Binding; 4 | import org.springframework.amqp.core.BindingBuilder; 5 | import org.springframework.amqp.core.Queue; 6 | import org.springframework.amqp.core.TopicExchange; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | 10 | /** 11 | * @author 宣炳刚 12 | * @date 2019-09-03 13 | * @remark Topic交换机配置 14 | */ 15 | @Configuration 16 | public class TopicExchangeConfig { 17 | 18 | /** 19 | * Topic交换机 20 | * 21 | * @return TopicExchange 22 | */ 23 | @Bean 24 | public TopicExchange exchange() { 25 | return new TopicExchange("amq.topic"); 26 | } 27 | 28 | /** 29 | * 新增消息发送队列 30 | * 31 | * @return Queue 32 | */ 33 | @Bean 34 | public Queue messageQueue() { 35 | return new Queue("schedule.message"); 36 | } 37 | 38 | /** 39 | * 新增本地调用队列 40 | * 41 | * @return Queue 42 | */ 43 | @Bean 44 | public Queue localQueue() { 45 | return new Queue("schedule.local"); 46 | } 47 | 48 | /** 49 | * 新增远程调用队列 50 | * 51 | * @return Queue 52 | */ 53 | @Bean 54 | public Queue remoteQueue() { 55 | return new Queue("schedule.remote"); 56 | } 57 | 58 | /** 59 | * 消息发送绑定 60 | * 61 | * @return Binding 62 | */ 63 | @Bean 64 | public Binding manageBinding() { 65 | return BindingBuilder.bind(messageQueue()).to(exchange()).with("schedule.message"); 66 | } 67 | 68 | /** 69 | * 本地调用绑定 70 | * 71 | * @return Binding 72 | */ 73 | @Bean 74 | public Binding localBinding() { 75 | return BindingBuilder.bind(localQueue()).to(exchange()).with("schedule.local"); 76 | } 77 | 78 | /** 79 | * 远程调用绑定 80 | * 81 | * @return Binding 82 | */ 83 | @Bean 84 | public Binding remoteBinding() { 85 | return BindingBuilder.bind(remoteQueue()).to(exchange()).with("schedule.remote"); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/scene/SceneService.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.scene; 2 | 3 | import com.insight.common.message.common.dto.SceneConfigDto; 4 | import com.insight.common.message.common.entity.Scene; 5 | import com.insight.common.message.common.entity.SceneConfig; 6 | import com.insight.utils.pojo.auth.LoginInfo; 7 | import com.insight.utils.pojo.base.Reply; 8 | import com.insight.utils.pojo.base.Search; 9 | 10 | import java.util.List; 11 | 12 | /** 13 | * @author 宣炳刚 14 | * @date 2019-08-28 15 | * @remark 消息管理服务接口 16 | */ 17 | public interface SceneService { 18 | 19 | /** 20 | * 获取场景列表 21 | * 22 | * @param search 查询DTO 23 | * @return Reply 24 | */ 25 | Reply getScenes(Search search); 26 | 27 | /** 28 | * 获取场景 29 | * 30 | * @param id 场景ID 31 | * @return Reply 32 | */ 33 | Scene getScene(Long id); 34 | 35 | /** 36 | * 新增场景 37 | * 38 | * @param info 用户关键信息 39 | * @param dto 场景DTO 40 | * @return Reply 41 | */ 42 | Long newScene(LoginInfo info, Scene dto); 43 | 44 | /** 45 | * 编辑场景 46 | * 47 | * @param info 用户关键信息 48 | * @param dto 场景DTO 49 | */ 50 | void editScene(LoginInfo info, Scene dto); 51 | 52 | /** 53 | * 删除场景 54 | * 55 | * @param info 用户关键信息 56 | * @param id 场景ID 57 | */ 58 | void deleteScene(LoginInfo info, Long id); 59 | 60 | /** 61 | * 获取场景配置列表 62 | * 63 | * @param info 用户关键信息 64 | * @param sceneId 场景ID 65 | * @return Reply 66 | */ 67 | List getSceneConfigs(LoginInfo info, Long sceneId); 68 | 69 | /** 70 | * 新增场景配置 71 | * 72 | * @param info 用户关键信息 73 | * @param dto 场景配置DTO 74 | * @return Reply 75 | */ 76 | Long newSceneConfig(LoginInfo info, SceneConfig dto); 77 | 78 | /** 79 | * 编辑场景配置 80 | * 81 | * @param info 用户关键信息 82 | * @param dto 场景配置DTO 83 | */ 84 | void editSceneConfig(LoginInfo info, SceneConfig dto); 85 | 86 | /** 87 | * 删除场景配置 88 | * 89 | * @param info 用户关键信息 90 | * @param id 场景配置ID 91 | */ 92 | void deleteSceneConfig(LoginInfo info, Long id); 93 | } 94 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/Listener.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common; 2 | 3 | import com.insight.common.message.common.dto.ScheduleCall; 4 | import com.insight.utils.pojo.message.InsightMessage; 5 | import com.insight.utils.pojo.message.Schedule; 6 | import com.rabbitmq.client.Channel; 7 | import org.springframework.amqp.core.Message; 8 | import org.springframework.amqp.rabbit.annotation.RabbitHandler; 9 | import org.springframework.amqp.rabbit.annotation.RabbitListener; 10 | import org.springframework.stereotype.Component; 11 | 12 | import java.io.IOException; 13 | import java.net.URISyntaxException; 14 | 15 | /** 16 | * @author 宣炳刚 17 | * @date 2019-09-03 18 | * @remark 队列监听类 19 | */ 20 | @Component 21 | public class Listener { 22 | private final Core core; 23 | 24 | /** 25 | * 构造方法 26 | * 27 | * @param core Core 28 | */ 29 | public Listener(Core core) { 30 | this.core = core; 31 | } 32 | 33 | /** 34 | * 从队列订阅消息类型的计划任务 35 | * 36 | * @param schedule 计划任务DTO 37 | */ 38 | @RabbitHandler 39 | @RabbitListener(queues = "schedule.message") 40 | public void receiveMessage(Schedule schedule, Channel channel, Message message) throws IOException { 41 | switch (schedule.getMethod()) { 42 | case "addMessage" -> core.addMessage(schedule, channel, message); 43 | case "pushNotice" -> core.pushNotice(schedule, channel, message); 44 | case "sendSms" -> core.sendSms(schedule, channel, message); 45 | case "sendMail" -> core.sendMail(schedule, channel, message); 46 | default -> { 47 | } 48 | } 49 | } 50 | 51 | /** 52 | * 从队列订阅本地调用类型的计划任务 53 | * 54 | * @param schedule 计划任务DTO 55 | */ 56 | @RabbitHandler 57 | @RabbitListener(queues = "schedule.local") 58 | public void receiveLocalCall(Schedule schedule, Channel channel, Message message) throws IOException, URISyntaxException { 59 | core.localCall(schedule, channel, message); 60 | } 61 | 62 | /** 63 | * 从队列订阅远程调用类型的计划任务 64 | * 65 | * @param schedule 计划任务DTO 66 | */ 67 | @RabbitHandler 68 | @RabbitListener(queues = "schedule.remote") 69 | public void receiveRemoteCall(Schedule schedule, Channel channel, Message message) throws IOException { 70 | core.remoteCall(schedule, channel, message); 71 | } 72 | } -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/dto/SceneDto.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.dto; 2 | 3 | import com.insight.utils.pojo.base.BaseXo; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * @author 宣炳刚 9 | * @date 2019-08-28 10 | * @remark 消息场景 11 | */ 12 | public class SceneDto extends BaseXo { 13 | 14 | /** 15 | * UUID主键 16 | */ 17 | private Long id; 18 | 19 | /** 20 | * 场景编号 21 | */ 22 | private String code; 23 | 24 | /** 25 | * 默认发送类型:0.未定义;1.仅消息(0001);2.仅推送(0010);3.推送+消息(0011);4.仅短信(0100);8.仅邮件(1000) 26 | */ 27 | private Integer type; 28 | 29 | /** 30 | * 场景名称 31 | */ 32 | private String name; 33 | 34 | /** 35 | * 默认消息标题 36 | */ 37 | private String title; 38 | 39 | /** 40 | * 默认消息标签 41 | */ 42 | private String tag; 43 | 44 | /** 45 | * 默认消息参数 46 | */ 47 | private List param; 48 | 49 | /** 50 | * 备注 51 | */ 52 | private String remark; 53 | 54 | public Long getId() { 55 | return id; 56 | } 57 | 58 | public void setId(Long id) { 59 | this.id = id; 60 | } 61 | 62 | public String getCode() { 63 | return code; 64 | } 65 | 66 | public void setCode(String code) { 67 | this.code = code; 68 | } 69 | 70 | public Integer getType() { 71 | return type; 72 | } 73 | 74 | public void setType(Integer type) { 75 | this.type = type; 76 | } 77 | 78 | public String getName() { 79 | return name; 80 | } 81 | 82 | public void setName(String name) { 83 | this.name = name; 84 | } 85 | 86 | public String getTitle() { 87 | return title; 88 | } 89 | 90 | public void setTitle(String title) { 91 | this.title = title; 92 | } 93 | 94 | public String getTag() { 95 | return tag; 96 | } 97 | 98 | public void setTag(String tag) { 99 | this.tag = tag; 100 | } 101 | 102 | public List getParam() { 103 | return param; 104 | } 105 | 106 | public void setParam(List param) { 107 | this.param = param; 108 | } 109 | 110 | public String getRemark() { 111 | return remark; 112 | } 113 | 114 | public void setRemark(String remark) { 115 | this.remark = remark; 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/dto/ScheduleListDto.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.dto; 2 | 3 | import com.insight.utils.pojo.base.BaseXo; 4 | 5 | import java.time.LocalDateTime; 6 | 7 | /** 8 | * @author 宣炳刚 9 | * @date 2019/9/23 10 | * @remark 计划任务DTO 11 | */ 12 | public class ScheduleListDto extends BaseXo { 13 | 14 | /** 15 | * UUID主键 16 | */ 17 | private Long id; 18 | 19 | /** 20 | * 任务类型:0.消息;1.本地调用;2.远程调用 21 | */ 22 | private Integer type; 23 | 24 | /** 25 | * 调用方法 26 | */ 27 | private String method; 28 | 29 | /** 30 | * 任务执行时间 31 | */ 32 | private LocalDateTime taskTime; 33 | 34 | /** 35 | * 累计执行次数 36 | */ 37 | private Integer count; 38 | 39 | /** 40 | * 任务过期时间 41 | */ 42 | private LocalDateTime expireTime; 43 | 44 | /** 45 | * 是否失效 46 | */ 47 | private Boolean invalid; 48 | 49 | /** 50 | * 创建时间 51 | */ 52 | private LocalDateTime createdTime; 53 | 54 | public Long getId() { 55 | return id; 56 | } 57 | 58 | public void setId(Long id) { 59 | this.id = id; 60 | } 61 | 62 | public Integer getType() { 63 | return type; 64 | } 65 | 66 | public void setType(Integer type) { 67 | this.type = type; 68 | } 69 | 70 | public String getMethod() { 71 | return method; 72 | } 73 | 74 | public void setMethod(String method) { 75 | this.method = method; 76 | } 77 | 78 | public LocalDateTime getTaskTime() { 79 | return taskTime; 80 | } 81 | 82 | public void setTaskTime(LocalDateTime taskTime) { 83 | this.taskTime = taskTime; 84 | } 85 | 86 | public Integer getCount() { 87 | return count; 88 | } 89 | 90 | public void setCount(Integer count) { 91 | this.count = count; 92 | } 93 | 94 | public LocalDateTime getExpireTime() { 95 | return expireTime; 96 | } 97 | 98 | public void setExpireTime(LocalDateTime expireTime) { 99 | this.expireTime = expireTime; 100 | } 101 | 102 | public Boolean getInvalid() { 103 | return invalid; 104 | } 105 | 106 | public void setInvalid(Boolean invalid) { 107 | this.invalid = invalid; 108 | } 109 | 110 | public LocalDateTime getCreatedTime() { 111 | return createdTime; 112 | } 113 | 114 | public void setCreatedTime(LocalDateTime createdTime) { 115 | this.createdTime = createdTime; 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/dto/UserMessageDto.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.dto; 2 | 3 | import com.insight.utils.pojo.base.BaseXo; 4 | 5 | import java.time.LocalDateTime; 6 | 7 | /** 8 | * @author 宣炳刚 9 | * @date 2019/9/20 10 | * @remark 消息DTO 11 | */ 12 | public class UserMessageDto extends BaseXo { 13 | 14 | /** 15 | * UUID主键 16 | */ 17 | private Long id; 18 | 19 | /** 20 | * 消息标签 21 | */ 22 | private String tag; 23 | 24 | /** 25 | * 消息标题 26 | */ 27 | private String title; 28 | 29 | /** 30 | * 消息内容 31 | */ 32 | private String content; 33 | 34 | /** 35 | * 是否已读 36 | */ 37 | private Boolean read; 38 | 39 | /** 40 | * 是否广播消息 41 | */ 42 | private Boolean broadcast; 43 | 44 | /** 45 | * 创建人 46 | */ 47 | private String creator; 48 | 49 | /** 50 | * 创建人ID 51 | */ 52 | private Long creatorId; 53 | 54 | /** 55 | * 创建时间 56 | */ 57 | private LocalDateTime createdTime; 58 | 59 | public Long getId() { 60 | return id; 61 | } 62 | 63 | public void setId(Long id) { 64 | this.id = id; 65 | } 66 | 67 | public String getTag() { 68 | return tag; 69 | } 70 | 71 | public void setTag(String tag) { 72 | this.tag = tag; 73 | } 74 | 75 | public String getTitle() { 76 | return title; 77 | } 78 | 79 | public void setTitle(String title) { 80 | this.title = title; 81 | } 82 | 83 | public String getContent() { 84 | return content; 85 | } 86 | 87 | public void setContent(String content) { 88 | this.content = content; 89 | } 90 | 91 | public Boolean getRead() { 92 | return read; 93 | } 94 | 95 | public void setRead(Boolean read) { 96 | this.read = read; 97 | } 98 | 99 | public Boolean getBroadcast() { 100 | return broadcast; 101 | } 102 | 103 | public void setBroadcast(Boolean broadcast) { 104 | this.broadcast = broadcast; 105 | } 106 | 107 | public String getCreator() { 108 | return creator; 109 | } 110 | 111 | public void setCreator(String creator) { 112 | this.creator = creator; 113 | } 114 | 115 | public Long getCreatorId() { 116 | return creatorId; 117 | } 118 | 119 | public void setCreatorId(Long creatorId) { 120 | this.creatorId = creatorId; 121 | } 122 | 123 | public LocalDateTime getCreatedTime() { 124 | return createdTime; 125 | } 126 | 127 | public void setCreatedTime(LocalDateTime createdTime) { 128 | this.createdTime = createdTime; 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/dto/CustomMessage.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.dto; 2 | 3 | import com.insight.utils.Util; 4 | import com.insight.utils.pojo.base.BaseXo; 5 | import jakarta.validation.constraints.NotEmpty; 6 | import jakarta.validation.constraints.NotNull; 7 | 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | /** 12 | * @author 宣炳刚 13 | * @date 2019/9/20 14 | * @remark 自定义消息DTO 15 | */ 16 | public class CustomMessage extends BaseXo { 17 | 18 | /** 19 | * 消息标签 20 | */ 21 | @NotEmpty(message = "消息标签不能为空") 22 | private String tag; 23 | 24 | /** 25 | * 发送类型:0.未定义;1.仅消息(0001);2.仅推送(0010);3.推送+消息(0011);4.仅短信(0100);8.仅邮件(1000) 26 | */ 27 | @NotNull(message = "发送类型类型不能为空") 28 | private Integer type; 29 | 30 | /** 31 | * 接收人,多个接收人使用逗号分隔 32 | */ 33 | @NotEmpty(message = "接收人不能为空") 34 | private List receivers; 35 | 36 | /** 37 | * 消息标题 38 | */ 39 | @NotEmpty(message = "消息标题不能为空") 40 | private String title; 41 | 42 | /** 43 | * 消息内容 44 | */ 45 | @NotEmpty(message = "消息内容不能为空") 46 | private String content; 47 | 48 | /** 49 | * 发送参数 50 | */ 51 | private Map params; 52 | 53 | /** 54 | * 是否广播消息 55 | */ 56 | @NotNull(message = "广播设置不能为空") 57 | private Boolean broadcast; 58 | 59 | /** 60 | * 有效时长(分钟) 61 | */ 62 | private Integer expire; 63 | 64 | public String getTag() { 65 | return tag; 66 | } 67 | 68 | public void setTag(String tag) { 69 | this.tag = tag; 70 | } 71 | 72 | public Integer getType() { 73 | return type; 74 | } 75 | 76 | public void setType(Integer type) { 77 | this.type = type; 78 | } 79 | 80 | public List getReceivers() { 81 | return receivers; 82 | } 83 | 84 | public void setReceivers(String receivers) { 85 | this.receivers = Util.toStringList(receivers); 86 | } 87 | 88 | public String getTitle() { 89 | return title; 90 | } 91 | 92 | public void setTitle(String title) { 93 | this.title = title; 94 | } 95 | 96 | public String getContent() { 97 | return content; 98 | } 99 | 100 | public void setContent(String content) { 101 | this.content = content; 102 | } 103 | 104 | public Map getParams() { 105 | return params; 106 | } 107 | 108 | public void setParams(Map params) { 109 | this.params = params; 110 | } 111 | 112 | public Boolean getBroadcast() { 113 | return broadcast; 114 | } 115 | 116 | public void setBroadcast(Boolean broadcast) { 117 | this.broadcast = broadcast; 118 | } 119 | 120 | public Integer getExpire() { 121 | return expire; 122 | } 123 | 124 | public void setExpire(Integer expire) { 125 | this.expire = expire; 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/dto/SceneConfigDto.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.dto; 2 | 3 | import com.insight.utils.pojo.base.BaseXo; 4 | 5 | import java.time.LocalDateTime; 6 | 7 | /** 8 | * @author 宣炳刚 9 | * @date 2019-08-28 10 | * @remark 渠道消息模板 11 | */ 12 | public class SceneConfigDto extends BaseXo { 13 | 14 | /** 15 | * UUID主键 16 | */ 17 | private Long id; 18 | 19 | /** 20 | * 租户ID 21 | */ 22 | private Long tenantId; 23 | 24 | /** 25 | * 应用ID 26 | */ 27 | private Long appId; 28 | 29 | /** 30 | * 应用名称 31 | */ 32 | private String appName; 33 | 34 | /** 35 | * 消息内容 36 | */ 37 | private String content; 38 | 39 | /** 40 | * 签名 41 | */ 42 | private String sign; 43 | 44 | /** 45 | * 消息有效时长(小时) 46 | */ 47 | private Integer expire; 48 | 49 | /** 50 | * 备注 51 | */ 52 | private String remark; 53 | 54 | /** 55 | * 创建人 56 | */ 57 | private String creator; 58 | 59 | /** 60 | * 创建时间 61 | */ 62 | private LocalDateTime createdTime; 63 | 64 | public Long getId() { 65 | return id; 66 | } 67 | 68 | public void setId(Long id) { 69 | this.id = id; 70 | } 71 | 72 | public Long getTenantId() { 73 | return tenantId; 74 | } 75 | 76 | public void setTenantId(Long tenantId) { 77 | this.tenantId = tenantId; 78 | } 79 | 80 | public Long getAppId() { 81 | return appId; 82 | } 83 | 84 | public void setAppId(Long appId) { 85 | this.appId = appId; 86 | } 87 | 88 | public String getAppName() { 89 | return appName; 90 | } 91 | 92 | public void setAppName(String appName) { 93 | this.appName = appName; 94 | } 95 | 96 | public String getContent() { 97 | return content; 98 | } 99 | 100 | public void setContent(String content) { 101 | this.content = content; 102 | } 103 | 104 | public String getSign() { 105 | return sign; 106 | } 107 | 108 | public void setSign(String sign) { 109 | this.sign = sign; 110 | } 111 | 112 | public Integer getExpire() { 113 | return expire; 114 | } 115 | 116 | public void setExpire(Integer expire) { 117 | this.expire = expire; 118 | } 119 | 120 | public String getRemark() { 121 | return remark; 122 | } 123 | 124 | public void setRemark(String remark) { 125 | this.remark = remark; 126 | } 127 | 128 | public String getCreator() { 129 | return creator; 130 | } 131 | 132 | public void setCreator(String creator) { 133 | this.creator = creator; 134 | } 135 | 136 | public LocalDateTime getCreatedTime() { 137 | return createdTime; 138 | } 139 | 140 | public void setCreatedTime(LocalDateTime createdTime) { 141 | this.createdTime = createdTime; 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/entity/Scene.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.entity; 2 | 3 | import com.insight.utils.pojo.base.BaseXo; 4 | import jakarta.validation.constraints.NotEmpty; 5 | import jakarta.validation.constraints.NotNull; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * @author 宣炳刚 11 | * @date 2019-08-28 12 | * @remark 消息场景 13 | */ 14 | public class Scene extends BaseXo { 15 | 16 | /** 17 | * UUID主键 18 | */ 19 | private Long id; 20 | 21 | /** 22 | * 场景编号 23 | */ 24 | @NotEmpty(message = "消息场景编码不能为空") 25 | private String code; 26 | 27 | /** 28 | * 默认发送类型:0.未定义;1.仅消息(0001);2.仅推送(0010);3.推送+消息(0011);4.仅短信(0100);8.仅邮件(1000) 29 | */ 30 | @NotNull(message = "发送类型不能为空") 31 | private Integer type; 32 | 33 | /** 34 | * 场景名称 35 | */ 36 | @NotEmpty(message = "消息场景名称不能为空") 37 | private String name; 38 | 39 | /** 40 | * 默认消息标题 41 | */ 42 | private String title; 43 | 44 | /** 45 | * 默认消息标签 46 | */ 47 | private String tag; 48 | 49 | /** 50 | * 默认消息参数 51 | */ 52 | private List param; 53 | 54 | /** 55 | * 备注 56 | */ 57 | private String remark; 58 | 59 | /** 60 | * 创建人 61 | */ 62 | private String creator; 63 | 64 | /** 65 | * 创建人ID 66 | */ 67 | private Long creatorId; 68 | 69 | public Long getId() { 70 | return id; 71 | } 72 | 73 | public void setId(Long id) { 74 | this.id = id; 75 | } 76 | 77 | public String getCode() { 78 | return code; 79 | } 80 | 81 | public void setCode(String code) { 82 | this.code = code; 83 | } 84 | 85 | public Integer getType() { 86 | return type; 87 | } 88 | 89 | public void setType(Integer type) { 90 | this.type = type; 91 | } 92 | 93 | public String getName() { 94 | return name; 95 | } 96 | 97 | public void setName(String name) { 98 | this.name = name; 99 | } 100 | 101 | public String getTitle() { 102 | return title; 103 | } 104 | 105 | public void setTitle(String title) { 106 | this.title = title; 107 | } 108 | 109 | public String getTag() { 110 | return tag; 111 | } 112 | 113 | public void setTag(String tag) { 114 | this.tag = tag; 115 | } 116 | 117 | public List getParam() { 118 | return param; 119 | } 120 | 121 | public void setParam(List param) { 122 | this.param = param; 123 | } 124 | 125 | public String getRemark() { 126 | return remark; 127 | } 128 | 129 | public void setRemark(String remark) { 130 | this.remark = remark; 131 | } 132 | 133 | public String getCreator() { 134 | return creator; 135 | } 136 | 137 | public void setCreator(String creator) { 138 | this.creator = creator; 139 | } 140 | 141 | public Long getCreatorId() { 142 | return creatorId; 143 | } 144 | 145 | public void setCreatorId(Long creatorId) { 146 | this.creatorId = creatorId; 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/ScheduleTask.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common; 2 | 3 | import com.insight.common.message.common.client.RabbitClient; 4 | import com.insight.common.message.common.dto.ScheduleCall; 5 | import com.insight.common.message.common.mapper.MessageMapper; 6 | import com.insight.utils.Util; 7 | import com.insight.utils.pojo.message.InsightMessage; 8 | import com.insight.utils.pojo.message.Schedule; 9 | import com.insight.utils.redis.LockHandler; 10 | import com.insight.utils.redis.LockParam; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | import org.springframework.scheduling.annotation.Scheduled; 14 | import org.springframework.stereotype.Component; 15 | 16 | import java.util.List; 17 | 18 | /** 19 | * @author 宣炳刚 20 | * @date 2019/9/24 21 | * @remark 计划任务执行类 22 | */ 23 | @Component 24 | public class ScheduleTask { 25 | private final Logger logger = LoggerFactory.getLogger(this.getClass()); 26 | private final LockHandler handler = new LockHandler(); 27 | private final LockParam param = new LockParam("Message:Schedule"); 28 | private final MessageMapper mapper; 29 | 30 | /** 31 | * 构造方法 32 | * 33 | * @param mapper MessageMapper 34 | */ 35 | public ScheduleTask(MessageMapper mapper) { 36 | this.mapper = mapper; 37 | } 38 | 39 | /** 40 | * 每间隔10秒执行一次计划任务 41 | */ 42 | @Scheduled(fixedDelay = 10000) 43 | public void execute() { 44 | param.setValue(Util.uuid()); 45 | if (handler.tryLock(param)) { 46 | try { 47 | // 执行消息类型的计划任务 48 | List> messageSchedules = mapper.getMessageSchedule(); 49 | messageSchedules.forEach(this::messageTask); 50 | 51 | // 执行本地调用类型的计划任务 52 | List> localSchedules = mapper.getLocalSchedule(); 53 | localSchedules.forEach(this::localCallTask); 54 | 55 | // 执行远程调用类型的计划任务 56 | List> rpcSchedules = mapper.getRpcSchedule(); 57 | rpcSchedules.forEach(this::rpcCallTask); 58 | } catch (Exception ex) { 59 | logger.error("计划任务发生错误! 异常信息为: {}", ex.getMessage()); 60 | } finally { 61 | handler.releaseLock(param); 62 | } 63 | } 64 | } 65 | 66 | /** 67 | * 执行消息类型的计划任务 68 | * 69 | * @param schedule 计划任务DTO 70 | */ 71 | private void messageTask(Schedule schedule) { 72 | mapper.deleteSchedule(schedule.getId()); 73 | RabbitClient.sendTopic("schedule.message", schedule); 74 | } 75 | 76 | /** 77 | * 执行本地调用类型的计划任务 78 | * 79 | * @param schedule 计划任务DTO 80 | */ 81 | private void localCallTask(Schedule schedule) { 82 | mapper.deleteSchedule(schedule.getId()); 83 | RabbitClient.sendTopic("schedule.local", schedule); 84 | } 85 | 86 | /** 87 | * 执行远程调用类型的计划任务 88 | * 89 | * @param schedule 计划任务DTO 90 | */ 91 | private void rpcCallTask(Schedule schedule) { 92 | mapper.deleteSchedule(schedule.getId()); 93 | RabbitClient.sendTopic("schedule.remote", schedule); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/MessageDal.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common; 2 | 3 | import com.insight.common.message.common.entity.PushMessage; 4 | import com.insight.common.message.common.entity.SubscribeMessage; 5 | import com.insight.common.message.common.mapper.MessageMapper; 6 | import com.insight.utils.SnowflakeCreator; 7 | import com.insight.utils.pojo.message.InsightMessage; 8 | import com.insight.utils.pojo.message.Schedule; 9 | import org.springframework.scheduling.annotation.Async; 10 | import org.springframework.stereotype.Component; 11 | import org.springframework.transaction.annotation.Transactional; 12 | 13 | import java.time.LocalDateTime; 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | 17 | 18 | /** 19 | * @author 宣炳刚 20 | * @date 2019/9/23 21 | * @remark 消息数据处理DAL 22 | */ 23 | @Component 24 | public class MessageDal { 25 | private final MessageMapper mapper; 26 | private final SnowflakeCreator creator; 27 | 28 | /** 29 | * 构造方法 30 | * 31 | * @param mapper MessageMapper 32 | * @param creator 雪花算法ID生成器 33 | */ 34 | public MessageDal(MessageMapper mapper, SnowflakeCreator creator) { 35 | this.mapper = mapper; 36 | this.creator = creator; 37 | } 38 | 39 | /** 40 | * 保存消息到数据库 41 | * 42 | * @param message 消息DTO 43 | */ 44 | @Transactional 45 | public void addMessage(InsightMessage message) { 46 | Long id = message.getId(); 47 | if (id == null) { 48 | message.setId(creator.nextId(0)); 49 | } 50 | 51 | message.setCreatedTime(LocalDateTime.now()); 52 | mapper.addMessage(message); 53 | if (message.getBroadcast()) { 54 | return; 55 | } 56 | 57 | // 构造本地消息推送列表并写入数据库 58 | List pushList = new ArrayList<>(); 59 | message.getReceivers().forEach(i -> { 60 | PushMessage push = new PushMessage(); 61 | push.setMessageId(message.getId()); 62 | push.setUserId(i); 63 | push.setRead(false); 64 | pushList.add(push); 65 | }); 66 | mapper.pushMessage(pushList); 67 | } 68 | 69 | /** 70 | * 设置消息为已读 71 | * 72 | * @param messageId 消息ID 73 | * @param userId 用户ID 74 | * @param isBroadcast 是否广播消息 75 | */ 76 | @Async 77 | public void readMessage(Long messageId, Long userId, boolean isBroadcast) { 78 | if (isBroadcast) { 79 | SubscribeMessage subscribe = new SubscribeMessage(); 80 | subscribe.setMessageId(messageId); 81 | subscribe.setUserId(userId); 82 | subscribe.setCreatedTime(LocalDateTime.now()); 83 | 84 | mapper.subscribeMessage(subscribe); 85 | } else { 86 | mapper.readMessage(messageId, userId); 87 | } 88 | } 89 | 90 | /** 91 | * 保存计划任务到数据库 92 | * 93 | * @param schedule 计划任务DTO 94 | */ 95 | public void addSchedule(Schedule schedule) { 96 | if (schedule.getExpireTime() == null) { 97 | schedule.setExpireTime(LocalDateTime.now().plusMinutes(60)); 98 | } 99 | 100 | mapper.addSchedule(schedule); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/entity/SceneConfig.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.entity; 2 | 3 | import com.insight.utils.pojo.base.BaseXo; 4 | import jakarta.validation.constraints.NotEmpty; 5 | 6 | /** 7 | * @author 宣炳刚 8 | * @date 2019-08-28 9 | * @remark 渠道消息模板 10 | */ 11 | public class SceneConfig extends BaseXo { 12 | 13 | /** 14 | * UUID主键 15 | */ 16 | private Long id; 17 | 18 | /** 19 | * 租户ID 20 | */ 21 | private Long tenantId; 22 | 23 | /** 24 | * 场景ID 25 | */ 26 | private Long sceneId; 27 | 28 | /** 29 | * 应用ID 30 | */ 31 | private Long appId; 32 | 33 | /** 34 | * 应用名称 35 | */ 36 | private String appName; 37 | 38 | /** 39 | * 消息内容 40 | */ 41 | @NotEmpty(message = "消息内容不能为空") 42 | private String content; 43 | 44 | /** 45 | * 签名 46 | */ 47 | private String sign; 48 | 49 | /** 50 | * 消息有效时长(小时) 51 | */ 52 | private Integer expire; 53 | 54 | /** 55 | * 备注 56 | */ 57 | private String remark; 58 | 59 | /** 60 | * 创建人 61 | */ 62 | private String creator; 63 | 64 | /** 65 | * 创建人ID 66 | */ 67 | private Long creatorId; 68 | 69 | public Long getId() { 70 | return id; 71 | } 72 | 73 | public void setId(Long id) { 74 | this.id = id; 75 | } 76 | 77 | public Long getTenantId() { 78 | return tenantId; 79 | } 80 | 81 | public void setTenantId(Long tenantId) { 82 | this.tenantId = tenantId; 83 | } 84 | 85 | public Long getSceneId() { 86 | return sceneId; 87 | } 88 | 89 | public void setSceneId(Long sceneId) { 90 | this.sceneId = sceneId; 91 | } 92 | 93 | public Long getAppId() { 94 | return appId; 95 | } 96 | 97 | public void setAppId(Long appId) { 98 | this.appId = appId; 99 | } 100 | 101 | public String getAppName() { 102 | return appName; 103 | } 104 | 105 | public void setAppName(String appName) { 106 | this.appName = appName; 107 | } 108 | 109 | public String getContent() { 110 | return content; 111 | } 112 | 113 | public void setContent(String content) { 114 | this.content = content; 115 | } 116 | 117 | public String getSign() { 118 | return sign; 119 | } 120 | 121 | public void setSign(String sign) { 122 | this.sign = sign; 123 | } 124 | 125 | public Integer getExpire() { 126 | return expire == null ? 1 : expire; 127 | } 128 | 129 | public void setExpire(Integer expire) { 130 | this.expire = expire; 131 | } 132 | 133 | public String getRemark() { 134 | return remark; 135 | } 136 | 137 | public void setRemark(String remark) { 138 | this.remark = remark; 139 | } 140 | 141 | public String getCreator() { 142 | return creator; 143 | } 144 | 145 | public void setCreator(String creator) { 146 | this.creator = creator; 147 | } 148 | 149 | public Long getCreatorId() { 150 | return creatorId; 151 | } 152 | 153 | public void setCreatorId(Long creatorId) { 154 | this.creatorId = creatorId; 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/message/MessageController.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.message; 2 | 3 | import com.insight.common.message.common.dto.CustomMessage; 4 | import com.insight.common.message.common.dto.NormalMessage; 5 | import com.insight.common.message.common.dto.UserMessageDto; 6 | import com.insight.utils.Json; 7 | import com.insight.utils.pojo.auth.LoginInfo; 8 | import com.insight.utils.pojo.base.BusinessException; 9 | import com.insight.utils.pojo.base.Reply; 10 | import com.insight.utils.pojo.base.Search; 11 | import com.insight.utils.pojo.message.SmsCode; 12 | import jakarta.validation.Valid; 13 | import org.springframework.web.bind.annotation.*; 14 | 15 | /** 16 | * @author 宣炳刚 17 | * @date 2019-08-28 18 | * @remark 短信服务控制器 19 | */ 20 | @RestController 21 | @RequestMapping("/common/message") 22 | public class MessageController { 23 | private final MessageService service; 24 | 25 | /** 26 | * 构造方法 27 | * 28 | * @param service MessageService 29 | */ 30 | public MessageController(MessageService service) { 31 | this.service = service; 32 | } 33 | 34 | /** 35 | * 绑定手机号 36 | * 37 | * @param mobile 手机号 38 | */ 39 | @GetMapping("/v1.0/codes") 40 | public void verifyMobile(@RequestHeader("loginInfo") String loginInfo, @RequestParam String mobile) { 41 | LoginInfo info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 42 | 43 | var dto = new SmsCode(); 44 | dto.setMobile(mobile); 45 | dto.setType(4); 46 | service.seedSmsCode(dto); 47 | } 48 | 49 | /** 50 | * 发送短信验证码 51 | * 52 | * @param dto 短信DTO 53 | */ 54 | @PostMapping("/v1.0/codes") 55 | public void seedCode(@Valid @RequestBody SmsCode dto) { 56 | if (dto.getType() < 0 || dto.getType() > 3) { 57 | throw new BusinessException("无效的短信类型"); 58 | } 59 | 60 | service.seedSmsCode(dto); 61 | } 62 | 63 | /** 64 | * 验证短信验证码 65 | * 66 | * @param key 验证参数,MD5(type + mobile + code) 67 | * @param isCheck 是否检验模式:true.检验模式,验证后验证码不失效;false.验证模式,验证后验证码失效 68 | * @return Reply 69 | */ 70 | @GetMapping("/v1.0/codes/{key}/status") 71 | public String verifySmsCode(@PathVariable String key, @RequestParam(defaultValue = "true") Boolean isCheck) { 72 | if (key == null || key.isEmpty()) { 73 | throw new BusinessException("无效的验证参数"); 74 | } 75 | 76 | return service.verifySmsCode(key, isCheck); 77 | } 78 | 79 | /** 80 | * 发送送标准消息 81 | * 82 | * @param loginInfo 用户关键信息 83 | * @param dto 标准信息DTO 84 | */ 85 | @PostMapping("/v1.0/messages") 86 | public void sendNormalMessage(@RequestHeader("loginInfo") String loginInfo, @Valid @RequestBody NormalMessage dto) { 87 | LoginInfo info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 88 | service.sendNormalMessage(info, dto); 89 | } 90 | 91 | /** 92 | * 发送自定义消息 93 | * 94 | * @param loginInfo 用户关键信息 95 | * @param dto 标准信息DTO 96 | */ 97 | @PostMapping("/v1.0/customs") 98 | public void sendCustomMessage(@RequestHeader("loginInfo") String loginInfo, @Valid @RequestBody CustomMessage dto) { 99 | LoginInfo info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 100 | service.sendCustomMessage(info, dto); 101 | } 102 | 103 | /** 104 | * 获取用户消息列表 105 | * 106 | * @param loginInfo 用户关键信息 107 | * @param search 查询实体类 108 | * @return Reply 109 | */ 110 | @GetMapping("/v1.0/messages") 111 | public Reply getUserMessages(@RequestHeader("loginInfo") String loginInfo, Search search) { 112 | LoginInfo info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 113 | return service.getUserMessages(info, search); 114 | } 115 | 116 | /** 117 | * 获取用户消息详情 118 | * 119 | * @param loginInfo 用户关键信息 120 | * @param id 消息ID 121 | * @return Reply 122 | */ 123 | @GetMapping("/v1.0/messages/{id}") 124 | public UserMessageDto getUserMessage(@RequestHeader("loginInfo") String loginInfo, @PathVariable Long id) { 125 | LoginInfo info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 126 | return service.getUserMessage(id, info.getId()); 127 | } 128 | 129 | /** 130 | * 删除用户消息 131 | * 132 | * @param loginInfo 用户关键信息 133 | * @param id 消息ID 134 | */ 135 | @DeleteMapping("/v1.0/messages/{id}") 136 | public void deleteUserMessage(@RequestHeader("loginInfo") String loginInfo, @PathVariable Long id) { 137 | LoginInfo info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 138 | service.deleteUserMessage(id, info.getId()); 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/schedule/ScheduleController.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.schedule; 2 | 3 | import com.insight.common.message.common.client.LogClient; 4 | import com.insight.common.message.common.client.LogServiceClient; 5 | import com.insight.common.message.common.entity.OperateType; 6 | import com.insight.utils.Json; 7 | import com.insight.utils.pojo.auth.LoginInfo; 8 | import com.insight.utils.pojo.base.Reply; 9 | import com.insight.utils.pojo.base.Search; 10 | import com.insight.utils.pojo.message.Schedule; 11 | import jakarta.validation.Valid; 12 | import org.springframework.web.bind.annotation.*; 13 | 14 | /** 15 | * @author 宣炳刚 16 | * @date 2019-08-28 17 | * @remark 计划任务服务控制器 18 | */ 19 | @RestController 20 | @RequestMapping("/common/message") 21 | public class ScheduleController { 22 | private static final String BUSINESS = "Schedule"; 23 | private final LogServiceClient client; 24 | private final ScheduleService service; 25 | 26 | /** 27 | * 构造方法 28 | * 29 | * @param client Feign客户端 30 | * @param service 注入Service 31 | */ 32 | public ScheduleController(LogServiceClient client, ScheduleService service) { 33 | this.client = client; 34 | this.service = service; 35 | } 36 | 37 | /** 38 | * 获取计划任务列表 39 | * 40 | * @param search 查询实体类 41 | * @return Reply 42 | */ 43 | @GetMapping("/v1.0/schedules") 44 | public Reply getSchedules(Search search) { 45 | return service.getSchedules(search); 46 | } 47 | 48 | /** 49 | * 获取计划任务详情 50 | * 51 | * @param id 计划任务ID 52 | * @return Reply 53 | */ 54 | @GetMapping("/v1.0/schedules/{id}") 55 | public Schedule getSchedule(@PathVariable Long id) { 56 | return service.getSchedule(id); 57 | } 58 | 59 | /** 60 | * 新增计划任务 61 | * 62 | * @param dto 计划任务DTO 63 | * @return Reply 64 | */ 65 | @PostMapping("/v1.0/schedules") 66 | public Long newSchedule(@Valid @RequestBody Schedule dto) { 67 | return service.newSchedule(dto); 68 | } 69 | 70 | /** 71 | * 立即执行计划任务 72 | * 73 | * @param loginInfo 用户关键信息 74 | * @param id 计划任务ID 75 | */ 76 | @PutMapping("/v1.0/schedules/{id}") 77 | public void executeSchedule(@RequestHeader("loginInfo") String loginInfo, @PathVariable Long id) { 78 | LoginInfo info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 79 | 80 | service.executeSchedule(info, id); 81 | LogClient.writeLog(info, BUSINESS, OperateType.EDIT, id,null); 82 | } 83 | 84 | /** 85 | * 删除计划任务 86 | * 87 | * @param loginInfo 用户关键信息 88 | * @param id 计划任务ID 89 | */ 90 | @DeleteMapping("/v1.0/schedules/{id}") 91 | public void deleteSchedule(@RequestHeader("loginInfo") String loginInfo, @PathVariable Long id) { 92 | LoginInfo info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 93 | 94 | service.deleteSchedule(info, id); 95 | LogClient.writeLog(info, BUSINESS, OperateType.DELETE, id, null); 96 | } 97 | 98 | /** 99 | * 禁用计划任务 100 | * 101 | * @param loginInfo 用户关键信息 102 | * @param id 计划任务ID 103 | */ 104 | @PutMapping("/v1.0/schedules/{id}/disable") 105 | public void disableSchedule(@RequestHeader("loginInfo") String loginInfo, @PathVariable Long id) { 106 | LoginInfo info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 107 | 108 | service.changeScheduleStatus(info, id, true); 109 | LogClient.writeLog(info, BUSINESS, OperateType.DISABLE, id, null); 110 | } 111 | 112 | /** 113 | * 启用计划任务 114 | * 115 | * @param loginInfo 用户关键信息 116 | * @param id 计划任务ID 117 | */ 118 | @PutMapping("/v1.0/schedules/{id}/enable") 119 | public void enableSchedule(@RequestHeader("loginInfo") String loginInfo, @PathVariable Long id) { 120 | LoginInfo info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 121 | 122 | service.changeScheduleStatus(info, id, false); 123 | LogClient.writeLog(info, BUSINESS, OperateType.ENABLE, id, null); 124 | } 125 | 126 | /** 127 | * 查询日志 128 | * 129 | * @param loginInfo 用户登录信息 130 | * @param search 查询条件 131 | * @return 日志集合 132 | */ 133 | @GetMapping("/v1.0/schedules/{id}/logs") 134 | public Reply getAirportLogs(@RequestHeader("loginInfo") String loginInfo, @PathVariable Long id, Search search) { 135 | var info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 136 | return client.getLogs(id, "Schedule", search.getKeyword()); 137 | } 138 | 139 | /** 140 | * 获取日志 141 | * 142 | * @param loginInfo 用户登录信息 143 | * @param id 日志ID 144 | * @return 日志VO 145 | */ 146 | @GetMapping("/v1.0/schedules/logs/{id}") 147 | public Reply getAirportLog(@RequestHeader("loginInfo") String loginInfo, @PathVariable Long id) { 148 | var info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 149 | return client.getLog(id); 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/mapper/SceneMapper.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.mapper; 2 | 3 | import com.insight.common.message.common.dto.SceneConfigDto; 4 | import com.insight.common.message.common.dto.SceneDto; 5 | import com.insight.common.message.common.entity.Scene; 6 | import com.insight.common.message.common.entity.SceneConfig; 7 | import com.insight.utils.pojo.base.ArrayTypeHandler; 8 | import com.insight.utils.pojo.base.Search; 9 | import org.apache.ibatis.annotations.*; 10 | 11 | import java.util.List; 12 | 13 | /** 14 | * @author 宣炳刚 15 | * @date 2019/9/17 16 | * @remark 场景DAL 17 | */ 18 | @Mapper 19 | public interface SceneMapper { 20 | 21 | /** 22 | * 获取消息场景列表 23 | * 24 | * @param search 查询DTO 25 | * @return 消息场景列表 26 | */ 27 | @Results({@Result(property = "param", column = "param", javaType = String.class, typeHandler = ArrayTypeHandler.class)}) 28 | @Select("") 30 | List getScenes(Search search); 31 | 32 | /** 33 | * 获取场景详情 34 | * 35 | * @param id 消息场景ID 36 | * @return 消息场景DTO 37 | */ 38 | @Results({@Result(property = "params", column = "params", javaType = String.class, typeHandler = ArrayTypeHandler.class)}) 39 | @Select("select * from ims_scene where id = #{id};") 40 | Scene getScene(Long id); 41 | 42 | /** 43 | * 获取指定编码的场景数量 44 | * 45 | * @param id 消息场景ID 46 | * @param code 消息场景编码 47 | * @return 场景数量 48 | */ 49 | @Select("select count(*) from ims_scene where id != #{id} and code = #{code};") 50 | int getSceneCount(@Param("id") Long id, @Param("code") String code); 51 | 52 | /** 53 | * 新增消息场景 54 | * 55 | * @param scene 消息场景DTO 56 | */ 57 | @Insert("insert ims_scene(id, `code`, type, `name`, title, tag, `param`, remark, creator, creator_id, created_time) values " + 58 | "(#{id}, #{code}, #{type}, #{name}, #{title}, #{tag}, #{param, typeHandler = com.insight.utils.pojo.base.ArrayTypeHandler}, " + 59 | "#{remark}, #{creator}, #{creatorId}, now());") 60 | void addScene(Scene scene); 61 | 62 | /** 63 | * 更新消息场景 64 | * 65 | * @param scene 消息场景DTO 66 | */ 67 | @Update("update ims_scene set `code` = #{code}, type = #{type}, `name` = #{name}, title = #{title}, tag = #{tag}, " + 68 | "`param` = #{param, typeHandler = com.insight.utils.pojo.base.ArrayTypeHandler}, remark = #{remark} where id = #{id};") 69 | void editScene(Scene scene); 70 | 71 | /** 72 | * 删除消息场景 73 | * 74 | * @param id 消息场景ID 75 | */ 76 | @Delete("delete s, c from ims_scene s left join ims_scene_config c on c.scene_id = s.id where s.id = #{id};") 77 | void deleteScene(Long id); 78 | 79 | /** 80 | * 获取场景配置列表 81 | * 82 | * @param tenantId 租户ID 83 | * @param sceneId 场景ID 84 | * @return 场景模板配置列表 85 | */ 86 | @Select("select * from ims_scene_config where scene_id = #{sceneId} and (tenant_id is null or tenant_id = #{tenantId}) order by created_time;") 87 | List getSceneConfigs(@Param("tenantId") Long tenantId, @Param("sceneId") Long sceneId); 88 | 89 | /** 90 | * 获取场景配置详情 91 | * 92 | * @param id 配置ID 93 | * @return 配置详情 94 | */ 95 | @Select("select * from ims_scene_config where id = #{id};") 96 | SceneConfig getSceneConfig(Long id); 97 | 98 | /** 99 | * 获取已存在配置数量 100 | * 101 | * @param id 场景ID 102 | * @param tenantId 租户ID 103 | * @param appId 应用ID 104 | * @return 消息模板 105 | */ 106 | @Select("") 112 | int getConfigCount(Long id, Long tenantId, Long appId); 113 | 114 | /** 115 | * 新增场景配置 116 | * 117 | * @param config 场景配置DTO 118 | */ 119 | @Insert("insert ims_scene_config(id, tenant_id, scene_id, app_id, app_name, content, sign, expire, creator, creator_id, created_time) VALUES " + 120 | "(#{id}, #{tenantId}, #{sceneId}, #{appId}, #{appName}, #{content}, #{sign}, #{expire}, #{creator}, #{creatorId}, now());") 121 | void addSceneConfig(SceneConfig config); 122 | 123 | /** 124 | * 编辑场景配置 125 | * 126 | * @param config 场景配置DTO 127 | */ 128 | @Update("update ims_scene_config set app_id = #{appId}, app_name = #{appName}, content = #{content}, sign = #{sign}, expire = #{expire} where id = #{id};") 129 | void updateSceneConfig(SceneConfig config); 130 | 131 | /** 132 | * 删除场景配置 133 | * 134 | * @param id 场景配置ID 135 | */ 136 | @Delete("delete from ims_scene_config where id = #{id};") 137 | void deleteSceneConfig(Long id); 138 | } 139 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/schedule/ScheduleServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.schedule; 2 | 3 | import com.github.pagehelper.PageHelper; 4 | import com.insight.common.message.common.dto.ScheduleCall; 5 | import com.insight.common.message.common.mapper.MessageMapper; 6 | import com.insight.utils.Json; 7 | import com.insight.utils.ReplyHelper; 8 | import com.insight.utils.SnowflakeCreator; 9 | import com.insight.utils.pojo.auth.LoginInfo; 10 | import com.insight.utils.pojo.base.BusinessException; 11 | import com.insight.utils.pojo.base.Reply; 12 | import com.insight.utils.pojo.base.Search; 13 | import com.insight.utils.pojo.message.InsightMessage; 14 | import com.insight.utils.pojo.message.Schedule; 15 | import org.springframework.stereotype.Service; 16 | 17 | import java.time.LocalDateTime; 18 | import java.util.ArrayList; 19 | import java.util.List; 20 | 21 | /** 22 | * @author 宣炳刚 23 | * @date 2019-08-28 24 | * @remark 计划任务服务 25 | */ 26 | @Service 27 | public class ScheduleServiceImpl implements ScheduleService { 28 | private static final List MATCH_LIST = new ArrayList<>(); 29 | 30 | static { 31 | MATCH_LIST.add("addMessage"); 32 | MATCH_LIST.add("pushNotice"); 33 | MATCH_LIST.add("sendSms"); 34 | MATCH_LIST.add("sendMail"); 35 | } 36 | 37 | private final SnowflakeCreator creator; 38 | private final MessageMapper mapper; 39 | 40 | /** 41 | * 构造方法 42 | * 43 | * @param creator 雪花算法ID生成器 44 | * @param mapper MessageMapper 45 | */ 46 | public ScheduleServiceImpl(SnowflakeCreator creator, MessageMapper mapper) { 47 | this.creator = creator; 48 | this.mapper = mapper; 49 | } 50 | 51 | /** 52 | * 获取计划任务列表 53 | * 54 | * @param search 查询实体类 55 | * @return Reply 56 | */ 57 | @Override 58 | public Reply getSchedules(Search search) { 59 | try (var page = PageHelper.startPage(search.getPageNum(), search.getPageSize()).setOrderBy(search.getOrderBy()) 60 | .doSelectPage(() -> mapper.getSchedules(search))) { 61 | var total = page.getTotal(); 62 | return total > 0 ? ReplyHelper.success(page.getResult(), total) : ReplyHelper.resultIsEmpty(); 63 | } 64 | } 65 | 66 | /** 67 | * 获取计划任务详情 68 | * 69 | * @param id 计划任务ID 70 | * @return Reply 71 | */ 72 | @Override 73 | public Schedule getSchedule(Long id) { 74 | Schedule schedule = mapper.getSchedule(id); 75 | if (schedule == null) { 76 | throw new BusinessException("ID不存在,未读取数据"); 77 | } 78 | 79 | return schedule; 80 | } 81 | 82 | /** 83 | * 新增计划任务 84 | * 85 | * @param dto 计划任务DTO 86 | * @return Reply 87 | */ 88 | @Override 89 | public Long newSchedule(Schedule dto) { 90 | if (dto.getType() > 0) { 91 | ScheduleCall call = Json.clone(dto.getContent(), ScheduleCall.class); 92 | if (call == null || call.getMethod() == null || call.getService() == null || call.getUrl() == null) { 93 | throw new BusinessException(("无效参数")); 94 | } 95 | } else { 96 | boolean match = MATCH_LIST.stream().anyMatch(i -> i.equals(dto.getMethod())); 97 | if (!match) { 98 | throw new BusinessException("调用方法错误"); 99 | } 100 | 101 | InsightMessage message = Json.clone(dto.getContent(), InsightMessage.class); 102 | if (message == null) { 103 | throw new BusinessException(("无效参数")); 104 | } 105 | 106 | if (dto.getExpireTime() == null) { 107 | dto.setExpireTime(LocalDateTime.now().plusMinutes(message.getExpire())); 108 | } 109 | } 110 | 111 | Long id = creator.nextId(3); 112 | dto.setId(id); 113 | if (dto.getTaskTime() == null) { 114 | dto.setTaskTime(LocalDateTime.now().plusSeconds(10)); 115 | } 116 | 117 | if (dto.getExpireTime() == null) { 118 | dto.setExpireTime(LocalDateTime.now().plusMinutes(60)); 119 | } 120 | 121 | dto.setCount(0); 122 | dto.setInvalid(false); 123 | dto.setCreatedTime(LocalDateTime.now()); 124 | 125 | mapper.addSchedule(dto); 126 | return id; 127 | } 128 | 129 | /** 130 | * 立即执行计划任务 131 | * 132 | * @param info 用户关键信息 133 | * @param id 计划任务ID 134 | */ 135 | @Override 136 | public void executeSchedule(LoginInfo info, Long id) { 137 | Schedule schedule = mapper.getSchedule(id); 138 | if (schedule == null) { 139 | throw new BusinessException("ID不存在,未更新数据"); 140 | } 141 | 142 | mapper.editSchedule(id); 143 | } 144 | 145 | /** 146 | * 删除计划任务 147 | * 148 | * @param info 用户关键信息 149 | * @param id 计划任务ID 150 | */ 151 | @Override 152 | public void deleteSchedule(LoginInfo info, Long id) { 153 | Schedule schedule = mapper.getSchedule(id); 154 | if (schedule == null) { 155 | throw new BusinessException("ID不存在,未更新数据"); 156 | } 157 | 158 | mapper.deleteSchedule(id); 159 | } 160 | 161 | /** 162 | * 禁用/启用计划任务 163 | * 164 | * @param info 用户关键信息 165 | * @param id 计划任务ID 166 | * @param status 禁用/启用状态 167 | */ 168 | @Override 169 | public void changeScheduleStatus(LoginInfo info, Long id, boolean status) { 170 | Schedule schedule = mapper.getSchedule(id); 171 | if (schedule == null) { 172 | throw new BusinessException("ID不存在,未更新数据"); 173 | } 174 | 175 | mapper.changeScheduleStatus(id, status); 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 3.3.7 9 | 10 | 11 | com.insight.base 12 | message 13 | 2.0.0-RELEASE 14 | Message 15 | Message project for Spring Boot 16 | 17 | 18 | 17 19 | 2023.0.4 20 | 21 | 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-web 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-tomcat 30 | 31 | 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-undertow 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-devtools 40 | runtime 41 | true 42 | 43 | 44 | org.springframework.boot 45 | spring-boot-starter-test 46 | test 47 | 48 | 49 | org.mybatis.spring.boot 50 | mybatis-spring-boot-starter 51 | 3.0.4 52 | 53 | 54 | org.springframework.boot 55 | spring-boot-starter-data-redis 56 | 57 | 58 | org.springframework.boot 59 | spring-boot-starter-amqp 60 | 61 | 62 | org.springframework.boot 63 | spring-boot-starter-mail 64 | 65 | 66 | 67 | org.springframework.cloud 68 | spring-cloud-starter-consul-discovery 69 | 70 | 71 | org.springframework.cloud 72 | spring-cloud-starter-consul-config 73 | 74 | 75 | org.springframework.cloud 76 | spring-cloud-starter-loadbalancer 77 | 78 | 79 | org.springframework.cloud 80 | spring-cloud-starter-openfeign 81 | 82 | 83 | 84 | com.mysql 85 | mysql-connector-j 86 | runtime 87 | 88 | 89 | com.github.pagehelper 90 | pagehelper-spring-boot-starter 91 | 1.4.7 92 | 93 | 94 | org.springframework.amqp 95 | spring-rabbit-test 96 | test 97 | 98 | 99 | com.insight 100 | utils 101 | 4.0.0 102 | 103 | 104 | io.github.openfeign 105 | feign-jackson 106 | 12.1 107 | 108 | 109 | com.aliyun 110 | dysmsapi20170525 111 | 2.0.24 112 | 113 | 114 | 115 | 116 | 117 | release 118 | https://nexus.i-facture.com/repository/maven-public/ 119 | 120 | true 121 | 122 | 123 | true 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | org.springframework.cloud 132 | spring-cloud-dependencies 133 | ${spring-cloud.version} 134 | pom 135 | import 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | org.springframework.boot 144 | spring-boot-maven-plugin 145 | ${project.parent.version} 146 | 147 | 148 | 149 | 150 | 151 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/scene/SceneServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.scene; 2 | 3 | import com.github.pagehelper.PageHelper; 4 | import com.insight.common.message.common.dto.SceneConfigDto; 5 | import com.insight.common.message.common.entity.Scene; 6 | import com.insight.common.message.common.entity.SceneConfig; 7 | import com.insight.common.message.common.mapper.SceneMapper; 8 | import com.insight.utils.ReplyHelper; 9 | import com.insight.utils.SnowflakeCreator; 10 | import com.insight.utils.pojo.auth.LoginInfo; 11 | import com.insight.utils.pojo.base.BusinessException; 12 | import com.insight.utils.pojo.base.Reply; 13 | import com.insight.utils.pojo.base.Search; 14 | import org.springframework.stereotype.Service; 15 | 16 | import java.util.List; 17 | 18 | /** 19 | * @author 宣炳刚 20 | * @date 2019-08-28 21 | * @remark 消息管理服务 22 | */ 23 | @Service 24 | public class SceneServiceImpl implements SceneService { 25 | private final SnowflakeCreator creator; 26 | private final SceneMapper mapper; 27 | 28 | /** 29 | * 构造方法 30 | * 31 | * @param creator 雪花算法ID生成器 32 | * @param mapper SceneMapper 33 | */ 34 | public SceneServiceImpl(SnowflakeCreator creator, SceneMapper mapper) { 35 | this.creator = creator; 36 | this.mapper = mapper; 37 | } 38 | 39 | /** 40 | * 获取消息场景列表 41 | * 42 | * @param search 查询DTO 43 | * @return Reply 44 | */ 45 | @Override 46 | public Reply getScenes(Search search) { 47 | try (var page = PageHelper.startPage(search.getPageNum(), search.getPageSize()).setOrderBy(search.getOrderBy()) 48 | .doSelectPage(() -> mapper.getScenes(search))) { 49 | var total = page.getTotal(); 50 | return total > 0 ? ReplyHelper.success(page.getResult(), total) : ReplyHelper.resultIsEmpty(); 51 | } 52 | } 53 | 54 | /** 55 | * 获取消息场景 56 | * 57 | * @param id 消息场景ID 58 | * @return Reply 59 | */ 60 | @Override 61 | public Scene getScene(Long id) { 62 | Scene scene = mapper.getScene(id); 63 | if (scene == null) { 64 | throw new BusinessException("ID不存在,未读取数据"); 65 | } 66 | 67 | return scene; 68 | } 69 | 70 | /** 71 | * 新增消息场景 72 | * 73 | * @param info 用户关键信息 74 | * @param dto 消息场景DTO 75 | * @return Reply 76 | */ 77 | @Override 78 | public Long newScene(LoginInfo info, Scene dto) { 79 | Long id = creator.nextId(1); 80 | int count = mapper.getSceneCount(id, dto.getCode()); 81 | if (count > 0) { 82 | throw new BusinessException("场景编码已存在"); 83 | } 84 | 85 | dto.setId(id); 86 | dto.setCreator(info.getName()); 87 | dto.setCreatorId(info.getId()); 88 | 89 | mapper.addScene(dto); 90 | return id; 91 | } 92 | 93 | /** 94 | * 编辑消息场景 95 | * 96 | * @param info 用户关键信息 97 | * @param dto 消息场景DTO 98 | */ 99 | @Override 100 | public void editScene(LoginInfo info, Scene dto) { 101 | Long id = dto.getId(); 102 | Scene scene = mapper.getScene(id); 103 | if (scene == null) { 104 | throw new BusinessException("ID不存在,未更新数据"); 105 | } 106 | 107 | int count = mapper.getSceneCount(id, dto.getCode()); 108 | if (count > 0) { 109 | throw new BusinessException("场景编码已存在"); 110 | } 111 | 112 | mapper.editScene(dto); 113 | } 114 | 115 | /** 116 | * 删除消息场景 117 | * 118 | * @param info 用户关键信息 119 | * @param id 消息场景ID 120 | */ 121 | @Override 122 | public void deleteScene(LoginInfo info, Long id) { 123 | Scene scene = mapper.getScene(id); 124 | if (scene == null) { 125 | throw new BusinessException("ID不存在,未删除数据"); 126 | } 127 | 128 | mapper.deleteScene(id); 129 | } 130 | 131 | /** 132 | * 获取场景配置列表 133 | * 134 | * @param info 用户关键信息 135 | * @param sceneId 场景ID 136 | * @return Reply 137 | */ 138 | @Override 139 | public List getSceneConfigs(LoginInfo info, Long sceneId) { 140 | return mapper.getSceneConfigs(info.getTenantId(), sceneId); 141 | } 142 | 143 | /** 144 | * 新增场景配置 145 | * 146 | * @param info 用户关键信息 147 | * @param dto 场景配置DTO 148 | * @return Reply 149 | */ 150 | @Override 151 | public Long newSceneConfig(LoginInfo info, SceneConfig dto) { 152 | Long tenantId = info.getTenantId(); 153 | Long id = creator.nextId(2); 154 | 155 | int count = mapper.getConfigCount(dto.getSceneId(), tenantId, dto.getAppId()); 156 | if (count > 0) { 157 | throw new BusinessException("场景配置已存在,请勿重复添加"); 158 | } 159 | 160 | dto.setId(id); 161 | dto.setTenantId(tenantId); 162 | dto.setCreator(info.getName()); 163 | dto.setCreatorId(info.getId()); 164 | 165 | mapper.addSceneConfig(dto); 166 | return id; 167 | } 168 | 169 | /** 170 | * 编辑场景配置 171 | * 172 | * @param info 用户关键信息 173 | * @param dto 场景配置DTO 174 | */ 175 | @Override 176 | public void editSceneConfig(LoginInfo info, SceneConfig dto) { 177 | Long id = dto.getId(); 178 | SceneConfig config = mapper.getSceneConfig(id); 179 | if (config == null) { 180 | throw new BusinessException("ID不存在,未更新数据"); 181 | } 182 | 183 | Long tenantId = info.getTenantId(); 184 | if (tenantId != null && !tenantId.equals(config.getTenantId())) { 185 | throw new BusinessException("您无权修改该数据"); 186 | } 187 | 188 | mapper.updateSceneConfig(dto); 189 | } 190 | 191 | /** 192 | * 删除场景配置 193 | * 194 | * @param info 用户关键信息 195 | * @param id 场景配置ID 196 | */ 197 | @Override 198 | public void deleteSceneConfig(LoginInfo info, Long id) { 199 | SceneConfig config = mapper.getSceneConfig(id); 200 | if (config == null) { 201 | throw new BusinessException("ID不存在,未删除数据"); 202 | } 203 | 204 | mapper.deleteSceneConfig(id); 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/scene/SceneController.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.scene; 2 | 3 | import com.insight.common.message.common.client.LogClient; 4 | import com.insight.common.message.common.client.LogServiceClient; 5 | import com.insight.common.message.common.dto.SceneConfigDto; 6 | import com.insight.common.message.common.entity.OperateType; 7 | import com.insight.common.message.common.entity.Scene; 8 | import com.insight.common.message.common.entity.SceneConfig; 9 | import com.insight.utils.Json; 10 | import com.insight.utils.pojo.auth.LoginInfo; 11 | import com.insight.utils.pojo.base.Reply; 12 | import com.insight.utils.pojo.base.Search; 13 | import jakarta.validation.Valid; 14 | import org.springframework.web.bind.annotation.*; 15 | 16 | import java.util.List; 17 | 18 | /** 19 | * @author 宣炳刚 20 | * @date 2019-08-28 21 | * @remark 消息管理服务控制器 22 | */ 23 | @RestController 24 | @RequestMapping("/common/message") 25 | public class SceneController { 26 | private static final String BUSINESS = "Scene"; 27 | private final LogServiceClient client; 28 | private final SceneService service; 29 | 30 | /** 31 | * 构造方法 32 | * 33 | * @param client Feign客户端 34 | * @param service 注入Service 35 | */ 36 | public SceneController(LogServiceClient client, SceneService service) { 37 | this.client = client; 38 | this.service = service; 39 | } 40 | 41 | /** 42 | * 获取场景列表 43 | * 44 | * @param search 查询DTO 45 | * @return Reply 46 | */ 47 | @GetMapping("/v1.0/scenes") 48 | public Reply getScenes(Search search) { 49 | return service.getScenes(search); 50 | } 51 | 52 | /** 53 | * 获取场景 54 | * 55 | * @param id 场景ID 56 | * @return Reply 57 | */ 58 | @GetMapping("/v1.0/scenes/{id}") 59 | public Scene getScene(@PathVariable Long id) { 60 | return service.getScene(id); 61 | } 62 | 63 | /** 64 | * 新增场景 65 | * 66 | * @param loginInfo 用户关键信息 67 | * @param dto 场景DTO 68 | * @return Reply 69 | */ 70 | @PostMapping("/v1.0/scenes") 71 | public Long newScene(@RequestHeader("loginInfo") String loginInfo, @Valid @RequestBody Scene dto) { 72 | LoginInfo info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 73 | 74 | var id = service.newScene(info, dto); 75 | LogClient.writeLog(info, BUSINESS, OperateType.NEW, id, dto); 76 | return id; 77 | } 78 | 79 | /** 80 | * 编辑场景 81 | * 82 | * @param loginInfo 用户关键信息 83 | * @param id 场景ID 84 | * @param dto 场景DTO 85 | */ 86 | @PutMapping("/v1.0/scenes/{id}") 87 | public void editScene(@RequestHeader("loginInfo") String loginInfo, @PathVariable Long id, @Valid @RequestBody Scene dto) { 88 | LoginInfo info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 89 | dto.setId(id); 90 | 91 | service.editScene(info, dto); 92 | LogClient.writeLog(info, BUSINESS, OperateType.EDIT, id, dto); 93 | } 94 | 95 | /** 96 | * 删除场景 97 | * 98 | * @param loginInfo 用户关键信息 99 | * @param id 场景ID 100 | */ 101 | @DeleteMapping("/v1.0/scenes/{id}") 102 | public void deleteScene(@RequestHeader("loginInfo") String loginInfo, @RequestBody Long id) { 103 | LoginInfo info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 104 | 105 | service.deleteScene(info, id); 106 | LogClient.writeLog(info, BUSINESS, OperateType.DELETE, id, null); 107 | } 108 | 109 | /** 110 | * 获取场景配置列表 111 | * 112 | * @param loginInfo 用户关键信息 113 | * @param id 场景ID 114 | * @return Reply 115 | */ 116 | @GetMapping("/v1.0/scenes/{id}/configs") 117 | public List getSceneConfigs(@RequestHeader("loginInfo") String loginInfo, @PathVariable Long id) { 118 | LoginInfo info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 119 | 120 | return service.getSceneConfigs(info, id); 121 | } 122 | 123 | /** 124 | * 新增场景配置 125 | * 126 | * @param loginInfo 用户关键信息 127 | * @param id 场景ID 128 | * @param dto 场景配置DTO 129 | * @return Reply 130 | */ 131 | @PostMapping("/v1.0/scenes/{id}/configs") 132 | public Long newSceneConfig(@RequestHeader("loginInfo") String loginInfo, @PathVariable Long id, @Valid @RequestBody SceneConfig dto) { 133 | LoginInfo info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 134 | dto.setSceneId(id); 135 | 136 | var configId = service.newSceneConfig(info, dto); 137 | LogClient.writeLog(info, BUSINESS, OperateType.NEW, configId, dto); 138 | return configId; 139 | } 140 | 141 | /** 142 | * 编辑场景配置 143 | * 144 | * @param loginInfo 用户关键信息 145 | * @param id 场景配置ID 146 | * @param dto 场景配置DTO 147 | */ 148 | @PutMapping("/v1.0/scenes/configs/{id}") 149 | public void editSceneConfig(@RequestHeader("loginInfo") String loginInfo, @PathVariable Long id, @Valid @RequestBody SceneConfig dto) { 150 | LoginInfo info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 151 | dto.setId(id); 152 | 153 | service.editSceneConfig(info, dto); 154 | LogClient.writeLog(info, BUSINESS, OperateType.EDIT, id, dto); 155 | } 156 | 157 | /** 158 | * 删除场景配置 159 | * 160 | * @param loginInfo 用户关键信息 161 | * @param id 场景配置ID 162 | */ 163 | @DeleteMapping("/v1.0/scenes/configs/{id}") 164 | public void deleteSceneConfig(@RequestHeader("loginInfo") String loginInfo, @PathVariable Long id) { 165 | LoginInfo info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 166 | 167 | service.deleteSceneConfig(info, id); 168 | LogClient.writeLog(info, BUSINESS, OperateType.DELETE, id, null); 169 | } 170 | 171 | /** 172 | * 查询日志 173 | * 174 | * @param loginInfo 用户登录信息 175 | * @param search 查询条件 176 | * @return 日志集合 177 | */ 178 | @GetMapping("/v1.0/scenes/{id}/logs") 179 | public Reply getAirportLogs(@RequestHeader("loginInfo") String loginInfo, @PathVariable Long id, Search search) { 180 | var info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 181 | return client.getLogs(id, "Scene", search.getKeyword()); 182 | } 183 | 184 | /** 185 | * 获取日志 186 | * 187 | * @param loginInfo 用户登录信息 188 | * @param id 日志ID 189 | * @return 日志VO 190 | */ 191 | @GetMapping("/v1.0/scenes/logs/{id}") 192 | public Reply getAirportLog(@RequestHeader("loginInfo") String loginInfo, @PathVariable Long id) { 193 | var info = Json.toBeanFromBase64(loginInfo, LoginInfo.class); 194 | return client.getLog(id); 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/mapper/MessageMapper.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.mapper; 2 | 3 | import com.insight.common.message.common.dto.*; 4 | import com.insight.common.message.common.entity.PushMessage; 5 | import com.insight.common.message.common.entity.SubscribeMessage; 6 | import com.insight.utils.pojo.base.JsonTypeHandler; 7 | import com.insight.utils.pojo.base.Search; 8 | import com.insight.utils.pojo.message.InsightMessage; 9 | import com.insight.utils.pojo.message.Schedule; 10 | import org.apache.ibatis.annotations.*; 11 | 12 | import java.util.List; 13 | 14 | /** 15 | * @author 宣炳刚 16 | * @date 2019/9/21 17 | * @remark 消息DAL 18 | */ 19 | @Mapper 20 | public interface MessageMapper { 21 | 22 | /** 23 | * 获取适用消息模板 24 | * 25 | * @param tenantId 租户ID 26 | * @param appId 应用ID 27 | * @param code 场景编号 28 | * @return 消息模板 29 | */ 30 | @Select("select s.type, s.title, s.tag, c.content, c.sign, c.expire from ims_scene s join ims_scene_config c on c.scene_id = s.id " + 31 | "and (c.tenant_id is null or c.tenant_id = #{tenantId}) and (c.app_id is null or c.app_id = #{appId}) " + 32 | "where s.code = #{code} order by c.tenant_id desc, c.app_id desc limit 1;") 33 | TemplateDto getTemplate(Long tenantId, Long appId, String code); 34 | 35 | /** 36 | * 获取消息列表 37 | * 38 | * @param search 查询实体类 39 | * @return 消息列表 40 | */ 41 | @Select("") 48 | List getMessages(Search search); 49 | 50 | /** 51 | * 获取消息详情 52 | * 53 | * @param messageId 消息ID 54 | * @param userId 用户ID 55 | * @return 消息详情 56 | */ 57 | @Select("select m.id, m.tag, m.title, m.content, case when r.message_id is null then 0 else 1 end as read, m.broadcast, m.creator, m.creator_id, m.created_time " + 58 | "from imm_message m left join (select message_id, read from imm_message_push where message_id = #{messageId} and user_id = #{userId} union all " + 59 | "select message_id, 1 as read from imm_message_subscribe where message_id = #{messageId} and user_id = #{userId}) r on r.message_id = m.id " + 60 | "where m.id = #{messageId};") 61 | UserMessageDto getMessage(@Param("messageId") Long messageId, @Param("userId") Long userId); 62 | 63 | /** 64 | * 新增消息 65 | * 66 | * @param message 消息DTO 67 | */ 68 | @Insert("insert imm_message(id, tenant_id, app_id, tag, title, content, expire, broadcast_id, creator, creator_id, created_time) values " + 69 | "(#{id}, #{tenantId}, #{appId}, #{tag}, #{title}, #{content}, #{expire}, #{broadcast}, #{creator}, #{creatorId}, #{createdTime});") 70 | void addMessage(InsightMessage message); 71 | 72 | /** 73 | * 推送消息 74 | * 75 | * @param list 消息推送DTO集合 76 | */ 77 | @Insert("") 80 | void pushMessage(List list); 81 | 82 | /** 83 | * 设置用户消息为已读 84 | * 85 | * @param messageId 消息ID 86 | * @param userId 用户ID 87 | */ 88 | @Update("update imm_message_push set read = 1, read_time = now() where message_id = #{messageId} and user_id = #{userId};") 89 | void readMessage(@Param("messageId") Long messageId, @Param("userId") Long userId); 90 | 91 | /** 92 | * 订阅消息 93 | * 94 | * @param subscribeMessage 消息订阅DTO 95 | */ 96 | @Insert("insert imm_message_subscribe(message_id, user_id, created_time) values (#{messageId}, #{userId}, #{createdTime});") 97 | void subscribeMessage(SubscribeMessage subscribeMessage); 98 | 99 | /** 100 | * 删除用户消息 101 | * 102 | * @param messageId 消息ID 103 | * @param userId 用户ID 104 | */ 105 | @Update("update imm_message_push set invalid = 1 where message_id = #{messageId} and user_id = #{userId};") 106 | void deleteUserMessage(@Param("messageId") Long messageId, @Param("userId") Long userId); 107 | 108 | /** 109 | * 删除用户消息 110 | * 111 | * @param messageId 消息ID 112 | * @param userId 用户ID 113 | */ 114 | @Update("update imm_message_subscribe set invalid = 1 where message_id = #{messageId} and user_id = #{userId};") 115 | void unsubscribeMessage(@Param("messageId") Long messageId, @Param("userId") Long userId); 116 | 117 | /** 118 | * 编辑消息 119 | * 120 | * @param message 消息DTO 121 | */ 122 | @Update("update imm_message set app_id = #{appId}, tag = #{tag}, type = #{type}, receivers = #{receivers, typeHandler = com.insight.utils.pojo.base.ArrayTypeHandler}, " + 123 | "content = #{content}, expire = #{expire}, broadcast = #{broadcast} where id = #{id};") 124 | void editMessage(InsightMessage message); 125 | 126 | /** 127 | * 删除消息 128 | * 129 | * @param id 消息ID 130 | */ 131 | @Delete("delete from imm_message where id = #{id};") 132 | void deleteMessage(String id); 133 | 134 | /** 135 | * 取消推送 136 | * 137 | * @param id 推送ID 138 | */ 139 | @Delete("delete from imm_message_push where id = #{id};") 140 | void cancelPush(String id); 141 | 142 | /** 143 | * 获取任务列表 144 | * 145 | * @param search 查询DTO 146 | * @return 任务列表 147 | */ 148 | @Select("") 150 | List getSchedules(Search search); 151 | 152 | /** 153 | * 获取任务详情 154 | * 155 | * @param id 计划任务ID 156 | * @return 计划任务DTO 157 | */ 158 | @Results({@Result(property = "content", column = "content", javaType = Object.class, typeHandler = JsonTypeHandler.class)}) 159 | @Select("select * from imt_schedule where id = #{id};") 160 | Schedule getSchedule(Long id); 161 | 162 | /** 163 | * 获取当前需要执行的消息类型的计划任务 164 | * 165 | * @return DTO集合 166 | */ 167 | @Results({@Result(property = "content", column = "content", javaType = InsightMessage.class, typeHandler = JsonTypeHandler.class)}) 168 | @Select("select * from imt_schedule where type = 0 and task_time < now() and expire_time > now() and invalid = 0;") 169 | List> getMessageSchedule(); 170 | 171 | /** 172 | * 获取当前需要执行的本地调用类型的计划任务 173 | * 174 | * @return 计划任务DTO集合 175 | */ 176 | @Results({@Result(property = "content", column = "content", javaType = ScheduleCall.class, typeHandler = JsonTypeHandler.class)}) 177 | @Select("select * from imt_schedule where type = 1 and task_time < now() and expire_time > now() and invalid = 0;") 178 | List> getLocalSchedule(); 179 | 180 | /** 181 | * 获取当前需要执行的远程调用类型的计划任务 182 | * 183 | * @return 计划任务DTO集合 184 | */ 185 | @Results({@Result(property = "content", column = "content", javaType = ScheduleCall.class, typeHandler = JsonTypeHandler.class)}) 186 | @Select("select * from imt_schedule where type = 2 and task_time < now() and expire_time > now() and invalid = 0;") 187 | List> getRpcSchedule(); 188 | 189 | /** 190 | * 新增计划任务记录 191 | * 192 | * @param schedule 计划任务DTO 193 | */ 194 | @Insert("insert imt_schedule (id, type, method, task_time, content, count, expire_time, invalid, created_time) values " + 195 | "(#{id}, #{type}, #{method}, #{taskTime}, #{content, typeHandler = com.insight.utils.pojo.base.JsonTypeHandler}, " + 196 | "#{count}, #{expireTime}, #{invalid}, #{createdTime});") 197 | void addSchedule(Schedule schedule); 198 | 199 | /** 200 | * 更新任务执行时间为当前时间 201 | * 202 | * @param id 计划任务ID 203 | */ 204 | @Update("update imt_schedule set task_time = now(), invalid = 0 where id = #{id};") 205 | void editSchedule(Long id); 206 | 207 | /** 208 | * 禁用/启用计划任务 209 | * 210 | * @param id 计划任务ID 211 | * @param status 禁用/启用状态 212 | */ 213 | @Update("update imt_schedule set invalid = #{status} where id = #{id};") 214 | void changeScheduleStatus(Long id, boolean status); 215 | 216 | /** 217 | * 删除计划任务 218 | * 219 | * @param id 计划任务ID 220 | */ 221 | @Delete("delete from imt_schedule where id = #{id};") 222 | void deleteSchedule(Long id); 223 | } 224 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/message/MessageServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.message; 2 | 3 | import com.github.pagehelper.PageHelper; 4 | import com.insight.common.message.common.Core; 5 | import com.insight.common.message.common.MessageDal; 6 | import com.insight.common.message.common.client.AuthClient; 7 | import com.insight.common.message.common.client.RabbitClient; 8 | import com.insight.common.message.common.dto.CodeDto; 9 | import com.insight.common.message.common.dto.CustomMessage; 10 | import com.insight.common.message.common.dto.NormalMessage; 11 | import com.insight.common.message.common.dto.UserMessageDto; 12 | import com.insight.common.message.common.mapper.MessageMapper; 13 | import com.insight.utils.Json; 14 | import com.insight.utils.ReplyHelper; 15 | import com.insight.utils.SnowflakeCreator; 16 | import com.insight.utils.Util; 17 | import com.insight.utils.pojo.auth.LoginInfo; 18 | import com.insight.utils.pojo.base.BusinessException; 19 | import com.insight.utils.pojo.base.Reply; 20 | import com.insight.utils.pojo.base.Search; 21 | import com.insight.utils.pojo.message.InsightMessage; 22 | import com.insight.utils.pojo.message.Schedule; 23 | import com.insight.utils.pojo.message.SmsCode; 24 | import com.insight.utils.redis.KeyOps; 25 | import com.insight.utils.redis.Redis; 26 | import org.slf4j.Logger; 27 | import org.slf4j.LoggerFactory; 28 | import org.springframework.beans.factory.annotation.Value; 29 | import org.springframework.stereotype.Service; 30 | 31 | import java.time.LocalDateTime; 32 | import java.util.HashMap; 33 | import java.util.Map; 34 | import java.util.concurrent.TimeUnit; 35 | 36 | /** 37 | * @author 宣炳刚 38 | * @date 2019-08-28 39 | * @remark 短信服务 40 | */ 41 | @Service 42 | public class MessageServiceImpl implements MessageService { 43 | private final Logger logger = LoggerFactory.getLogger(this.getClass()); 44 | private final SnowflakeCreator creator; 45 | private final AuthClient client; 46 | private final MessageDal dal; 47 | private final MessageMapper mapper; 48 | private final Core core; 49 | 50 | /** 51 | * 允许发送匿名短信 52 | */ 53 | @Value("${insight.sms.allowAnonymity}") 54 | private boolean allowAnonymity; 55 | 56 | /** 57 | * 构造方法 58 | * 59 | * @param creator 雪花算法ID生成器 60 | * @param client Feign客户端 61 | * @param dal MessageDal 62 | * @param mapper MessageMapper 63 | * @param core 计划任务异步执行核心类 64 | */ 65 | public MessageServiceImpl(SnowflakeCreator creator, AuthClient client, MessageDal dal, MessageMapper mapper, Core core) { 66 | this.creator = creator; 67 | this.client = client; 68 | this.dal = dal; 69 | this.mapper = mapper; 70 | this.core = core; 71 | } 72 | 73 | /** 74 | * 发送短信验证码 75 | * 76 | * @param dto 短信DTO 77 | */ 78 | @Override 79 | public void seedSmsCode(SmsCode dto) { 80 | var mobile = dto.getMobile(); 81 | var type = dto.getType(); 82 | switch (type) { 83 | case 0 -> { 84 | if (allowAnonymity) { 85 | sendSmsCode(dto); 86 | } else { 87 | throw new BusinessException("不允许发送匿名验证码"); 88 | } 89 | } 90 | case 1 -> { 91 | if (KeyOps.hasKey("ID:" + dto.getMobile())) { 92 | sendSmsCode(dto); 93 | } else { 94 | throw new BusinessException("请输入正确的手机号"); 95 | } 96 | } 97 | case 2, 3 -> { 98 | var data = new CodeDto(mobile); 99 | var reply = client.getCode(data); 100 | if (reply.getSuccess()) { 101 | sendSmsCode(dto); 102 | } else { 103 | throw new BusinessException("请输入正确的手机号"); 104 | } 105 | } 106 | default -> throw new BusinessException("验证码类型不正确"); 107 | } 108 | } 109 | 110 | /** 111 | * 验证短信验证码 112 | * 113 | * @param key 验证参数,MD5(type + mobile + code) 114 | * @param isCheck 是否检验模式:true.检验模式,验证后验证码不失效;false.验证模式,验证后验证码失效 115 | * @return Reply 116 | */ 117 | @Override 118 | public String verifySmsCode(String key, Boolean isCheck) { 119 | var codeKey = "VerifyCode:" + key; 120 | var mobile = Redis.get(codeKey); 121 | if (mobile == null || mobile.isEmpty()) { 122 | throw new BusinessException("验证码错误"); 123 | } 124 | 125 | if (isCheck) { 126 | // 每验证一次有效时间减少15秒,以避免暴力破解 127 | Redis.changeExpire(codeKey, -15); 128 | return mobile; 129 | } 130 | 131 | // 清理已通过验证的验证码对应手机号的全部验证码 132 | var setKey = "VerifyCodeSet:" + mobile; 133 | var keys = Redis.getMembers(setKey); 134 | for (var k : keys) { 135 | Redis.deleteKey("VerifyCode:" + k); 136 | } 137 | 138 | // 清理验证码对应手机号缓存 139 | Redis.deleteKey(setKey); 140 | 141 | return mobile; 142 | } 143 | 144 | /** 145 | * 发送送标准消息 146 | * 147 | * @param info 用户关键信息 148 | * @param dto 标准信息DTO 149 | */ 150 | @Override 151 | public void sendNormalMessage(LoginInfo info, NormalMessage dto) { 152 | var tenantId = info == null ? null : info.getTenantId(); 153 | var appId = info == null ? null : info.getAppId(); 154 | var template = mapper.getTemplate(tenantId, appId, dto.getSceneCode()); 155 | if (template == null) { 156 | throw new BusinessException("没有可用消息模板,请检查消息参数是否正确"); 157 | } 158 | 159 | // 处理签名 160 | var sign = template.getSign(); 161 | var params = dto.getParams(); 162 | if (sign != null && !sign.isEmpty()) { 163 | if (params == null) { 164 | params = new HashMap<>(4); 165 | } 166 | 167 | params.put("sign", sign); 168 | } 169 | 170 | // 组装消息 171 | var message = Json.clone(dto, InsightMessage.class); 172 | message.setTag(template.getTag()); 173 | message.setType(template.getType()); 174 | message.setTitle(template.getTitle()); 175 | 176 | var content = assemblyContent(template.getContent(), dto.getParams()); 177 | message.setContent(content); 178 | message.setParams(params); 179 | 180 | message.setExpire(template.getExpire()); 181 | sendMessage(info, message); 182 | } 183 | 184 | /** 185 | * 发送自定义消息 186 | * 187 | * @param info 用户关键信息 188 | * @param dto 标准信息DTO 189 | */ 190 | @Override 191 | public void sendCustomMessage(LoginInfo info, CustomMessage dto) { 192 | var message = Json.clone(dto, InsightMessage.class); 193 | sendMessage(info, message); 194 | } 195 | 196 | /** 197 | * 获取用户消息列表 198 | * 199 | * @param info 用户关键信息 200 | * @param search 查询实体类 201 | * @return Reply 202 | */ 203 | @Override 204 | public Reply getUserMessages(LoginInfo info, Search search) { 205 | search.setOwnerId(info.getId()); 206 | var page = PageHelper.startPage(search.getPageNum(), search.getPageSize()) 207 | .setOrderBy(search.getOrderBy()).doSelectPage(() -> mapper.getMessages(search)); 208 | 209 | var total = page.getTotal(); 210 | return total > 0 ? ReplyHelper.success(page.getResult(), total) : ReplyHelper.resultIsEmpty(); 211 | } 212 | 213 | /** 214 | * 获取用户消息详情 215 | * 216 | * @param messageId 消息ID 217 | * @param userId 用户ID 218 | * @return Reply 219 | */ 220 | @Override 221 | public UserMessageDto getUserMessage(Long messageId, Long userId) { 222 | var message = mapper.getMessage(messageId, userId); 223 | if (message == null) { 224 | throw new BusinessException("ID不存在,未读取数据"); 225 | } 226 | 227 | if (!message.getRead()) { 228 | dal.readMessage(message.getId(), userId, message.getBroadcast()); 229 | message.setRead(true); 230 | } 231 | 232 | return message; 233 | } 234 | 235 | /** 236 | * 删除用户消息 237 | * 238 | * @param messageId 消息ID 239 | * @param userId 用户ID 240 | */ 241 | @Override 242 | public void deleteUserMessage(Long messageId, Long userId) { 243 | var message = mapper.getMessage(messageId, userId); 244 | if (message == null) { 245 | throw new BusinessException("ID不存在,未删除数据"); 246 | } 247 | 248 | if (message.getBroadcast()) { 249 | if (!message.getRead()) { 250 | dal.readMessage(message.getId(), userId, true); 251 | } 252 | 253 | mapper.unsubscribeMessage(messageId, userId); 254 | } else { 255 | mapper.deleteUserMessage(messageId, userId); 256 | } 257 | } 258 | 259 | /** 260 | * 发送短信验证码 261 | * 262 | * @param dto 短信DTO 263 | */ 264 | private void sendSmsCode(SmsCode dto) { 265 | var mobile = dto.getMobile(); 266 | var type = dto.getType(); 267 | 268 | var message = new InsightMessage(); 269 | message.setChannel(dto.getChannel()); 270 | message.setReceiver(mobile); 271 | message.setParams(dto.getParam()); 272 | core.sendSms(message); 273 | 274 | var smsCode = dto.getCode(); 275 | var key = Util.md5(type + mobile + smsCode); 276 | Redis.set("VerifyCode:" + key, mobile, Long.valueOf(dto.getMinutes()), TimeUnit.MINUTES); 277 | Redis.add("VerifyCodeSet:" + mobile, key); 278 | Redis.changeExpire("VerifyCodeSet:" + mobile, Long.valueOf(dto.getMinutes()) * 60); 279 | logger.info("手机号[{}]的{}类短信验证码为: {}", mobile, type, smsCode); 280 | } 281 | 282 | /** 283 | * 发送消息到队列 284 | * 285 | * @param info 用户关键信息 286 | * @param message 消息DTO 287 | */ 288 | private void sendMessage(LoginInfo info, InsightMessage message) { 289 | var schedule = new Schedule(); 290 | schedule.setType(0); 291 | schedule.setContent(message); 292 | int type = message.getType(); 293 | 294 | // 本地消息 295 | if (1 == (type & 1) && info != null) { 296 | message.setId(creator.nextId(0)); 297 | message.setTenantId(info.getTenantId()); 298 | message.setAppId(info.getAppId()); 299 | message.setCreator(info.getName()); 300 | message.setCreatorId(info.getId()); 301 | 302 | message.setCreatedTime(LocalDateTime.now()); 303 | schedule.setMethod("addMessage"); 304 | RabbitClient.sendTopic("schedule.message", schedule); 305 | } 306 | 307 | // 推送通知 308 | if (2 == (type & 2)) { 309 | schedule.setMethod("pushNotice"); 310 | RabbitClient.sendTopic("schedule.message", schedule); 311 | } 312 | 313 | // 发送短信 314 | if (4 == (type & 4)) { 315 | schedule.setMethod("sendSms"); 316 | RabbitClient.sendTopic("schedule.message", schedule); 317 | } 318 | 319 | // 发送邮件 320 | if (8 == (type & 8)) { 321 | schedule.setMethod("sendMail"); 322 | RabbitClient.sendTopic("schedule.message", schedule); 323 | } 324 | } 325 | 326 | /** 327 | * 使用模板组装消息内容 328 | * 329 | * @param template 内容模板 330 | * @param params 消息参数 331 | * @return 消息内容 332 | */ 333 | private String assemblyContent(String template, Map params) { 334 | for (var k : params.keySet()) { 335 | var v = params.get(k); 336 | if (v == null) { 337 | continue; 338 | } 339 | 340 | var key = "\\{" + k + "}"; 341 | template = template.replaceAll(key, v.toString()); 342 | } 343 | 344 | return template; 345 | } 346 | } 347 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/config/GlobalExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common.config; 2 | 3 | import com.insight.utils.Json; 4 | import com.insight.utils.ReplyHelper; 5 | import com.insight.utils.pojo.base.BusinessException; 6 | import com.insight.utils.pojo.base.Reply; 7 | import feign.FeignException; 8 | import jakarta.servlet.http.HttpServletRequest; 9 | import jakarta.validation.UnexpectedTypeException; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | import org.springframework.boot.logging.LogLevel; 13 | import org.springframework.core.MethodParameter; 14 | import org.springframework.dao.DataIntegrityViolationException; 15 | import org.springframework.http.HttpStatus; 16 | import org.springframework.http.MediaType; 17 | import org.springframework.http.converter.HttpMessageConverter; 18 | import org.springframework.http.converter.HttpMessageNotReadableException; 19 | import org.springframework.http.server.ServerHttpRequest; 20 | import org.springframework.http.server.ServerHttpResponse; 21 | import org.springframework.jdbc.BadSqlGrammarException; 22 | import org.springframework.validation.BindException; 23 | import org.springframework.validation.FieldError; 24 | import org.springframework.web.HttpMediaTypeNotSupportedException; 25 | import org.springframework.web.bind.MethodArgumentNotValidException; 26 | import org.springframework.web.bind.MissingServletRequestParameterException; 27 | import org.springframework.web.bind.ServletRequestBindingException; 28 | import org.springframework.web.bind.annotation.ControllerAdvice; 29 | import org.springframework.web.bind.annotation.ExceptionHandler; 30 | import org.springframework.web.bind.annotation.ResponseBody; 31 | import org.springframework.web.bind.annotation.ResponseStatus; 32 | import org.springframework.web.context.request.RequestContextHolder; 33 | import org.springframework.web.context.request.ServletRequestAttributes; 34 | import org.springframework.web.context.request.async.AsyncRequestTimeoutException; 35 | import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; 36 | 37 | import java.sql.SQLIntegrityConstraintViolationException; 38 | import java.sql.SQLSyntaxErrorException; 39 | import java.time.format.DateTimeParseException; 40 | import java.util.Objects; 41 | 42 | /** 43 | * @author 宣炳刚 44 | * @date 2023/1/4 45 | * @remark 全局异常捕获 46 | */ 47 | @ResponseStatus(HttpStatus.OK) 48 | @ResponseBody 49 | @ControllerAdvice 50 | public class GlobalExceptionHandler implements ResponseBodyAdvice { 51 | private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class); 52 | 53 | /** 54 | * 业务异常 55 | * 56 | * @param ex 业务异常 57 | * @return Reply 58 | */ 59 | @ExceptionHandler(BusinessException.class) 60 | public Reply handleBusinessException(BusinessException ex) { 61 | String msg = ex.getMessage(); 62 | logger(LogLevel.INFO, "业务发生异常, " + msg); 63 | 64 | return ReplyHelper.fail(msg); 65 | } 66 | 67 | /** 68 | * 处理缺少请求参数的异常 69 | * 70 | * @param ex 缺少请求参数 71 | * @return Reply 72 | */ 73 | @ExceptionHandler(MissingServletRequestParameterException.class) 74 | public Reply handleMissingServletRequestParameterException(MissingServletRequestParameterException ex) { 75 | String msg = "缺少请求参数, " + ex.getParameterName(); 76 | logger(LogLevel.WARN, msg); 77 | 78 | return ReplyHelper.invalidParam(msg); 79 | } 80 | 81 | /** 82 | * 处理不合法的参数的异常 83 | * 84 | * @param ex 不合法的参数异常 85 | * @return Reply 86 | */ 87 | @ExceptionHandler(IllegalArgumentException.class) 88 | public Reply handleIllegalArgumentException(IllegalArgumentException ex) { 89 | String msg = "不合法的参数, " + ex.getMessage(); 90 | logger(LogLevel.WARN, msg); 91 | 92 | return ReplyHelper.invalidParam(msg); 93 | } 94 | 95 | /** 96 | * 处理参数绑定出现的异常 97 | * 98 | * @param ex 参数绑定错误异常 99 | * @return Reply 100 | */ 101 | @ExceptionHandler(ServletRequestBindingException.class) 102 | public Reply handleServletRequestBindingException(ServletRequestBindingException ex) { 103 | String msg = "参数绑定错误, " + ex.getMessage(); 104 | logger(LogLevel.WARN, msg); 105 | 106 | return ReplyHelper.invalidParam(msg); 107 | } 108 | 109 | /** 110 | * 处理参数解析失败的异常 111 | * 112 | * @param ex 参数解析失败异常 113 | * @return Reply 114 | */ 115 | @ExceptionHandler(HttpMessageNotReadableException.class) 116 | public Reply handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) { 117 | String msg = "参数解析失败, " + ex.getMessage(); 118 | logger(LogLevel.WARN, msg); 119 | 120 | return ReplyHelper.invalidParam(msg); 121 | } 122 | 123 | /** 124 | * 参数验证失败的异常 125 | * 126 | * @param ex 参数验证失败异常 127 | * @return Reply 128 | */ 129 | @ExceptionHandler(MethodArgumentNotValidException.class) 130 | public Reply handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) { 131 | FieldError error = ex.getBindingResult().getFieldError(); 132 | if (error == null) { 133 | String msg = "参数解析失败, " + ex.getMessage(); 134 | logger(LogLevel.WARN, msg); 135 | 136 | return ReplyHelper.invalidParam("参数解析失败"); 137 | } 138 | 139 | String parameter = error.getField(); 140 | String msg = "参数绑定失败, " + parameter; 141 | logger(LogLevel.WARN, msg); 142 | 143 | return ReplyHelper.invalidParam(msg); 144 | } 145 | 146 | /** 147 | * 参数绑定失败的异常 148 | * 149 | * @param ex 参数绑定失败异常 150 | * @return Reply 151 | */ 152 | @ExceptionHandler(BindException.class) 153 | public Reply handleBindException(BindException ex) { 154 | FieldError error = ex.getBindingResult().getFieldError(); 155 | if (error == null) { 156 | String msg = "参数绑定失败, " + ex.getMessage(); 157 | logger(LogLevel.WARN, msg); 158 | 159 | return ReplyHelper.invalidParam("参数绑定失败"); 160 | } 161 | 162 | String parameter = error.getField(); 163 | String msg = "参数绑定失败, " + parameter; 164 | logger(LogLevel.WARN, msg); 165 | 166 | return ReplyHelper.invalidParam(msg); 167 | } 168 | 169 | /** 170 | * 参数类型不匹配的异常 171 | * 172 | * @param ex 参数类型不匹配异常 173 | * @return Reply 174 | */ 175 | @ExceptionHandler(HttpMediaTypeNotSupportedException.class) 176 | public Reply handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException ex) { 177 | String msg = "不支持当前媒体类型, " + ex.getMessage(); 178 | logger(LogLevel.WARN, msg); 179 | 180 | return ReplyHelper.invalidParam(msg); 181 | } 182 | 183 | /** 184 | * 非预期类型的异常 185 | * 186 | * @param ex 非预期类型异常 187 | * @return Reply 188 | */ 189 | @ExceptionHandler(UnexpectedTypeException.class) 190 | public Reply handleUnexpectedTypeException(UnexpectedTypeException ex) { 191 | String msg = "参数类型不匹配, " + ex.getMessage(); 192 | logger(LogLevel.WARN, msg); 193 | 194 | return ReplyHelper.invalidParam(msg); 195 | } 196 | 197 | /** 198 | * 服务调用异常 199 | * 200 | * @param ex 服务调用异常 201 | * @return Reply 202 | */ 203 | @ExceptionHandler(FeignException.class) 204 | public Reply handleFeignException(FeignException ex) { 205 | String msg = "服务调用异常, " + ex.getMessage(); 206 | String requestId = logger(LogLevel.ERROR, msg); 207 | 208 | return ReplyHelper.error(requestId); 209 | } 210 | 211 | /** 212 | * 数据库操作出现异常:插入、删除和修改数据的时候,违背数据完整性约束抛出的异常 213 | * 214 | * @param ex 违背数据完整性约异常 215 | * @return Reply 216 | */ 217 | @ExceptionHandler(DataIntegrityViolationException.class) 218 | public Reply handleDataIntegrityViolationException(DataIntegrityViolationException ex) { 219 | String msg = "数据库操作异常, " + ex.getCause().getMessage(); 220 | String requestId = logger(LogLevel.ERROR, msg); 221 | 222 | return ReplyHelper.error(requestId); 223 | } 224 | 225 | /** 226 | * 数据库操作出现异常:插入、删除和修改数据的时候,违背数据完整性约束抛出的异常 227 | * 228 | * @param ex 违背数据完整性约异常 229 | * @return Reply 230 | */ 231 | @ExceptionHandler(BadSqlGrammarException.class) 232 | public Reply handleBadSqlGrammarException(BadSqlGrammarException ex) { 233 | String msg = "数据库操作异常, " + ex.getCause().getMessage(); 234 | String requestId = logger(LogLevel.ERROR, msg); 235 | 236 | return ReplyHelper.error(requestId); 237 | } 238 | 239 | /** 240 | * 数据库操作出现异常:插入、删除和修改数据的时候,违背数据完整性约束抛出的异常 241 | * 242 | * @param ex 违背数据完整性约异常 243 | * @return Reply 244 | */ 245 | @ExceptionHandler(SQLIntegrityConstraintViolationException.class) 246 | public Reply handleSqlIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException ex) { 247 | String msg = "数据库操作异常, " + ex.getCause().getMessage(); 248 | String requestId = logger(LogLevel.ERROR, msg); 249 | 250 | return ReplyHelper.error(requestId); 251 | } 252 | 253 | /** 254 | * SQL语句执行错误抛出的异常 255 | * 256 | * @param ex SQL语句执行错误的异常 257 | * @return Reply 258 | */ 259 | @ExceptionHandler(SQLSyntaxErrorException.class) 260 | public Reply handleSqlSyntaxErrorException(SQLSyntaxErrorException ex) { 261 | String msg = "数据库操作异常, " + ex.getCause().getMessage(); 262 | String requestId = logger(LogLevel.ERROR, msg); 263 | 264 | return ReplyHelper.error(requestId); 265 | } 266 | 267 | /** 268 | * 空指针抛出的异常 269 | * 270 | * @param ex 空指针异常 271 | * @return Reply 272 | */ 273 | @ExceptionHandler(NullPointerException.class) 274 | public Reply handleNullPointerException(NullPointerException ex) { 275 | String msg = "空指针异常, " + ex.getMessage(); 276 | String requestId = logger(LogLevel.ERROR, msg); 277 | printStack(requestId, ex); 278 | 279 | return ReplyHelper.error(requestId); 280 | } 281 | 282 | /** 283 | * 时间/日期格式错误的异常 284 | * 285 | * @param ex 时间/日期格式错误的异常 286 | * @return Reply 287 | */ 288 | @ExceptionHandler(DateTimeParseException.class) 289 | public Reply handleUnexpectedTypeException(DateTimeParseException ex) { 290 | String msg = "时间/日期格式错误, " + ex.getMessage(); 291 | String requestId = logger(LogLevel.ERROR, msg); 292 | printStack(requestId, ex); 293 | 294 | return ReplyHelper.error(requestId, msg); 295 | } 296 | 297 | /** 298 | * 异步请求超时异常 299 | * 300 | * @param ex 异步请求超时异常 301 | * @return Reply 302 | */ 303 | @ExceptionHandler(AsyncRequestTimeoutException.class) 304 | public Reply handleAsyncRequestTimeoutException(AsyncRequestTimeoutException ex) { 305 | String msg = "异步请求超时异常, " + ex.getMessage(); 306 | String requestId = logger(LogLevel.ERROR, msg); 307 | printStack(requestId, ex); 308 | 309 | return ReplyHelper.error(requestId); 310 | } 311 | 312 | /** 313 | * 运行时异常 314 | * 315 | * @param ex 运行时异常 316 | * @return Reply 317 | */ 318 | @ExceptionHandler(RuntimeException.class) 319 | public Reply handleRuntimeException(RuntimeException ex) { 320 | String msg = "运行时异常, " + ex.getMessage(); 321 | String requestId = logger(LogLevel.ERROR, msg); 322 | printStack(requestId, ex); 323 | 324 | return ReplyHelper.error(requestId); 325 | } 326 | 327 | /** 328 | * 服务器异常 329 | * 330 | * @param ex 通用异常 331 | * @return Reply 332 | */ 333 | @ExceptionHandler(Exception.class) 334 | public Reply handleException(Exception ex) { 335 | String msg = "服务器异常, " + ex.getMessage(); 336 | String requestId = logger(LogLevel.ERROR, msg); 337 | printStack(requestId, ex); 338 | 339 | return ReplyHelper.error(requestId); 340 | } 341 | 342 | /** 343 | * 打印日志 344 | * 345 | * @param level 日志等级 346 | * @param message 错误信息 347 | * @return 请求ID 348 | */ 349 | private String logger(LogLevel level, String message) { 350 | ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 351 | HttpServletRequest request = Objects.requireNonNull(requestAttributes).getRequest(); 352 | String requestId = request.getHeader("requestId"); 353 | switch (level) { 354 | case ERROR -> LOGGER.error("requestId: {}. 错误信息: {}", requestId, message); 355 | case WARN -> LOGGER.warn("requestId: {}. 警告信息: {}", requestId, message); 356 | default -> LOGGER.info("requestId: {}. 日志信息: {}", requestId, message); 357 | } 358 | 359 | return requestId; 360 | } 361 | 362 | /** 363 | * 打印异常堆栈 364 | * 365 | * @param requestId 请求ID 366 | * @param ex Exception 367 | */ 368 | private void printStack(String requestId, Exception ex) { 369 | String stackTrace = Json.toJson(ex.getStackTrace()); 370 | LOGGER.error("requestId, {}. 异常堆栈, {}", requestId, stackTrace); 371 | } 372 | 373 | /** 374 | * 是否支持重写Body 375 | * 376 | * @param parameter 方法参数 377 | * @param converter 消息转换器 378 | * @return boolean 379 | */ 380 | @Override 381 | public boolean supports(MethodParameter parameter, Class> converter) { 382 | return true; 383 | } 384 | 385 | /** 386 | * 重写Body 387 | * 388 | * @param object Body对象 389 | * @param parameter 方法参数 390 | * @param type 媒体类型 391 | * @param converter 消息转换器 392 | * @param request 请求数据 393 | * @param response 响应数据 394 | * @return Object 395 | */ 396 | @Override 397 | public Object beforeBodyWrite(Object object, MethodParameter parameter, MediaType type, Class> converter, ServerHttpRequest request, ServerHttpResponse response) { 398 | if (object instanceof Reply) { 399 | return object; 400 | } 401 | 402 | if (object instanceof String) { 403 | return ReplyHelper.success(object).toString(); 404 | } 405 | 406 | return ReplyHelper.success(object); 407 | } 408 | } 409 | -------------------------------------------------------------------------------- /src/main/java/com/insight/common/message/common/Core.java: -------------------------------------------------------------------------------- 1 | package com.insight.common.message.common; 2 | 3 | import com.insight.common.message.common.client.AliyunClient; 4 | import com.insight.common.message.common.client.TaskClient; 5 | import com.insight.common.message.common.dto.ScheduleCall; 6 | import com.insight.utils.SnowflakeCreator; 7 | import com.insight.utils.http.HttpUtil; 8 | import com.insight.utils.pojo.base.BusinessException; 9 | import com.insight.utils.pojo.base.Reply; 10 | import com.insight.utils.pojo.message.InsightMessage; 11 | import com.insight.utils.pojo.message.Schedule; 12 | import com.insight.utils.redis.Redis; 13 | import com.rabbitmq.client.Channel; 14 | import feign.Feign; 15 | import feign.codec.Decoder; 16 | import feign.codec.Encoder; 17 | import feign.jackson.JacksonDecoder; 18 | import feign.jackson.JacksonEncoder; 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | import org.springframework.amqp.core.Message; 22 | import org.springframework.beans.factory.annotation.Value; 23 | import org.springframework.cloud.client.ServiceInstance; 24 | import org.springframework.cloud.client.discovery.DiscoveryClient; 25 | import org.springframework.cloud.openfeign.FeignClientsConfiguration; 26 | import org.springframework.context.annotation.Import; 27 | import org.springframework.mail.SimpleMailMessage; 28 | import org.springframework.mail.javamail.JavaMailSender; 29 | import org.springframework.scheduling.annotation.Async; 30 | import org.springframework.stereotype.Component; 31 | 32 | import java.io.IOException; 33 | import java.net.URI; 34 | import java.net.URISyntaxException; 35 | import java.time.LocalDateTime; 36 | import java.util.ArrayList; 37 | import java.util.List; 38 | import java.util.Map; 39 | import java.util.concurrent.TimeUnit; 40 | 41 | /** 42 | * @author 宣炳刚 43 | * @date 2019/10/2 44 | * @remark 计划任务异步执行核心类 45 | */ 46 | @Component 47 | @Import(FeignClientsConfiguration.class) 48 | public class Core { 49 | private final Logger logger = LoggerFactory.getLogger(this.getClass()); 50 | private final Decoder decoder = new JacksonDecoder(); 51 | private final Encoder encoder = new JacksonEncoder(); 52 | private final DiscoveryClient discoveryClient; 53 | private final JavaMailSender mailSender; 54 | private final SnowflakeCreator creator; 55 | private final MessageDal dal; 56 | 57 | /** 58 | * 邮件发件人 59 | */ 60 | @Value("${insight.mail.sender}") 61 | private String sender; 62 | 63 | /** 64 | * 默认短信模版 65 | */ 66 | @Value("${insight.sms.aliyun.template}") 67 | private String defaultTemplate; 68 | 69 | /** 70 | * 默认短信签名 71 | */ 72 | @Value("${insight.sms.aliyun.sign}") 73 | private String defaultSign; 74 | 75 | /** 76 | * 构造方法 77 | * 78 | * @param discoveryClient DiscoveryClient 79 | * @param mailSender JavaMailSender 80 | * @param creator 雪花算法ID生成器 81 | * @param dal MessageDal 82 | */ 83 | public Core(DiscoveryClient discoveryClient, JavaMailSender mailSender, SnowflakeCreator creator, MessageDal dal) { 84 | this.discoveryClient = discoveryClient; 85 | this.mailSender = mailSender; 86 | this.creator = creator; 87 | this.dal = dal; 88 | } 89 | 90 | /** 91 | * 保存消息到数据库,使用补偿机制保证写入成功 92 | * 93 | * @param schedule 计划任务DTO 94 | * @param channel 队列通道 95 | * @param message 队列消息 96 | */ 97 | @Async 98 | public void addMessage(Schedule schedule, Channel channel, Message message) throws IOException { 99 | InsightMessage msg = schedule.getContent(); 100 | if (msg != null && !addMessage(msg)) { 101 | schedule.setExpireTime(LocalDateTime.now().plusMinutes(msg.getExpire())); 102 | addSchedule(schedule); 103 | } 104 | 105 | channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); 106 | } 107 | 108 | /** 109 | * 通过极光推送消息通知给用户,使用补偿机制保证推送成功 110 | * 111 | * @param schedule 计划任务DTO 112 | * @param channel 队列通道 113 | * @param message 队列消息 114 | */ 115 | @Async 116 | public void pushNotice(Schedule schedule, Channel channel, Message message) throws IOException { 117 | InsightMessage msg = schedule.getContent(); 118 | if (msg != null && !pushNotice(msg)) { 119 | schedule.setExpireTime(LocalDateTime.now().plusMinutes(msg.getExpire())); 120 | addSchedule(schedule); 121 | } 122 | 123 | channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); 124 | } 125 | 126 | /** 127 | * 发送短信给用户,使用补偿机制保证发送成功 128 | * 129 | * @param schedule 计划任务DTO 130 | * @param channel 队列通道 131 | * @param message 队列消息 132 | */ 133 | @Async 134 | public void sendSms(Schedule schedule, Channel channel, Message message) throws IOException { 135 | InsightMessage msg = schedule.getContent(); 136 | if (msg != null) { 137 | sendSms(msg); 138 | schedule.setExpireTime(LocalDateTime.now().plusMinutes(msg.getExpire())); 139 | addSchedule(schedule); 140 | } 141 | 142 | channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); 143 | } 144 | 145 | /** 146 | * 发送邮件给用户,使用补偿机制保证发送成功 147 | * 148 | * @param schedule 计划任务DTO 149 | * @param channel 队列通道 150 | * @param message 队列消息 151 | */ 152 | @Async 153 | public void sendMail(Schedule schedule, Channel channel, Message message) throws IOException { 154 | InsightMessage msg = schedule.getContent(); 155 | if (msg != null && !sendMail(msg)) { 156 | schedule.setExpireTime(LocalDateTime.now().plusMinutes(msg.getExpire())); 157 | addSchedule(schedule); 158 | } 159 | 160 | channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); 161 | } 162 | 163 | /** 164 | * 本地调用,使用补偿机制保证调用成功 165 | * 166 | * @param schedule 计划任务DTO 167 | * @param channel 队列通道 168 | * @param message 队列消息 169 | */ 170 | @Async 171 | public void localCall(Schedule schedule, Channel channel, Message message) throws IOException, URISyntaxException { 172 | ScheduleCall call = schedule.getContent(); 173 | String host = getServiceUrl(call.getService()); 174 | URI uri = new URI(host + call.getUrl()); 175 | Object body = call.getBody(); 176 | TaskClient taskClient = Feign.builder().decoder(decoder).encoder(encoder) 177 | .requestInterceptor(template -> { 178 | Map map = call.getHeaders(); 179 | if (map != null) { 180 | for (String k : map.keySet()) { 181 | String v = map.get(k); 182 | template.header(k, v); 183 | } 184 | } 185 | }).target(TaskClient.class, host); 186 | try { 187 | Reply reply; 188 | switch (call.getMethod()) { 189 | case "GET" -> reply = taskClient.get(uri); 190 | case "POST" -> reply = taskClient.post(uri, body); 191 | case "PUT" -> reply = taskClient.put(uri, body); 192 | case "DELETE" -> reply = taskClient.delete(uri, body); 193 | default -> { 194 | return; 195 | } 196 | } 197 | if (!reply.getSuccess()) { 198 | logger.error("本地调用发生错误! 错误信息为: {}", reply.getMessage()); 199 | addSchedule(schedule); 200 | } 201 | } catch (Exception ex) { 202 | logger.error("本地调用发生错误! 异常信息为: {}", ex.getMessage()); 203 | addSchedule(schedule); 204 | } finally { 205 | channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); 206 | } 207 | } 208 | 209 | /** 210 | * 从队列订阅远程调用类型的计划任务 211 | * 212 | * @param schedule 计划任务DTO 213 | * @param channel 队列通道 214 | * @param message 队列消息 215 | */ 216 | @Async 217 | public void remoteCall(Schedule schedule, Channel channel, Message message) throws IOException { 218 | ScheduleCall call = schedule.getContent(); 219 | String method = call.getMethod(); 220 | String url = call.getUrl(); 221 | Map headers = call.getHeaders(); 222 | Object body = call.getBody(); 223 | try { 224 | String result; 225 | switch (method) { 226 | case "GET" -> result = HttpUtil.get(url, headers, String.class); 227 | case "POST" -> result = HttpUtil.post(url, body, headers, String.class); 228 | case "PUT" -> result = HttpUtil.put(url, body, headers, String.class); 229 | case "DELETE" -> result = HttpUtil.delete(url, body, headers, String.class); 230 | default -> { 231 | return; 232 | } 233 | } 234 | if (result == null || result.isEmpty() || result.contains("error")) { 235 | logger.error("本地调用发生错误! 错误信息为: {}", result); 236 | addSchedule(schedule); 237 | } 238 | } catch (Exception ex) { 239 | logger.error("本地调用发生错误! 异常信息为: {}", ex.getMessage()); 240 | addSchedule(schedule); 241 | } finally { 242 | channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); 243 | } 244 | } 245 | 246 | /** 247 | * 保存计划任务数据 248 | * 249 | * @param schedule 计划任务DTO 250 | */ 251 | private void addSchedule(Schedule schedule) { 252 | var expireTime = schedule.getExpireTime(); 253 | LocalDateTime now = LocalDateTime.now(); 254 | Long id = schedule.getId(); 255 | if (id == null) { 256 | schedule.setId(creator.nextId(3)); 257 | schedule.setTaskTime(now.plusSeconds(10)); 258 | schedule.setCount(0); 259 | schedule.setInvalid(false); 260 | schedule.setCreatedTime(now); 261 | } else { 262 | int count = schedule.getCount(); 263 | if (count > 99 || (expireTime != null && now.isAfter(expireTime))) { 264 | schedule.setInvalid(true); 265 | } else { 266 | schedule.setTaskTime(now.plusSeconds((long) Math.pow(count, 2))); 267 | schedule.setCount(count + 1); 268 | } 269 | } 270 | 271 | try { 272 | // 保存计划任务数据 273 | dal.addSchedule(schedule); 274 | } catch (Exception ex) { 275 | // 保存计划任务数据失败,记录日志并发短信通知运维人员 276 | logger.warn("保存任务失败! 任务数据为: {}", schedule); 277 | 278 | String key = "Config:Warning"; 279 | boolean isWarning = Redis.hasKey(key); 280 | if (isWarning) { 281 | return; 282 | } 283 | 284 | List list = new ArrayList<>(); 285 | list.add("13958085903"); 286 | InsightMessage message = new InsightMessage(); 287 | message.setReceivers(list); 288 | message.setContent(now + "保存任务失败! 请尽快处理"); 289 | 290 | Redis.set(key, now.toString(), 24L, TimeUnit.HOURS); 291 | sendSms(message); 292 | } 293 | } 294 | 295 | /** 296 | * 根据eureka服务名获取服务地址 297 | * 298 | * @param service 服务名 299 | * @return URL 300 | */ 301 | private String getServiceUrl(String service) { 302 | try { 303 | List list = discoveryClient.getInstances(service); 304 | if (list == null || list.isEmpty()) { 305 | return null; 306 | } 307 | 308 | URI uri = list.get(0).getUri(); 309 | return uri.toString(); 310 | } catch (Exception ex) { 311 | logger.error("从eureka 获取服务:{}的地址出现异常:{}", service, ex.getMessage()); 312 | 313 | return null; 314 | } 315 | } 316 | 317 | /** 318 | * 存储消息 319 | * 320 | * @param message 消息DTO 321 | * @return 是否存储成功 322 | */ 323 | private boolean addMessage(InsightMessage message) { 324 | try { 325 | dal.addMessage(message); 326 | return true; 327 | } catch (Exception ex) { 328 | logger.error("存储消息发生错误! 异常信息为: {}", ex.getMessage()); 329 | return false; 330 | } 331 | } 332 | 333 | /** 334 | * 推送通知 335 | * 336 | * @param message 消息DTO 337 | * @return 是否推送成功 338 | */ 339 | private boolean pushNotice(InsightMessage message) { 340 | try { 341 | return true; 342 | } catch (Exception ex) { 343 | logger.error("推送消息发生错误! 异常信息为: {}", ex.getMessage()); 344 | return false; 345 | } 346 | } 347 | 348 | /** 349 | * 发送短信 350 | * 351 | * @param message 消息DTO 352 | */ 353 | public void sendSms(InsightMessage message) { 354 | var receivers = message.getReceivers(); 355 | if (receivers == null || receivers.isEmpty()) { 356 | throw new BusinessException("短信接收人手机号不能为空"); 357 | } 358 | 359 | try { 360 | if (receivers.size() > 1) { 361 | // 群发 362 | AliyunClient.createClient(); 363 | } else { 364 | var phone = receivers.get(0); 365 | AliyunClient.sendTemplateMessage(phone, defaultTemplate, message.getParams(), defaultSign); 366 | } 367 | } catch (Exception ex) { 368 | throw new BusinessException("发送短信发生错误! 异常信息为: " + ex.getMessage()); 369 | } 370 | } 371 | 372 | /** 373 | * 发送邮件 374 | * 375 | * @param message 消息DTO 376 | * @return 是否发送成功 377 | */ 378 | private boolean sendMail(InsightMessage message) { 379 | try { 380 | List list = message.getReceivers(); 381 | String receivers = String.join(";", list); 382 | SimpleMailMessage mail = new SimpleMailMessage(); 383 | mail.setFrom(sender); 384 | mail.setTo(receivers); 385 | mail.setSubject(message.getTitle()); 386 | mail.setText(message.getContent()); 387 | 388 | mailSender.send(mail); 389 | return true; 390 | } catch (Exception ex) { 391 | logger.error("发送邮件发生错误! 异常信息为: {}", ex.getMessage()); 392 | return false; 393 | } 394 | } 395 | } 396 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------