Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
Yohann0617 committed Nov 24, 2024
1 parent 1fd9488 commit 12cbd2b
Show file tree
Hide file tree
Showing 7 changed files with 123 additions and 7 deletions.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,11 @@
<scope>compile</scope>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -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;

/**
* <p>
* DingMessageServiceImpl
* </p >
*
* @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 += "&timestamp=" + timestamp + "&sign=" + URLEncoder.encode(sign, "UTF-8");
}

Map<String, Object> payload = new HashMap<>();
payload.put("msgtype", "text");
Map<String, String> 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);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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());
}
Expand Down
5 changes: 5 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ web:
tg-cfg:
token: xxxx:xxxx
chat-id: xxxxxx

# 钉钉机器人通知配置 (可选)
ding-cfg:
access-token:
secret:
# --------------------------------------- 用户自定义修改项 ------------------------------------

spring:
Expand Down

0 comments on commit 12cbd2b

Please sign in to comment.