From 12cbd2bd96361469dc85837ff3d4c12d4d5cdddf Mon Sep 17 00:00:00 2001 From: Yohann0617 <852221040@qq.com> Date: Mon, 25 Nov 2024 00:44:19 +0800 Subject: [PATCH] update --- pom.xml | 5 + .../service/impl/DingMessageServiceImpl.java | 95 +++++++++++++++++++ .../service/impl/InstanceServiceImpl.java | 3 +- .../service/impl/OciServiceImpl.java | 12 ++- .../service/impl/TgMessageServiceImpl.java | 5 +- .../utils/MessageServiceFactory.java | 5 + src/main/resources/application.yml | 5 + 7 files changed, 123 insertions(+), 7 deletions(-) create mode 100644 src/main/java/com/yohann/ocihelper/service/impl/DingMessageServiceImpl.java diff --git a/pom.xml b/pom.xml index 81ba4b8..4cd37ef 100644 --- a/pom.xml +++ b/pom.xml @@ -89,6 +89,11 @@ compile + + com.fasterxml.jackson.core + jackson-databind + + cn.hutool hutool-all diff --git a/src/main/java/com/yohann/ocihelper/service/impl/DingMessageServiceImpl.java b/src/main/java/com/yohann/ocihelper/service/impl/DingMessageServiceImpl.java new file mode 100644 index 0000000..da21119 --- /dev/null +++ b/src/main/java/com/yohann/ocihelper/service/impl/DingMessageServiceImpl.java @@ -0,0 +1,95 @@ +package com.yohann.ocihelper.service.impl; + +import cn.hutool.core.util.StrUtil; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.yohann.ocihelper.service.IMessageService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.codec.binary.Base64; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +/** + *

+ * DingMessageServiceImpl + *

+ * + * @author yuhui.fan + * @since 2024/11/8 12:06 + */ +@Service +@Slf4j +public class DingMessageServiceImpl implements IMessageService { + + @Value("${ding-cfg.access-token}") + private String token; + @Value("${ding-cfg.secret}") + private String secret; + + private static final String DING_URL = "https://oapi.dingtalk.com/robot/send?access_token=%s"; + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + @Override + public void sendMessage(String message) { + if (StrUtil.isNotBlank(token) && StrUtil.isNotBlank(secret)) { + try { + sendDingTalkMessage(String.format(DING_URL, token), secret, message); + } catch (Exception e) { + log.info("Failed to send dingding message, error: {}", e.getLocalizedMessage()); + } + } + } + + public static void sendDingTalkMessage(String webhook, String secret, String message) throws Exception { + String url = webhook; + if (secret != null && !secret.isEmpty()) { + long timestamp = System.currentTimeMillis(); + String sign = generateSign(timestamp, secret); + url += "×tamp=" + timestamp + "&sign=" + URLEncoder.encode(sign, "UTF-8"); + } + + Map payload = new HashMap<>(); + payload.put("msgtype", "text"); + Map text = new HashMap<>(); + text.put("content", message); + payload.put("text", text); + + sendPostRequest(url, OBJECT_MAPPER.writeValueAsString(payload)); + } + + private static String generateSign(long timestamp, String secret) throws Exception { + String stringToSign = timestamp + "\n" + secret; + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8)); + return new String(Base64.encodeBase64(signData)); + } + + private static void sendPostRequest(String url, String jsonPayload) throws Exception { + URL connectionUrl = new URL(url); + HttpURLConnection connection = (HttpURLConnection) connectionUrl.openConnection(); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setDoOutput(true); + + try (OutputStream os = connection.getOutputStream()) { + os.write(jsonPayload.getBytes(StandardCharsets.UTF_8)); + } + + int responseCode = connection.getResponseCode(); + if (responseCode == 200) { + log.info("dingding message sent successfully!"); + } else { + log.info("Failed to send dingding message, HTTP response code: {}", responseCode); + } + } +} diff --git a/src/main/java/com/yohann/ocihelper/service/impl/InstanceServiceImpl.java b/src/main/java/com/yohann/ocihelper/service/impl/InstanceServiceImpl.java index 3aaa155..15f897d 100644 --- a/src/main/java/com/yohann/ocihelper/service/impl/InstanceServiceImpl.java +++ b/src/main/java/com/yohann/ocihelper/service/impl/InstanceServiceImpl.java @@ -97,10 +97,11 @@ public CreateInstanceDTO createInstance(OracleInstanceFetcher fetcher) { instanceDetail.getShape(), instanceDetail.getPublicIp(), instanceDetail.getRootPassword()); + messageServiceFactory.getMessageService(MessageTypeEnum.MSG_TYPE_DING_DING).sendMessage(message); try { messageServiceFactory.getMessageService(MessageTypeEnum.MSG_TYPE_TELEGRAM).sendMessage(message); } catch (Exception e) { - log.error("【开机任务】用户:[{}] ,区域:[{}] ,系统架构:[{}] 开机成功,实例IP:{} ,但是消息发送失败", + log.error("【开机任务】用户:[{}] ,区域:[{}] ,系统架构:[{}] 开机成功,实例IP:{} ,但是TG消息发送失败", instanceDetail.getUsername(), instanceDetail.getRegion(), instanceDetail.getShape(), instanceDetail.getPublicIp()); } diff --git a/src/main/java/com/yohann/ocihelper/service/impl/OciServiceImpl.java b/src/main/java/com/yohann/ocihelper/service/impl/OciServiceImpl.java index 5f9ecaf..3789db4 100644 --- a/src/main/java/com/yohann/ocihelper/service/impl/OciServiceImpl.java +++ b/src/main/java/com/yohann/ocihelper/service/impl/OciServiceImpl.java @@ -216,6 +216,7 @@ public void createInstance(CreateInstanceParams params) { Long.valueOf(params.getDisk()), params.getCreateNumbers(), params.getRootPassword()); + messageServiceFactory.getMessageService(MessageTypeEnum.MSG_TYPE_DING_DING).sendMessage(beginCreateMsg); messageServiceFactory.getMessageService(MessageTypeEnum.MSG_TYPE_TELEGRAM).sendMessage(beginCreateMsg); } @@ -489,14 +490,15 @@ private void sendChangeIpMsg(String username, String region, String instanceName log.info("✔✔✔【更换公共IP】用户:[{}] ,区域:[{}] ,实例:[{}] ,更换公共IP成功,新的公共IP地址:{} ✔✔✔", username, region, instanceName, publicIp); + String message = String.format(CHANGE_IP_MESSAGE_TEMPLATE, + username, + LocalDateTime.now().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)), + region, instanceName, publicIp); + messageServiceFactory.getMessageService(MessageTypeEnum.MSG_TYPE_DING_DING).sendMessage(message); try { - String message = String.format(CHANGE_IP_MESSAGE_TEMPLATE, - username, - LocalDateTime.now().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)), - region, instanceName, publicIp); messageServiceFactory.getMessageService(MessageTypeEnum.MSG_TYPE_TELEGRAM).sendMessage(message); } catch (Exception e) { - log.error("【开机任务】用户:[{}] ,区域:[{}] ,实例:[{}] 更换公共IP成功,新的实例IP:{} ,但是消息发送失败", + log.error("【开机任务】用户:[{}] ,区域:[{}] ,实例:[{}] 更换公共IP成功,新的实例IP:{} ,但是TG消息发送失败", username, region, instanceName, publicIp); } diff --git a/src/main/java/com/yohann/ocihelper/service/impl/TgMessageServiceImpl.java b/src/main/java/com/yohann/ocihelper/service/impl/TgMessageServiceImpl.java index d88a69d..2792828 100644 --- a/src/main/java/com/yohann/ocihelper/service/impl/TgMessageServiceImpl.java +++ b/src/main/java/com/yohann/ocihelper/service/impl/TgMessageServiceImpl.java @@ -1,5 +1,6 @@ package com.yohann.ocihelper.service.impl; +import cn.hutool.core.util.StrUtil; import cn.hutool.http.HttpResponse; import cn.hutool.http.HttpUtil; import com.yohann.ocihelper.service.IMessageService; @@ -32,7 +33,9 @@ public class TgMessageServiceImpl implements IMessageService { @Override public void sendMessage(String message) { - doSend(message); + if (StrUtil.isNotBlank(chatId) && StrUtil.isNotBlank(botToken)) { + doSend(message); + } } private void doSend(String message) { diff --git a/src/main/java/com/yohann/ocihelper/utils/MessageServiceFactory.java b/src/main/java/com/yohann/ocihelper/utils/MessageServiceFactory.java index faadbe4..704391b 100644 --- a/src/main/java/com/yohann/ocihelper/utils/MessageServiceFactory.java +++ b/src/main/java/com/yohann/ocihelper/utils/MessageServiceFactory.java @@ -2,6 +2,7 @@ import com.yohann.ocihelper.enums.MessageTypeEnum; import com.yohann.ocihelper.service.IMessageService; +import com.yohann.ocihelper.service.impl.DingMessageServiceImpl; import com.yohann.ocihelper.service.impl.TgMessageServiceImpl; import org.springframework.stereotype.Component; @@ -20,11 +21,15 @@ public class MessageServiceFactory { @Resource private TgMessageServiceImpl tgMessageService; + @Resource + private DingMessageServiceImpl dingMessageService; public IMessageService getMessageService(MessageTypeEnum type) { switch (type) { case MSG_TYPE_TELEGRAM: return tgMessageService; + case MSG_TYPE_DING_DING: + return dingMessageService; default: throw new IllegalArgumentException("Unknown message service type: " + type.getType()); } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index fbcafea..d680ef1 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -11,6 +11,11 @@ web: tg-cfg: token: xxxx:xxxx chat-id: xxxxxx + +# 钉钉机器人通知配置 (可选) +ding-cfg: + access-token: + secret: # --------------------------------------- 用户自定义修改项 ------------------------------------ spring: