From f7f4c204dc4a8bbd963d873b603627d2c2163f22 Mon Sep 17 00:00:00 2001 From: Carpe-Wang <78642589+Carpe-Wang@users.noreply.github.com> Date: Fri, 26 Jan 2024 16:15:21 +0800 Subject: [PATCH] add wechat alarm notify, refactor code (#1516) Co-authored-by: Carpe-Wang --- .../service/impl/AlertDefineServiceImpl.java | 4 +- .../impl/WeChatAlertNotifyHandlerImpl.java | 77 ++++++++++++++++++- .../controller/MonitorsController.java | 4 +- 3 files changed, 79 insertions(+), 6 deletions(-) diff --git a/alerter/src/main/java/org/dromara/hertzbeat/alert/service/impl/AlertDefineServiceImpl.java b/alerter/src/main/java/org/dromara/hertzbeat/alert/service/impl/AlertDefineServiceImpl.java index e4f3e3722a0..e5e3a21b118 100644 --- a/alerter/src/main/java/org/dromara/hertzbeat/alert/service/impl/AlertDefineServiceImpl.java +++ b/alerter/src/main/java/org/dromara/hertzbeat/alert/service/impl/AlertDefineServiceImpl.java @@ -109,7 +109,9 @@ public Page getMonitorBindAlertDefines(Specification s public void applyBindAlertDefineMonitors(Long alertId, List alertDefineBinds) { // todo checks whether the alarm definition and monitoring exist // todo 校验此告警定义和监控是否存在 - + if (!alertDefineBindDao.existsById(alertId)){ + alertDefineBindDao.deleteAlertDefineBindsByAlertDefineIdEquals(alertId); + } // Delete all associations of this alarm alertDefineBindDao.deleteAlertDefineBindsByAlertDefineIdEquals(alertId); // Save the associated diff --git a/manager/src/main/java/org/dromara/hertzbeat/manager/component/alerter/impl/WeChatAlertNotifyHandlerImpl.java b/manager/src/main/java/org/dromara/hertzbeat/manager/component/alerter/impl/WeChatAlertNotifyHandlerImpl.java index fe0dba61df0..2acfc2840b0 100644 --- a/manager/src/main/java/org/dromara/hertzbeat/manager/component/alerter/impl/WeChatAlertNotifyHandlerImpl.java +++ b/manager/src/main/java/org/dromara/hertzbeat/manager/component/alerter/impl/WeChatAlertNotifyHandlerImpl.java @@ -20,15 +20,88 @@ import org.dromara.hertzbeat.common.entity.alerter.Alert; import org.dromara.hertzbeat.common.entity.manager.NoticeReceiver; import org.dromara.hertzbeat.common.entity.manager.NoticeTemplate; -import org.dromara.hertzbeat.manager.component.alerter.AlertNotifyHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.URI; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; /** * */ final class WeChatAlertNotifyHandlerImpl extends AbstractAlertNotifyHandlerImpl { + private static final Logger log = LoggerFactory.getLogger(WeChatAlertNotifyHandlerImpl.class); + private static final String CORP_ID = "YOUR_CORP_ID"; + private static final String CORP_SECRET = "YOUR_CORP_SECRET"; + private static final String AGENT_ID = "YOUR_AGENT_ID"; + private static final String GET_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + CORP_ID + "&corpsecret=" + CORP_SECRET; + private static final String SEND_MESSAGE_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="; + private static final String ACCESS_TOKEN = "access_token"; + @Override public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) { - // todo + try { + String accessToken = getAccessToken(); + String messageContent = constructMessageContent(receiver, noticeTemplate, alert); + sendMessage(accessToken, messageContent); + } catch (Exception e) { + log.error("Failed to send WeChat alert", e); + } + } + + private String getAccessToken() throws Exception { + HttpClient client = HttpClient.newHttpClient(); + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI(GET_TOKEN_URL)) + .GET() + .build(); + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + JsonParser parser = new JsonParser(); + JsonObject jsonObject = parser.parse(response.body()).getAsJsonObject(); + String accessToken = null; + if (jsonObject.has(ACCESS_TOKEN)) { + accessToken = jsonObject.get(ACCESS_TOKEN).getAsString(); + } else { + // todo 处理错误情况,例如记录日志或抛出异常 + log.error("Failed to obtain ACCESS_TOKEN from response: {}", response.body()); + } + + return accessToken; + } + + private String constructMessageContent(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) { + // 示例:构造一个文本消息内容 + JsonObject messageContent = new JsonObject(); + messageContent.addProperty("msgtype", "text"); + JsonObject textContent = new JsonObject(); + + // 这里可以根据NoticeTemplate和Alert信息构造消息内容 + String alertMessage = String.format("警告:%s\n详情:%s", alert.getAlertDefineId(), alert.getContent()); + textContent.addProperty("content", alertMessage); + messageContent.add("text", textContent); + + // 如果需要@某人,可以在这里添加 + JsonObject atInfo = new JsonObject(); + atInfo.addProperty("isAtAll", false); // 是否@所有人 + messageContent.add("at", atInfo); + + // 返回JSON字符串 + return messageContent.toString(); + } + + private void sendMessage(String accessToken, String messageContent) throws Exception { + HttpClient client = HttpClient.newHttpClient(); + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI(SEND_MESSAGE_URL + accessToken)) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(messageContent)) + .build(); + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + // 检查消息是否成功发送 + log.info("Message sent response: {}", response.body()); } @Override diff --git a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/MonitorsController.java b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/MonitorsController.java index 5eba1978841..3d019bf79c8 100644 --- a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/MonitorsController.java +++ b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/MonitorsController.java @@ -211,12 +211,10 @@ public ResponseEntity> export(MultipartFile file) throws Exception @Operation(summary = "copy monitors by ids", description = "根据id批量复制monitor") public ResponseEntity> duplicateMonitors( @Parameter(description = "Monitor ID List | 监控任务ID列表", example = "6565463543") @RequestParam List ids - ) throws Exception { + ){ if (ids != null && !ids.isEmpty()) { monitorService.copyMonitors(ids); } return ResponseEntity.ok(Message.success("copy success")); } - - }