Unverified Commit 10ae3036 authored by zhu-mingye's avatar zhu-mingye Committed by GitHub

[refactor][alert] refactor alert module (#1577)

* refactor alert module * format code * refactor alert module * modify constant name * modify alert extends doc * modify alert extends doc * modify alert extends doc * format code * format code of spotless * format code of spotless * fix enum * refactor alert module of enum * modify doc * modify code
parent ab555936
...@@ -39,5 +39,21 @@ ...@@ -39,5 +39,21 @@
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.alert;
/** AlertBaseConstant */
public class AlertBaseConstant {
/** base constant */
public static final String MARKDOWN_QUOTE_MIDDLE_LINE = "- ";
public static final String TAB = "\t";
public static final String ENTER_LINE = "\n";
public static final String MARKDOWN_QUOTE_RIGHT_TAG = "> ";
public static final String MARKDOWN_QUOTE_RIGHT_TAG_WITH_SPACE = ">";
public static final String MARKDOWN_ENTER_BACK_SLASH = "/n";
public static final String CHARSET = "UTF-8";
public static final String PROXY_ENABLE = "isEnableProxy";
public static final String WEB_HOOK = "webhook";
public static final String KEYWORD = "keyword";
public static final String SECRET = "secret";
public static final String MSG_TYPE = "msgtype";
public static final String AT_MOBILES = "atMobiles";
public static final String AT_USERIDS = "atUserIds";
public static final String AT_ALL = "isAtAll";
public static final String PROXY = "proxy";
public static final String PORT = "port";
public static final String USER = "user";
public static final String AT_USERS = "users";
public static final String PASSWORD = "password";
public AlertBaseConstant() {
throw new UnsupportedOperationException(
"This is a utility class and cannot be instantiated");
}
}
...@@ -26,25 +26,25 @@ package org.dinky.alert; ...@@ -26,25 +26,25 @@ package org.dinky.alert;
* @since 2022/2/23 21:32 * @since 2022/2/23 21:32
*/ */
public enum ShowType { public enum ShowType {
MARKDOWN(0, "markdown"), // 通用markdown格式 /** markdown */
TEXT(1, "text"), // 通用文本格式 MARKDOWN("markdown"),
POST(2, "post"), // 飞书的富文本msgType /** text */
TABLE(0, "table"), // table格式 TEXT("text"),
ATTACHMENT(3, "attachment"), // 邮件相关 只发送附件 /** post of feishu */
TABLE_ATTACHMENT(4, "table attachment"); // 邮件相关 邮件表格+附件 POST("post"),
/** table */
TABLE("table"),
/** attachment */
ATTACHMENT("attachment"),
/** table and attachment */
TABLE_ATTACHMENT("table attachment");
private int code;
private String value; private String value;
ShowType(int code, String value) { ShowType(String value) {
this.code = code;
this.value = value; this.value = value;
} }
public int getCode() {
return code;
}
public String getValue() { public String getValue() {
return value; return value;
} }
......
...@@ -17,10 +17,9 @@ ...@@ -17,10 +17,9 @@
* *
*/ */
package org.dinky.alert.email; package org.dinky.utils;
import org.dinky.alert.AlertException; import org.dinky.alert.AlertException;
import org.dinky.utils.JSONUtil;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Cell;
......
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
* *
*/ */
package org.dinky.alert.feishu; package org.dinky.utils;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthScope;
......
...@@ -19,41 +19,9 @@ ...@@ -19,41 +19,9 @@
package org.dinky.alert.dingtalk; package org.dinky.alert.dingtalk;
/** import org.dinky.alert.AlertBaseConstant;
* DingTalkConstants
*
* @author wenmo
* @since 2022/2/23 19:37
*/
public final class DingTalkConstants {
static final String TYPE = "DingTalk";
static final String MARKDOWN_QUOTE = "- ";
static final String MARKDOWN_ENTER = "\n";
static final String PROXY_ENABLE = "isEnableProxy";
static final String WEB_HOOK = "webhook";
static final String KEYWORD = "keyword";
static final String SECRET = "secret";
static final String MSG_TYPE = "msgtype";
static final String AT_MOBILES = "atMobiles";
static final String AT_USERIDS = "atUserIds";
static final String AT_ALL = "isAtAll";
static final String PROXY = "proxy";
static final String PORT = "port";
static final String USER = "user";
static final String PASSWORD = "password"; /** DingTalkConstants */
public class DingTalkConstants extends AlertBaseConstant {
public static final String TYPE = "DingTalk";
} }
...@@ -19,6 +19,8 @@ ...@@ -19,6 +19,8 @@
package org.dinky.alert.dingtalk; package org.dinky.alert.dingtalk;
import static java.util.Objects.requireNonNull;
import org.dinky.alert.AlertResult; import org.dinky.alert.AlertResult;
import org.dinky.alert.AlertSendResponse; import org.dinky.alert.AlertSendResponse;
import org.dinky.alert.ShowType; import org.dinky.alert.ShowType;
...@@ -85,7 +87,10 @@ public class DingTalkSender { ...@@ -85,7 +87,10 @@ public class DingTalkSender {
url = config.get(DingTalkConstants.WEB_HOOK); url = config.get(DingTalkConstants.WEB_HOOK);
keyword = config.get(DingTalkConstants.KEYWORD); keyword = config.get(DingTalkConstants.KEYWORD);
secret = config.get(DingTalkConstants.SECRET); secret = config.get(DingTalkConstants.SECRET);
msgType = config.get(DingTalkConstants.MSG_TYPE); msgType = config.get(DingTalkConstants.MSG_TYPE);
requireNonNull(msgType, DingTalkConstants.MSG_TYPE + " must not null");
atMobiles = config.get(DingTalkConstants.AT_MOBILES); atMobiles = config.get(DingTalkConstants.AT_MOBILES);
atUserIds = config.get(DingTalkConstants.AT_USERIDS); atUserIds = config.get(DingTalkConstants.AT_USERIDS);
atAll = Boolean.valueOf(config.get(DingTalkConstants.AT_ALL)); atAll = Boolean.valueOf(config.get(DingTalkConstants.AT_ALL));
...@@ -98,11 +103,18 @@ public class DingTalkSender { ...@@ -98,11 +103,18 @@ public class DingTalkSender {
} }
} }
/**
* send msg of main
*
* @param title : send msg title
* @param content: send msg content
* @return AlertResult
*/
public AlertResult send(String title, String content) { public AlertResult send(String title, String content) {
AlertResult alertResult; AlertResult alertResult;
try { try {
String resp = sendMsg(title, content); String sendMsgOfResult = buildSendMsgAndSendOfResult(title, content);
return checkMsgResult(resp); return checkMsgResult(sendMsgOfResult);
} catch (Exception e) { } catch (Exception e) {
logger.info("send ding talk alert msg exception : {}", e.getMessage()); logger.info("send ding talk alert msg exception : {}", e.getMessage());
alertResult = new AlertResult(); alertResult = new AlertResult();
...@@ -112,25 +124,24 @@ public class DingTalkSender { ...@@ -112,25 +124,24 @@ public class DingTalkSender {
return alertResult; return alertResult;
} }
private String sendMsg(String title, String content) throws IOException { /**
String msg = generateMsgJson(title, content); * 1. budild send msg 2. request send 3. return response msg
String httpUrl = url; *
if (Asserts.isNotNullString(secret)) { * @param title
httpUrl = generateSignedUrl(); * @param content
} * @return
HttpPost httpPost = new HttpPost(httpUrl); * @throws IOException
StringEntity stringEntity = new StringEntity(msg, StandardCharsets.UTF_8); */
httpPost.setEntity(stringEntity); private String buildSendMsgAndSendOfResult(String title, String content) throws IOException {
httpPost.addHeader("Content-Type", "application/json; charset=utf-8"); String msg = generateMsgBody(title, content);
String httpUrl = Asserts.isNotNullString(secret) ? generateSignedUrl() : url;
HttpPost httpPost = buildHttpPost(httpUrl, msg);
CloseableHttpClient httpClient; CloseableHttpClient httpClient;
if (Boolean.TRUE.equals(enableProxy)) { if (Boolean.TRUE.equals(enableProxy)) {
HttpHost httpProxy = new HttpHost(proxy, port); httpClient = getCloseableHttpClientOfProxy(httpPost);
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(
new AuthScope(httpProxy), new UsernamePasswordCredentials(user, password));
httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
RequestConfig rcf = RequestConfig.custom().setProxy(httpProxy).build();
httpPost.setConfig(rcf);
} else { } else {
httpClient = HttpClients.createDefault(); httpClient = HttpClients.createDefault();
} }
...@@ -139,7 +150,7 @@ public class DingTalkSender { ...@@ -139,7 +150,7 @@ public class DingTalkSender {
String resp; String resp;
try { try {
HttpEntity httpEntity = response.getEntity(); HttpEntity httpEntity = response.getEntity();
resp = EntityUtils.toString(httpEntity, "UTF-8"); resp = EntityUtils.toString(httpEntity, DingTalkConstants.CHARSET);
EntityUtils.consume(httpEntity); EntityUtils.consume(httpEntity);
} finally { } finally {
response.close(); response.close();
...@@ -150,34 +161,86 @@ public class DingTalkSender { ...@@ -150,34 +161,86 @@ public class DingTalkSender {
} }
} }
private String generateMsgJson(String title, String content) { /**
if (Asserts.isNullString(msgType)) { * build httpPost
msgType = ShowType.TEXT.getValue(); *
* @param httpUrl
* @param msg
* @return HttpPost
*/
private static HttpPost buildHttpPost(String httpUrl, String msg) {
HttpPost httpPost = new HttpPost(httpUrl);
StringEntity stringEntity = new StringEntity(msg, StandardCharsets.UTF_8);
httpPost.setEntity(stringEntity);
httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
return httpPost;
}
/**
* get CloseableHttpClient Of Proxy
*
* @param httpPost
* @return
*/
private CloseableHttpClient getCloseableHttpClientOfProxy(HttpPost httpPost) {
CloseableHttpClient httpClient;
HttpHost httpProxy = new HttpHost(proxy, port);
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(
new AuthScope(httpProxy), new UsernamePasswordCredentials(user, password));
httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
RequestConfig rcf = RequestConfig.custom().setProxy(httpProxy).build();
httpPost.setConfig(rcf);
return httpClient;
} }
/**
* Generate Msg of parse Json 1. put the msg type 2. build the msg body of send type 3. build
* the At User list
*
* @param title
* @param content
* @return String
*/
private String generateMsgBody(String title, String content) {
Map<String, Object> items = new HashMap<>(); Map<String, Object> items = new HashMap<>();
items.put("msgtype", msgType); items.put(DingTalkConstants.MSG_TYPE, msgType);
Map<String, Object> text = new HashMap<>(); Map<String, Object> text = new HashMap<>();
items.put(msgType, text); items.put(msgType, text);
if (ShowType.MARKDOWN.getValue().equals(msgType)) { if (ShowType.MARKDOWN.getValue().equals(msgType)) {
generateMarkdownMsg(title, content, text); buildMarkdownMsg(title, content, text);
} else { } else {
generateTextMsg(title, content, text); buildTextMsg(title, content, text);
} }
setMsgAt(items); buildAtUserList(items);
return JSONUtil.toJsonString(items); return JSONUtil.toJsonString(items);
} }
private void generateTextMsg(String title, String content, Map<String, Object> text) { /**
* Generate Text Msg
*
* @param title
* @param content
* @param text
*/
private void buildTextMsg(String title, String content, Map<String, Object> text) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
if (Asserts.isNotNullString(keyword)) { if (Asserts.isNotNullString(keyword)) {
builder.append(keyword); builder.append(keyword);
builder.append("\n"); builder.append(DingTalkConstants.ENTER_LINE);
} }
String txt = genrateResultMsg(title, content, builder); String finalResultMsgBody = buildFinalResultMsgBody(title, content, builder);
text.put("content", txt); text.put("content", finalResultMsgBody);
} }
private void generateMarkdownMsg(String title, String content, Map<String, Object> text) { /**
* Generate Markdown Msg
*
* @param title
* @param content
* @param text
*/
private void buildMarkdownMsg(String title, String content, Map<String, Object> text) {
StringBuilder builder = new StringBuilder("# "); StringBuilder builder = new StringBuilder("# ");
if (Asserts.isNotNullString(keyword)) { if (Asserts.isNotNullString(keyword)) {
builder.append(" "); builder.append(" ");
...@@ -203,78 +266,96 @@ public class DingTalkSender { ...@@ -203,78 +266,96 @@ public class DingTalkSender {
}); });
} }
builder.append("\n\n"); builder.append("\n\n");
String txt = genrateResultMsg(title, content, builder); String finalResultMsgBody = buildFinalResultMsgBody(title, content, builder);
text.put("title", title); text.put("title", title);
text.put("text", txt); text.put("text", finalResultMsgBody);
} }
/** /**
* 公共生成 markdown 和 text 消息 * Generate markdown and text msg of public
* *
* @param title 标题 * @param title
* @param content 内容 * @param content
* @param builder 拼接字符串 * @param builder
* @return * @return String
*/ */
private String genrateResultMsg(String title, String content, StringBuilder builder) { private String buildFinalResultMsgBody(String title, String content, StringBuilder builder) {
List<LinkedHashMap> mapSendResultItemsList = JSONUtil.toList(content, LinkedHashMap.class); List<LinkedHashMap> mapSendResultItemsList = JSONUtil.toList(content, LinkedHashMap.class);
if (null == mapSendResultItemsList || mapSendResultItemsList.isEmpty()) { if (null == mapSendResultItemsList || mapSendResultItemsList.isEmpty()) {
logger.error("itemsList is null"); logger.error("itemsList is null");
throw new RuntimeException("itemsList is null"); throw new RuntimeException("itemsList is null");
} }
for (LinkedHashMap mapItems : mapSendResultItemsList) { for (LinkedHashMap mapItems : mapSendResultItemsList) {
Set<Map.Entry<String, Object>> entries = mapItems.entrySet(); Set<Map.Entry<String, Object>> entries = mapItems.entrySet();
Iterator<Map.Entry<String, Object>> iterator = entries.iterator(); Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
StringBuilder t = StringBuilder t =
new StringBuilder( new StringBuilder(String.format("`%s`%s", title, DingTalkConstants.ENTER_LINE));
String.format("`%s`%s", title, DingTalkConstants.MARKDOWN_ENTER));
while (iterator.hasNext()) { while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next(); Map.Entry<String, Object> entry = iterator.next();
t.append(DingTalkConstants.MARKDOWN_QUOTE); t.append(DingTalkConstants.MARKDOWN_QUOTE_MIDDLE_LINE);
t.append(entry.getKey()).append(":").append(entry.getValue()); t.append(entry.getKey()).append(":").append(entry.getValue());
t.append(DingTalkConstants.MARKDOWN_ENTER); t.append(DingTalkConstants.ENTER_LINE);
} }
builder.append(t); builder.append(t);
} }
byte[] byt = StringUtils.getBytesUtf8(builder.toString()); byte[] msgOfBytes = StringUtils.getBytesUtf8(builder.toString());
String txt = StringUtils.newStringUtf8(byt); String finalContent = StringUtils.newStringUtf8(msgOfBytes);
return txt; return finalContent;
} }
/**
* generate Signed Url of SHA256
*
* @return String
*/
private String generateSignedUrl() { private String generateSignedUrl() {
Long timestamp = System.currentTimeMillis(); Long timestamp = System.currentTimeMillis();
String stringToSign = timestamp + "\n" + secret; String stringToSign = timestamp + DingTalkConstants.ENTER_LINE + secret;
String sign = ""; String sign = "";
try { try {
Mac mac = Mac.getInstance("HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256")); mac.init(new SecretKeySpec(secret.getBytes(DingTalkConstants.CHARSET), "HmacSHA256"));
byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8")); byte[] signData = mac.doFinal(stringToSign.getBytes(DingTalkConstants.CHARSET));
sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8"); sign =
URLEncoder.encode(
new String(Base64.encodeBase64(signData)), DingTalkConstants.CHARSET);
} catch (Exception e) { } catch (Exception e) {
logger.error("generate sign error, message:{}", e); logger.error("generate sign error, message:{}", e);
} }
return url + "&timestamp=" + timestamp + "&sign=" + sign; return url + "&timestamp=" + timestamp + "&sign=" + sign;
} }
private void setMsgAt(Map<String, Object> items) { /**
* Set Msg AtUsers
*
* @param items
*/
private void buildAtUserList(Map<String, Object> items) {
Map<String, Object> at = new HashMap<>(); Map<String, Object> at = new HashMap<>();
String[] atMobileArray = String[] atMobileArray =
Asserts.isNotNullString(atMobiles) ? atMobiles.split(",") : new String[0]; Asserts.isNotNullString(atMobiles) ? atMobiles.split(",") : new String[0];
String[] atUserArray = String[] atUserArray =
Asserts.isNotNullString(atUserIds) ? atUserIds.split(",") : new String[0]; Asserts.isNotNullString(atUserIds) ? atUserIds.split(",") : new String[0];
boolean isAtAll = Objects.isNull(atAll) ? false : atAll; boolean isAtAll = Objects.isNull(atAll) ? false : atAll;
at.put("isAtAll", isAtAll); at.put(DingTalkConstants.AT_ALL, isAtAll);
if (atMobileArray.length > 0) { if (atMobileArray.length > 0) {
at.put("atMobiles", atMobileArray); at.put(DingTalkConstants.AT_MOBILES, atMobileArray);
} }
if (atMobileArray.length > 0) { if (atMobileArray.length > 0) {
at.put("atUserIds", atUserArray); at.put(DingTalkConstants.AT_USERIDS, atUserArray);
} }
items.put("at", at); items.put("at", at);
} }
/**
* Check Msg Result
*
* @param result
* @return
*/
private AlertResult checkMsgResult(String result) { private AlertResult checkMsgResult(String result) {
AlertResult alertResult = new AlertResult(); AlertResult alertResult = new AlertResult();
alertResult.setSuccess(false); alertResult.setSuccess(false);
......
...@@ -34,14 +34,7 @@ ...@@ -34,14 +34,7 @@
<groupId>org.dinky</groupId> <groupId>org.dinky</groupId>
<artifactId>dinky-alert-base</artifactId> <artifactId>dinky-alert-base</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>
<dependency> <dependency>
<groupId>com.sun.mail</groupId> <groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId> <artifactId>javax.mail</artifactId>
...@@ -50,10 +43,6 @@ ...@@ -50,10 +43,6 @@
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId> <artifactId>commons-email</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
......
...@@ -37,7 +37,7 @@ public class EmailAlert extends AbstractAlert { ...@@ -37,7 +37,7 @@ public class EmailAlert extends AbstractAlert {
@Override @Override
public AlertResult send(String title, String content) { public AlertResult send(String title, String content) {
MailSender mailSender = new MailSender(getConfig().getParam()); EmailSender emailSender = new EmailSender(getConfig().getParam());
return mailSender.send(title, content); return emailSender.send(title, content);
} }
} }
...@@ -19,65 +19,43 @@ ...@@ -19,65 +19,43 @@
package org.dinky.alert.email; package org.dinky.alert.email;
/** import org.dinky.alert.AlertBaseConstant;
* EmailConstants 邮件常量
*
* @author zhumingye
* @date: 2022/4/3
*/
public final class EmailConstants {
/** EmailConstants */
public class EmailConstants extends AlertBaseConstant {
public static final String TYPE = "Email"; public static final String TYPE = "Email";
/** Email base constant */
public static final String PLUGIN_DEFAULT_EMAIL_RECEIVERS = "receiver.name"; public static final String PLUGIN_DEFAULT_EMAIL_RECEIVERS = "receiver.name";
public static final String NAME_PLUGIN_DEFAULT_EMAIL_RECEIVERS = "receivers";
public static final String NAME_PLUGIN_DEFAULT_EMAIL_RECEIVERS = "receivers";
public static final String PLUGIN_DEFAULT_EMAIL_RECEIVERCCS = "receiverCcs"; public static final String PLUGIN_DEFAULT_EMAIL_RECEIVERCCS = "receiverCcs";
public static final String NAME_PLUGIN_DEFAULT_EMAIL_RECEIVERCCS = "receiverCcs"; public static final String NAME_PLUGIN_DEFAULT_EMAIL_RECEIVERCCS = "receiverCcs";
public static final String NAME_MAIL_PROTOCOL = "mail.protocol"; public static final String NAME_MAIL_PROTOCOL = "mail.protocol";
public static final String MAIL_SMTP_HOST = "mail.smtp.host"; public static final String MAIL_SMTP_HOST = "mail.smtp.host";
public static final String NAME_MAIL_SMTP_HOST = "serverHost"; public static final String NAME_MAIL_SMTP_HOST = "serverHost";
public static final String MAIL_SMTP_PORT = "mail.smtp.port"; public static final String MAIL_SMTP_PORT = "mail.smtp.port";
public static final String NAME_MAIL_SMTP_PORT = "serverPort"; public static final String NAME_MAIL_SMTP_PORT = "serverPort";
public static final String MAIL_SENDER = "sender.name"; public static final String MAIL_SENDER = "sender.name";
public static final String NAME_MAIL_SENDER = "sender"; public static final String NAME_MAIL_SENDER = "sender";
public static final String MAIL_SMTP_AUTH = "mail.smtp.auth"; public static final String MAIL_SMTP_AUTH = "mail.smtp.auth";
public static final String NAME_MAIL_SMTP_AUTH = "enableSmtpAuth"; public static final String NAME_MAIL_SMTP_AUTH = "enableSmtpAuth";
public static final String MAIL_USER = "mail.smtp.user"; public static final String MAIL_USER = "mail.smtp.user";
public static final String NAME_MAIL_USER = "User"; public static final String NAME_MAIL_USER = "User";
public static final String MAIL_PASSWD = "mail.smtp.passwd"; public static final String MAIL_PASSWD = "mail.smtp.passwd";
public static final String NAME_MAIL_PASSWD = "Password"; public static final String NAME_MAIL_PASSWD = "Password";
public static final String MAIL_SMTP_STARTTLS_ENABLE = "mail.smtp.starttls.enable"; public static final String MAIL_SMTP_STARTTLS_ENABLE = "mail.smtp.starttls.enable";
public static final String NAME_MAIL_SMTP_STARTTLS_ENABLE = "starttlsEnable"; public static final String NAME_MAIL_SMTP_STARTTLS_ENABLE = "starttlsEnable";
public static final String MAIL_SMTP_SSL_ENABLE = "mail.smtp.ssl.enable"; public static final String MAIL_SMTP_SSL_ENABLE = "mail.smtp.ssl.enable";
public static final String NAME_MAIL_SMTP_SSL_ENABLE = "sslEnable"; public static final String NAME_MAIL_SMTP_SSL_ENABLE = "sslEnable";
public static final String MAIL_SMTP_SSL_TRUST = "mail.smtp.ssl.trust"; public static final String MAIL_SMTP_SSL_TRUST = "mail.smtp.ssl.trust";
public static final String NAME_MAIL_SMTP_SSL_TRUST = "smtpSslTrust"; public static final String NAME_MAIL_SMTP_SSL_TRUST = "smtpSslTrust";
public static final String XLS_FILE_PATH = "xls.file.path"; public static final String XLS_FILE_PATH = "xls.file.path";
public static final String NAME_SHOW_TYPE = "msgtype";
public static final String MAIL_TRANSPORT_PROTOCOL = "mail.transport.protocol"; public static final String MAIL_TRANSPORT_PROTOCOL = "mail.transport.protocol";
public static final String TEXT_HTML_CHARSET_UTF_8 = "text/html;charset=utf-8"; public static final String TEXT_HTML_CHARSET_UTF_8 = "text/html;charset=utf-8";
public static final int NUMBER_1000 = 1000; public static final int NUMBER_1000 = 1000;
public static final String TR = "<tr>"; public static final String TR = "<tr>";
public static final String TD = "<td>"; public static final String TD = "<td>";
public static final String TD_END = "</td>"; public static final String TD_END = "</td>";
public static final String TR_END = "</tr>"; public static final String TR_END = "</tr>";
...@@ -88,12 +66,6 @@ public final class EmailConstants { ...@@ -88,12 +66,6 @@ public final class EmailConstants {
public static final String TH_END = "</th>"; public static final String TH_END = "</th>";
public static final String TAB = "\t";
public static final String LINE = "\n";
public static final String LEFT = ">";
public static final String HTML_HEADER_PREFIX = public static final String HTML_HEADER_PREFIX =
"<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>" "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>"
+ "<html>" + "<html>"
...@@ -111,14 +83,9 @@ public final class EmailConstants { ...@@ -111,14 +83,9 @@ public final class EmailConstants {
public static final String TABLE_BODY_HTML_TAIL = "</table></body></html>"; public static final String TABLE_BODY_HTML_TAIL = "</table></body></html>";
public static final String UTF_8 = "UTF-8";
public static final String EXCEL_SUFFIX_XLSX = ".xlsx"; public static final String EXCEL_SUFFIX_XLSX = ".xlsx";
public static final String SINGLE_SLASH = "/"; public static final String SINGLE_SLASH = "/";
private EmailConstants() { public static final String XLS_FILE_DEFAULT_PATH = "/tmp/xls";
throw new UnsupportedOperationException(
"This is a utility class and cannot be instantiated");
}
} }
...@@ -26,6 +26,7 @@ import org.dinky.alert.AlertResult; ...@@ -26,6 +26,7 @@ import org.dinky.alert.AlertResult;
import org.dinky.alert.ShowType; import org.dinky.alert.ShowType;
import org.dinky.alert.email.template.AlertTemplate; import org.dinky.alert.email.template.AlertTemplate;
import org.dinky.alert.email.template.DefaultHTMLTemplate; import org.dinky.alert.email.template.DefaultHTMLTemplate;
import org.dinky.utils.ExcelUtils;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
...@@ -60,14 +61,14 @@ import org.slf4j.LoggerFactory; ...@@ -60,14 +61,14 @@ import org.slf4j.LoggerFactory;
import com.sun.mail.smtp.SMTPProvider; import com.sun.mail.smtp.SMTPProvider;
/** /**
* MailSender 邮件发送器 * EmailSender 邮件发送器
* *
* @author zhumingye * @author zhumingye
* @date: 2022/4/3 * @date: 2022/4/3
*/ */
public final class MailSender { public final class EmailSender {
private static final Logger logger = LoggerFactory.getLogger(MailSender.class); private static final Logger logger = LoggerFactory.getLogger(EmailSender.class);
private final List<String> receivers; private final List<String> receivers;
private final List<String> receiverCcs; private final List<String> receiverCcs;
...@@ -86,7 +87,7 @@ public final class MailSender { ...@@ -86,7 +87,7 @@ public final class MailSender {
private final String mustNotNull = " must not be null"; private final String mustNotNull = " must not be null";
private String xlsFilePath; private String xlsFilePath;
public MailSender(Map<String, String> config) { public EmailSender(Map<String, String> config) {
String receiversConfig = config.get(EmailConstants.NAME_PLUGIN_DEFAULT_EMAIL_RECEIVERS); String receiversConfig = config.get(EmailConstants.NAME_PLUGIN_DEFAULT_EMAIL_RECEIVERS);
if (receiversConfig == null || "".equals(receiversConfig)) { if (receiversConfig == null || "".equals(receiversConfig)) {
throw new AlertException( throw new AlertException(
...@@ -125,12 +126,12 @@ public final class MailSender { ...@@ -125,12 +126,12 @@ public final class MailSender {
sslTrust = config.get(EmailConstants.NAME_MAIL_SMTP_SSL_TRUST); sslTrust = config.get(EmailConstants.NAME_MAIL_SMTP_SSL_TRUST);
showType = config.get(EmailConstants.NAME_SHOW_TYPE); showType = config.get(EmailConstants.MSG_TYPE);
requireNonNull(showType, EmailConstants.NAME_SHOW_TYPE + mustNotNull); requireNonNull(showType, EmailConstants.MSG_TYPE + mustNotNull);
xlsFilePath = config.get(EmailConstants.XLS_FILE_PATH); xlsFilePath = config.get(EmailConstants.XLS_FILE_PATH);
if (StringUtils.isBlank(xlsFilePath)) { if (StringUtils.isBlank(xlsFilePath)) {
xlsFilePath = "/tmp/xls"; xlsFilePath = EmailConstants.XLS_FILE_DEFAULT_PATH;
} }
alertTemplate = new DefaultHTMLTemplate(); alertTemplate = new DefaultHTMLTemplate();
...@@ -176,7 +177,7 @@ public final class MailSender { ...@@ -176,7 +177,7 @@ public final class MailSender {
Session session = getSession(); Session session = getSession();
email.setMailSession(session); email.setMailSession(session);
email.setFrom(mailUser, mailSenderNickName); email.setFrom(mailUser, mailSenderNickName);
email.setCharset(EmailConstants.UTF_8); email.setCharset(EmailConstants.CHARSET);
if (CollectionUtils.isNotEmpty(receivers)) { if (CollectionUtils.isNotEmpty(receivers)) {
// receivers mail // receivers mail
for (String receiver : receivers) { for (String receiver : receivers) {
...@@ -365,7 +366,7 @@ public final class MailSender { ...@@ -365,7 +366,7 @@ public final class MailSender {
part2.attachFile(file); part2.attachFile(file);
part2.setFileName( part2.setFileName(
MimeUtility.encodeText( MimeUtility.encodeText(
title + EmailConstants.EXCEL_SUFFIX_XLSX, EmailConstants.UTF_8, "B")); title + EmailConstants.EXCEL_SUFFIX_XLSX, EmailConstants.CHARSET, "B"));
// add components to collection // add components to collection
partList.addBodyPart(part1); partList.addBodyPart(part1);
partList.addBodyPart(part2); partList.addBodyPart(part2);
......
...@@ -21,11 +21,7 @@ package org.dinky.alert.email.template; ...@@ -21,11 +21,7 @@ package org.dinky.alert.email.template;
import org.dinky.alert.ShowType; import org.dinky.alert.ShowType;
/** /** AlertTemplate */
* @Author: zhumingye
*
* @date: 2022/4/3 @Description: 邮件告警模板接口
*/
public interface AlertTemplate { public interface AlertTemplate {
String getMessageFromTemplate(String title, String content, ShowType showType, boolean showAll); String getMessageFromTemplate(String title, String content, ShowType showType, boolean showAll);
......
...@@ -36,11 +36,7 @@ import java.util.Set; ...@@ -36,11 +36,7 @@ import java.util.Set;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /** DefaultHTMLTemplate */
* @Author: zhumingye
*
* @date: 2022/4/3 @Description: 邮件告警Html模板
*/
public class DefaultHTMLTemplate implements AlertTemplate { public class DefaultHTMLTemplate implements AlertTemplate {
public static final Logger logger = LoggerFactory.getLogger(DefaultHTMLTemplate.class); public static final Logger logger = LoggerFactory.getLogger(DefaultHTMLTemplate.class);
......
...@@ -44,7 +44,7 @@ import org.slf4j.LoggerFactory; ...@@ -44,7 +44,7 @@ import org.slf4j.LoggerFactory;
public class EmailSenderTest { public class EmailSenderTest {
private static final Logger logger = LoggerFactory.getLogger(EmailSenderTest.class); private static final Logger logger = LoggerFactory.getLogger(EmailSenderTest.class);
static MailSender mailSender; static EmailSender emailSender;
private static Map<String, String> emailConfig = new HashMap<>(); private static Map<String, String> emailConfig = new HashMap<>();
private static AlertTemplate alertTemplate; private static AlertTemplate alertTemplate;
...@@ -83,42 +83,42 @@ public class EmailSenderTest { ...@@ -83,42 +83,42 @@ public class EmailSenderTest {
emailConfig.put( emailConfig.put(
EmailConstants.NAME_PLUGIN_DEFAULT_EMAIL_RECEIVERS, "user1@qq.com,user2@163.com"); EmailConstants.NAME_PLUGIN_DEFAULT_EMAIL_RECEIVERS, "user1@qq.com,user2@163.com");
emailConfig.put(EmailConstants.NAME_PLUGIN_DEFAULT_EMAIL_RECEIVERCCS, "user3@qq.com"); emailConfig.put(EmailConstants.NAME_PLUGIN_DEFAULT_EMAIL_RECEIVERCCS, "user3@qq.com");
emailConfig.put(EmailConstants.NAME_SHOW_TYPE, ShowType.TEXT.getValue()); emailConfig.put(EmailConstants.MSG_TYPE, ShowType.TEXT.getValue());
alertTemplate = new DefaultHTMLTemplate(); alertTemplate = new DefaultHTMLTemplate();
mailSender = new MailSender(emailConfig); emailSender = new EmailSender(emailConfig);
} }
@Ignore @Ignore
@Test @Test
public void testTextSendMails() { public void testTextSendMails() {
AlertResult alertResult = mailSender.send(title, alertMsg.toString()); AlertResult alertResult = emailSender.send(title, alertMsg.toString());
Assert.assertEquals(true, alertResult.getSuccess()); // 格式需要调整 Assert.assertEquals(true, alertResult.getSuccess()); // 格式需要调整
} }
@Ignore @Ignore
@Test @Test
public void testSendTableMail() { public void testSendTableMail() {
emailConfig.put(EmailConstants.NAME_SHOW_TYPE, ShowType.TABLE.getValue()); emailConfig.put(EmailConstants.MSG_TYPE, ShowType.TABLE.getValue());
mailSender = new MailSender(emailConfig); emailSender = new EmailSender(emailConfig);
AlertResult alertResult = mailSender.send(title, alertMsg.toString()); AlertResult alertResult = emailSender.send(title, alertMsg.toString());
Assert.assertEquals(true, alertResult.getSuccess()); Assert.assertEquals(true, alertResult.getSuccess());
} }
@Ignore @Ignore
@Test @Test
public void testAttachmentFile() { public void testAttachmentFile() {
emailConfig.put(EmailConstants.NAME_SHOW_TYPE, ShowType.ATTACHMENT.getValue()); emailConfig.put(EmailConstants.MSG_TYPE, ShowType.ATTACHMENT.getValue());
mailSender = new MailSender(emailConfig); emailSender = new EmailSender(emailConfig);
AlertResult alertResult = mailSender.send(title, alertMsg.toString()); AlertResult alertResult = emailSender.send(title, alertMsg.toString());
Assert.assertEquals(true, alertResult.getSuccess()); Assert.assertEquals(true, alertResult.getSuccess());
} }
@Ignore @Ignore
@Test @Test
public void testTableAttachmentFile() { public void testTableAttachmentFile() {
emailConfig.put(EmailConstants.NAME_SHOW_TYPE, ShowType.TABLE_ATTACHMENT.getValue()); emailConfig.put(EmailConstants.MSG_TYPE, ShowType.TABLE_ATTACHMENT.getValue());
mailSender = new MailSender(emailConfig); emailSender = new EmailSender(emailConfig);
AlertResult alertResult = mailSender.send(title, alertMsg.toString()); AlertResult alertResult = emailSender.send(title, alertMsg.toString());
Assert.assertEquals(true, alertResult.getSuccess()); Assert.assertEquals(true, alertResult.getSuccess());
} }
......
...@@ -34,10 +34,6 @@ ...@@ -34,10 +34,6 @@
<artifactId>dinky-alert-base</artifactId> <artifactId>dinky-alert-base</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>com.google.guava</groupId>
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
...@@ -50,15 +46,10 @@ ...@@ -50,15 +46,10 @@
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId> <artifactId>jackson-annotations</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>
...@@ -19,35 +19,19 @@ ...@@ -19,35 +19,19 @@
package org.dinky.alert.feishu; package org.dinky.alert.feishu;
/** import org.dinky.alert.AlertBaseConstant;
* @Author: zhumingye
* /** FeiShuConstants */
* @date: 2022/4/2 @Description: 参数常量 public class FeiShuConstants extends AlertBaseConstant {
*/ public static final String TYPE = "FeiShu";
public final class FeiShuConstants {
static final String TYPE = "FeiShu"; /** FeiShu alert baseconstant */
static final String MARKDOWN_QUOTE = "> "; public static final String FEI_SHU_TEXT_TEMPLATE =
static final String MARKDOWN_ENTER = "/n";
static final String WEB_HOOK = "webhook";
static final String KEY_WORD = "keyword";
static final String SECRET = "secret";
static final String FEI_SHU_PROXY_ENABLE = "isEnableProxy";
static final String FEI_SHU_PROXY = "proxy";
static final String FEI_SHU_PORT = "port";
static final String FEI_SHU_USER = "user";
static final String FEI_SHU_PASSWORD = "password";
static final String MSG_TYPE = "msgtype";
static final String AT_ALL = "isAtAll";
static final String AT_USERS = "users";
static final String FEI_SHU_TEXT_TEMPLATE =
"{\"msg_type\":\"{msg_type}\",\"content\":{\"{msg_type}\":\"{msg} {users} \" }}"; "{\"msg_type\":\"{msg_type}\",\"content\":{\"{msg_type}\":\"{msg} {users} \" }}";
static final String FEI_SHU_POST_TEMPLATE =
public static final String FEI_SHU_POST_TEMPLATE =
"{\"msg_type\":\"{msg_type}\",\"content\":{\"{msg_type}\":{\"zh_cn\":{\"title\":\"{keyword}\"," "{\"msg_type\":\"{msg_type}\",\"content\":{\"{msg_type}\":{\"zh_cn\":{\"title\":\"{keyword}\","
+ "\"content\":[[{\"tag\":\"text\",\"un_escape\": true,\"text\":\"{msg}\"},{users}]]}}}}"; + "\"content\":[[{\"tag\":\"text\",\"un_escape\": true,\"text\":\"{msg}\"},{users}]]}}}}";
public static final String SIGN_TMESTAMP = "timestamp";
private FeiShuConstants() { public static final String SIGN = "sign";
throw new UnsupportedOperationException(
"This is a utility class and cannot be instantiated");
}
} }
...@@ -19,19 +19,32 @@ ...@@ -19,19 +19,32 @@
package org.dinky.alert.feishu; package org.dinky.alert.feishu;
import static java.util.Objects.requireNonNull;
import org.dinky.alert.AlertResult; import org.dinky.alert.AlertResult;
import org.dinky.alert.ShowType; import org.dinky.alert.ShowType;
import org.dinky.assertion.Asserts;
import org.dinky.utils.JSONUtil; import org.dinky.utils.JSONUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils; import org.apache.commons.codec.binary.StringUtils;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
...@@ -39,10 +52,14 @@ import java.util.Map; ...@@ -39,10 +52,14 @@ import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.node.ObjectNode;
/** /**
* @Author: zhumingye * @Author: zhumingye
...@@ -52,15 +69,10 @@ import com.fasterxml.jackson.annotation.JsonProperty; ...@@ -52,15 +69,10 @@ import com.fasterxml.jackson.annotation.JsonProperty;
public final class FeiShuSender { public final class FeiShuSender {
private static final Logger logger = LoggerFactory.getLogger(FeiShuSender.class); private static final Logger logger = LoggerFactory.getLogger(FeiShuSender.class);
static final String FEI_SHU_PROXY_ENABLE_REGX = "{isEnableProxy}";
static final String FEI_SHU_PROXY_REGX = "{proxy}";
static final String FEI_SHU_PORT_REGX = "{port}";
static final String FEI_SHU_USER_REGX = "{users}"; static final String FEI_SHU_USER_REGX = "{users}";
static final String FEI_SHU_PASSWORD_REGX = "{password}";
static final String MSG_RESULT_REGX = "{msg}"; static final String MSG_RESULT_REGX = "{msg}";
static final String MSG_TYPE_REGX = "{msg_type}"; static final String MSG_TYPE_REGX = "{msg_type}";
static final String FEI_SHU_MSG_TYPE_REGX = "{keyword}"; static final String FEI_SHU_KEYWORD_REGX = "{keyword}";
private final String url; private final String url;
private final String msgType; private final String msgType;
...@@ -76,18 +88,21 @@ public final class FeiShuSender { ...@@ -76,18 +88,21 @@ public final class FeiShuSender {
FeiShuSender(Map<String, String> config) { FeiShuSender(Map<String, String> config) {
url = config.get(FeiShuConstants.WEB_HOOK); url = config.get(FeiShuConstants.WEB_HOOK);
msgType = config.get(FeiShuConstants.MSG_TYPE); msgType = config.get(FeiShuConstants.MSG_TYPE);
requireNonNull(msgType, FeiShuConstants.MSG_TYPE + " must not null");
keyword = keyword =
config.get(FeiShuConstants.KEY_WORD) != null config.get(FeiShuConstants.KEYWORD) != null
? config.get(FeiShuConstants.KEY_WORD).replace("\r\n", "") ? config.get(FeiShuConstants.KEYWORD).replace("\r\n", "")
: ""; : "";
enableProxy = Boolean.valueOf(config.get(FeiShuConstants.FEI_SHU_PROXY_ENABLE)); enableProxy = Boolean.valueOf(config.get(FeiShuConstants.PROXY_ENABLE));
secret = config.get(FeiShuConstants.SECRET); secret = config.get(FeiShuConstants.SECRET);
if (Boolean.TRUE.equals(enableProxy)) { if (Boolean.TRUE.equals(enableProxy)) {
proxy = config.get(FeiShuConstants.FEI_SHU_PROXY); proxy = config.get(FeiShuConstants.PROXY);
port = Integer.parseInt(config.get(FeiShuConstants.FEI_SHU_PORT)); port = Integer.parseInt(config.get(FeiShuConstants.PORT));
user = config.get(FeiShuConstants.FEI_SHU_USER); user = config.get(FeiShuConstants.USER);
password = config.get(FeiShuConstants.FEI_SHU_PASSWORD); password = config.get(FeiShuConstants.PASSWORD);
} }
atAll = Boolean.valueOf(config.get(FeiShuConstants.AT_ALL)); atAll = Boolean.valueOf(config.get(FeiShuConstants.AT_ALL));
if (Boolean.FALSE.equals(atAll)) { if (Boolean.FALSE.equals(atAll)) {
...@@ -95,59 +110,210 @@ public final class FeiShuSender { ...@@ -95,59 +110,210 @@ public final class FeiShuSender {
} }
} }
private String toJsonSendMsg(String title, String content) { /**
* main send msg
*
* @param title
* @param content
* @return AlertResult
*/
public AlertResult send(String title, String content) {
AlertResult alertResult;
try {
String sendMsgOfResult = buildSendMsgAndSendOfResult(title, content);
return checkSendMsgResult(sendMsgOfResult);
} catch (Exception e) {
logger.error("send fei shu alert msg exception : {}", e.getMessage());
alertResult = new AlertResult();
alertResult.setSuccess(false);
alertResult.setMessage("send fei shu alert fail.");
}
return alertResult;
}
/**
* send msg
*
* @param title
* @param content
* @return
* @throws IOException
*/
private String buildSendMsgAndSendOfResult(String title, String content) throws IOException {
String msg = replaceParamsToBuildSendMsgTemplate(title, content);
HttpPost httpPost = buildHttpPost(url, msg);
CloseableHttpClient httpClient;
if (Boolean.TRUE.equals(enableProxy)) {
httpClient = getCloseableHttpClientOfProxy(httpPost);
} else {
httpClient = HttpClients.createDefault();
}
try {
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
logger.error("send feishu message error, return http status code: {} ", statusCode);
}
String resp;
try {
HttpEntity entity = response.getEntity();
resp = EntityUtils.toString(entity, FeiShuConstants.CHARSET);
EntityUtils.consume(entity);
} finally {
response.close();
}
logger.info("Fei Shu send title :{} ,content :{}, resp: {}", title, content, resp);
return resp;
} finally {
httpClient.close();
}
}
/**
* parse json to template
*
* @param title
* @param content
* @return
*/
private String replaceParamsToBuildSendMsgTemplate(String title, String content) {
Integer currentTimeMillis = Math.toIntExact(System.currentTimeMillis() / 1000);
String jsonResult = ""; String jsonResult = "";
byte[] byt = StringUtils.getBytesUtf8(formatContent(title, content)); byte[] byt = StringUtils.getBytesUtf8(buildFinalResultMsgBody(title, content));
String contentResult = StringUtils.newStringUtf8(byt); String contentResult = StringUtils.newStringUtf8(byt);
String userIdsToText = String userIdsToText = buildAtUserList(Asserts.isNullString(atUserIds) ? "all" : atUserIds);
mkUserIds(
org.apache.commons.lang3.StringUtils.isBlank(atUserIds)
? "all"
: atUserIds);
if (StringUtils.equals(ShowType.TEXT.getValue(), msgType)) { if (StringUtils.equals(ShowType.TEXT.getValue(), msgType)) {
jsonResult = jsonResult =
FeiShuConstants.FEI_SHU_TEXT_TEMPLATE FeiShuConstants.FEI_SHU_TEXT_TEMPLATE
.replace(MSG_TYPE_REGX, msgType) .replace(MSG_TYPE_REGX, msgType)
.replace(MSG_RESULT_REGX, contentResult) .replace(
MSG_RESULT_REGX,
keyword
+ FeiShuConstants.MARKDOWN_ENTER_BACK_SLASH
+ contentResult)
.replace(FEI_SHU_USER_REGX, userIdsToText) .replace(FEI_SHU_USER_REGX, userIdsToText)
.replaceAll("/n", "\\\\n"); .replaceAll("/n", "\\\\n");
} else { } else {
jsonResult = jsonResult =
FeiShuConstants.FEI_SHU_POST_TEMPLATE FeiShuConstants.FEI_SHU_POST_TEMPLATE
.replace(MSG_TYPE_REGX, msgType) .replace(MSG_TYPE_REGX, msgType)
.replace(FEI_SHU_MSG_TYPE_REGX, keyword) .replace(FEI_SHU_KEYWORD_REGX, keyword)
.replace(MSG_RESULT_REGX, contentResult) .replace(MSG_RESULT_REGX, contentResult)
.replace(FEI_SHU_USER_REGX, userIdsToText) .replace(FEI_SHU_USER_REGX, userIdsToText)
.replaceAll("/n", "\\\\n"); .replaceAll("/n", "\\\\n");
} }
if (Asserts.isNotNullString(secret)) {
ObjectNode jsonNodes = JSONUtil.parseObject(jsonResult);
jsonNodes.put(FeiShuConstants.SIGN_TMESTAMP, currentTimeMillis);
jsonNodes.put(FeiShuConstants.SIGN, getSign(secret, currentTimeMillis));
return jsonNodes.toString();
} else {
return jsonResult; return jsonResult;
} }
}
/**
* generate sign
*
* @param secretKey
* @param timestamp
* @return
*/
private String getSign(String secretKey, Integer timestamp) {
String stringToSign = timestamp + FeiShuConstants.ENTER_LINE + secretKey;
String sign = "";
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(
new SecretKeySpec(
stringToSign.getBytes(FeiShuConstants.CHARSET), "HmacSHA256"));
byte[] signData = mac.doFinal(new byte[] {});
sign = new String(Base64.encodeBase64(signData));
} catch (Exception e) {
logger.error("generate sign error, message:{}", e.getMessage());
}
return sign;
}
private String mkUserIds(String users) { /**
String userIdsToText = ""; * Generate AtUsers
*
* @param users
* @return
*/
private String buildAtUserList(String users) {
String[] userList = users.split(","); String[] userList = users.split(",");
StringBuilder atUserList = new StringBuilder();
if (msgType.equals(ShowType.TEXT.getValue())) { if (msgType.equals(ShowType.TEXT.getValue())) {
StringBuilder sb = new StringBuilder();
for (String user : userList) { for (String user : userList) {
sb.append("<at user_id=\\\"").append(user).append("\\\"></at>"); atUserList.append("<at user_id=\\\"").append(user).append("\\\"></at>");
} }
userIdsToText = sb.toString();
} else { } else {
StringBuilder sb = new StringBuilder();
for (String user : userList) { for (String user : userList) {
sb.append("{\"tag\":\"at\",\"user_id\":\"").append(user).append("\"},"); atUserList.append("{\"tag\":\"at\",\"user_id\":\"").append(user).append("\"},");
} }
sb.deleteCharAt(sb.length() - 1); atUserList.deleteCharAt(atUserList.length() - 1);
userIdsToText = sb.toString();
} }
return userIdsToText; return atUserList.toString();
} }
public static AlertResult checkSendFeiShuSendMsgResult(String result) { /**
* Generate send msg
*
* @param title
* @param content
* @return
*/
public static String buildFinalResultMsgBody(String title, String content) {
List<LinkedHashMap> mapSendResultItemsList = JSONUtil.toList(content, LinkedHashMap.class);
if (null == mapSendResultItemsList || mapSendResultItemsList.isEmpty()) {
logger.error("itemsList is null");
throw new RuntimeException("itemsList is null");
}
StringBuilder contents = new StringBuilder(100);
contents.append(String.format("`%s` %s", title, FeiShuConstants.MARKDOWN_ENTER_BACK_SLASH));
for (LinkedHashMap mapItems : mapSendResultItemsList) {
Set<Entry<String, Object>> entries = mapItems.entrySet();
Iterator<Entry<String, Object>> iterator = entries.iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
String key = entry.getKey();
String value = entry.getValue().toString();
contents.append(key + ":" + value)
.append(FeiShuConstants.MARKDOWN_ENTER_BACK_SLASH);
}
return contents.toString();
}
return null;
}
private static HttpPost buildHttpPost(String httpUrl, String msg) {
HttpPost httpPost = new HttpPost(httpUrl);
StringEntity stringEntity = new StringEntity(msg, StandardCharsets.UTF_8);
httpPost.setEntity(stringEntity);
httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
return httpPost;
}
/**
* checkSendFeiShuSendMsgResult
*
* @param result
* @return
*/
public static AlertResult checkSendMsgResult(String result) {
AlertResult alertResult = new AlertResult(); AlertResult alertResult = new AlertResult();
alertResult.setSuccess(false); alertResult.setSuccess(false);
if (org.apache.commons.lang3.StringUtils.isBlank(result)) { if (Asserts.isNull(result)) {
alertResult.setMessage("send fei shu msg error"); alertResult.setMessage("send fei shu msg error");
logger.info("send fei shu msg error,fei shu server resp is null"); logger.info("send fei shu msg error,fei shu server resp is null");
return alertResult; return alertResult;
...@@ -175,69 +341,22 @@ public final class FeiShuSender { ...@@ -175,69 +341,22 @@ public final class FeiShuSender {
return alertResult; return alertResult;
} }
public static String formatContent(String title, String content) { /**
List<LinkedHashMap> mapSendResultItemsList = JSONUtil.toList(content, LinkedHashMap.class); * get CloseableHttpClient Of Proxy
if (null == mapSendResultItemsList || mapSendResultItemsList.isEmpty()) { *
logger.error("itemsList is null"); * @param httpPost
throw new RuntimeException("itemsList is null"); * @return
} */
StringBuilder contents = new StringBuilder(100); private CloseableHttpClient getCloseableHttpClientOfProxy(HttpPost httpPost) {
contents.append(String.format("`%s` %s", title, FeiShuConstants.MARKDOWN_ENTER));
for (LinkedHashMap mapItems : mapSendResultItemsList) {
Set<Entry<String, Object>> entries = mapItems.entrySet();
Iterator<Entry<String, Object>> iterator = entries.iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
String key = entry.getKey();
String value = entry.getValue().toString();
contents.append(FeiShuConstants.MARKDOWN_QUOTE);
contents.append(key + ":" + value).append(FeiShuConstants.MARKDOWN_ENTER);
}
return contents.toString();
}
return null;
}
public AlertResult send(String title, String content) {
AlertResult alertResult;
try {
String resp = sendMsg(title, content);
return checkSendFeiShuSendMsgResult(resp);
} catch (Exception e) {
logger.info("send fei shu alert msg exception : {}", e.getMessage());
alertResult = new AlertResult();
alertResult.setSuccess(false);
alertResult.setMessage("send fei shu alert fail.");
}
return alertResult;
}
private String sendMsg(String title, String content) throws IOException {
String msgToJson = toJsonSendMsg(title, content);
HttpPost httpPost = HttpRequestUtil.constructHttpPost(url, msgToJson);
CloseableHttpClient httpClient; CloseableHttpClient httpClient;
httpClient = HttpRequestUtil.getHttpClient(enableProxy, proxy, port, user, password); HttpHost httpProxy = new HttpHost(proxy, port);
try { CredentialsProvider provider = new BasicCredentialsProvider();
CloseableHttpResponse response = httpClient.execute(httpPost); provider.setCredentials(
new AuthScope(httpProxy), new UsernamePasswordCredentials(user, password));
int statusCode = response.getStatusLine().getStatusCode(); httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
if (statusCode != HttpStatus.SC_OK) { RequestConfig rcf = RequestConfig.custom().setProxy(httpProxy).build();
logger.error("send feishu message error, return http status code: {} ", statusCode); httpPost.setConfig(rcf);
} return httpClient;
String resp;
try {
HttpEntity entity = response.getEntity();
resp = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);
} finally {
response.close();
}
logger.info("Fei Shu send title :{} ,content :{}, resp: {}", title, content, resp);
return resp;
} finally {
httpClient.close();
}
} }
static final class FeiShuSendMsgResponse { static final class FeiShuSendMsgResponse {
...@@ -280,6 +399,7 @@ public final class FeiShuSender { ...@@ -280,6 +399,7 @@ public final class FeiShuSender {
this.statusMessage = statusMessage; this.statusMessage = statusMessage;
} }
@Override
public boolean equals(final Object o) { public boolean equals(final Object o) {
if (o == this) { if (o == this) {
return true; return true;
...@@ -310,6 +430,7 @@ public final class FeiShuSender { ...@@ -310,6 +430,7 @@ public final class FeiShuSender {
return true; return true;
} }
@Override
public int hashCode() { public int hashCode() {
final int PRIME = 59; final int PRIME = 59;
int result = 1; int result = 1;
...@@ -322,6 +443,7 @@ public final class FeiShuSender { ...@@ -322,6 +443,7 @@ public final class FeiShuSender {
return result; return result;
} }
@Override
public String toString() { public String toString() {
return "FeiShuSender.FeiShuSendMsgResponse(extra=" return "FeiShuSender.FeiShuSendMsgResponse(extra="
+ this.getExtra() + this.getExtra()
......
...@@ -62,7 +62,7 @@ public class FeiShuSenderTest { ...@@ -62,7 +62,7 @@ public class FeiShuSenderTest {
feiShuConfig.put( feiShuConfig.put(
FeiShuConstants.WEB_HOOK, FeiShuConstants.WEB_HOOK,
"https://open.feishu.cn/open-apis/bot/v2/hook/aea3cd7f-75b4-45cd-abea-2c0dc808f2a9"); "https://open.feishu.cn/open-apis/bot/v2/hook/aea3cd7f-75b4-45cd-abea-2c0dc808f2a9");
feiShuConfig.put(FeiShuConstants.KEY_WORD, "Dinky 飞书WebHook 告警测试"); feiShuConfig.put(FeiShuConstants.KEYWORD, "Dinky 飞书WebHook 告警测试");
feiShuConfig.put(FeiShuConstants.MSG_TYPE, "text"); feiShuConfig.put(FeiShuConstants.MSG_TYPE, "text");
feiShuConfig.put(FeiShuConstants.AT_ALL, "true"); feiShuConfig.put(FeiShuConstants.AT_ALL, "true");
feiShuConfig.put(FeiShuConstants.AT_USERS, "zhumingye"); feiShuConfig.put(FeiShuConstants.AT_USERS, "zhumingye");
......
...@@ -19,54 +19,26 @@ ...@@ -19,54 +19,26 @@
package org.dinky.alert.wechat; package org.dinky.alert.wechat;
/** import org.dinky.alert.AlertBaseConstant;
* WeChatConstants
*
* @author wenmo
* @since 2022/2/23 21:10
*/
public class WeChatConstants {
static final String TYPE = "WeChat";
static final String MARKDOWN_QUOTE = ">";
static final String MARKDOWN_ENTER = "\n";
static final String CHARSET = "UTF-8"; /** WeChatConstants */
public class WeChatConstants extends AlertBaseConstant {
static final String PUSH_URL = public static final String TYPE = "WeChat";
/** WeChat alert baseconstant */
public static final String WECHAT_PUSH_URL =
"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}"; "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}";
static final String APP_CHAT_PUSH_URL = public static final String WECHAT_APP_PUSH_URL =
"https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token={token}"; "https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token={token}";
public static final String WECHAT_TOKEN_URL =
static final String TOKEN_URL =
"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpId}&corpsecret={secret}"; "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpId}&corpsecret={secret}";
public static final String WECHAT_WEBHOOK_TEMPLATE =
static final String WEBHOOK = "webhook";
static final String WEBHOOK_TEMPLATE =
"{\"msgtype\":\"{msgtype}\",\"{msgtype}\":{\"content\":\"{msg} \"}}"; "{\"msgtype\":\"{msgtype}\",\"{msgtype}\":{\"content\":\"{msg} \"}}";
public static final String CORP_ID = "corpId";
static final String KEYWORD = "keyword"; public static final String TEAM_SEND_MSG = "teamSendMsg";
public static final String WECHAT_APP_TEMPLATE =
static final String AT_ALL = "isAtAll";
static final String CORP_ID = "corpId";
static final String SECRET = "secret";
static final String TEAM_SEND_MSG = "teamSendMsg";
static final String USER_SEND_MSG =
"{\"touser\":\"{toUser}\",\"agentid\":{agentId},\"msgtype\":\"{msgtype}\",\"{msgtype}\":{\"content\":\"{msg}\"}}"; "{\"touser\":\"{toUser}\",\"agentid\":{agentId},\"msgtype\":\"{msgtype}\",\"{msgtype}\":{\"content\":\"{msg}\"}}";
public static final String AGENT_ID = "agentId";
static final String AGENT_ID = "agentId"; public static final String SEND_TYPE = "sendType";
public static final String ACCESS_TOKEN = "access_token";
static final String USERS = "users";
static final String SEND_TYPE = "sendType";
static final String SHOW_TYPE = "msgtype";
} }
...@@ -72,7 +72,7 @@ public class WeChatSender { ...@@ -72,7 +72,7 @@ public class WeChatSender {
private final String weChatTokenUrlReplace; private final String weChatTokenUrlReplace;
private final String weChatToken; private final String weChatToken;
private final String sendType; private final String sendType;
private static String showType; private static String msgType;
private final String webhookUrl; private final String webhookUrl;
private final String keyWord; private final String keyWord;
private final Boolean atAll; private final Boolean atAll;
...@@ -86,10 +86,10 @@ public class WeChatSender { ...@@ -86,10 +86,10 @@ public class WeChatSender {
atAll = Boolean.valueOf(config.get(WeChatConstants.AT_ALL)); atAll = Boolean.valueOf(config.get(WeChatConstants.AT_ALL));
weChatUsers = weChatUsers =
sendType.equals(WeChatType.CHAT.getValue()) sendType.equals(WeChatType.CHAT.getValue())
? (atAll && config.get(WeChatConstants.USERS) == null ? (atAll && config.get(WeChatConstants.AT_USERS) == null
? "" ? ""
: config.get(WeChatConstants.USERS)) : config.get(WeChatConstants.AT_USERS))
: config.get(WeChatConstants.USERS); : config.get(WeChatConstants.AT_USERS);
String weChatCorpId = String weChatCorpId =
sendType.equals(WeChatType.CHAT.getValue()) sendType.equals(WeChatType.CHAT.getValue())
? "" ? ""
...@@ -99,14 +99,16 @@ public class WeChatSender { ...@@ -99,14 +99,16 @@ public class WeChatSender {
? "" ? ""
: config.get(WeChatConstants.SECRET); : config.get(WeChatConstants.SECRET);
String weChatTokenUrl = String weChatTokenUrl =
sendType.equals(WeChatType.CHAT.getValue()) ? "" : WeChatConstants.TOKEN_URL; sendType.equals(WeChatType.CHAT.getValue()) ? "" : WeChatConstants.WECHAT_TOKEN_URL;
weChatUserSendMsg = WeChatConstants.USER_SEND_MSG; weChatUserSendMsg = WeChatConstants.WECHAT_APP_TEMPLATE;
showType = config.get(WeChatConstants.SHOW_TYPE);
requireNonNull(showType, WeChatConstants.SHOW_TYPE + " must not null"); msgType = config.get(WeChatConstants.MSG_TYPE);
webhookUrl = config.get(WeChatConstants.WEBHOOK); requireNonNull(msgType, WeChatConstants.MSG_TYPE + " must not null");
webhookUrl = config.get(WeChatConstants.WEB_HOOK);
keyWord = config.get(WeChatConstants.KEYWORD); keyWord = config.get(WeChatConstants.KEYWORD);
if (sendType.equals(WeChatType.CHAT.getValue())) { if (sendType.equals(WeChatType.CHAT.getValue())) {
requireNonNull(webhookUrl, WeChatConstants.WEBHOOK + " must not null"); requireNonNull(webhookUrl, WeChatConstants.WEB_HOOK + " must not null");
} }
weChatTokenUrlReplace = weChatTokenUrlReplace =
weChatTokenUrl weChatTokenUrl
...@@ -117,47 +119,19 @@ public class WeChatSender { ...@@ -117,47 +119,19 @@ public class WeChatSender {
public AlertResult send(String title, String content) { public AlertResult send(String title, String content) {
AlertResult alertResult = new AlertResult(); AlertResult alertResult = new AlertResult();
List<String> userList = new ArrayList<>();
if (Asserts.isNotNullString(weChatUsers)) {
userList = Arrays.asList(weChatUsers.split(","));
}
if (atAll) {
userList.add("所有人");
}
String data = ""; List<String> userList = getUserList();
if (sendType.equals(WeChatType.CHAT.getValue())) {
data = markdownByAlert(title, content, userList); String sendMsgOfResult = buildFinalResultMsgBody(title, content, userList, sendType);
} else {
data = markdownByAlert(title, content, userList); String msg = replaceParamsToBuildSendMsgTemplate(userList, sendMsgOfResult);
}
String msg = "";
if (sendType.equals(WeChatType.APP.getValue())) {
msg =
weChatUserSendMsg
.replace(USER_REG_EXP, mkUserString(userList))
.replace(AGENT_ID_REG_EXP, weChatAgentId)
.replace(MSG_REG_EXP, data)
.replace(SHOW_TYPE_REGEX, showType);
} else {
msg =
WeChatConstants.WEBHOOK_TEMPLATE
.replace(SHOW_TYPE_REGEX, showType)
.replace(MSG_REG_EXP, data);
}
if (sendType.equals(WeChatType.APP.getValue()) && Asserts.isNullString(weChatToken)) { if (sendType.equals(WeChatType.APP.getValue()) && Asserts.isNullString(weChatToken)) {
alertResult.setMessage("send we chat alert fail,get weChat token error"); alertResult.setMessage("send we chat alert fail,get weChat token error");
alertResult.setSuccess(false); alertResult.setSuccess(false);
return alertResult; return alertResult;
} }
String enterpriseWeChatPushUrlReplace = ""; String enterpriseWeChatPushUrlReplace = buildPushUrl();
if (sendType.equals(WeChatType.APP.getValue())) {
enterpriseWeChatPushUrlReplace =
WeChatConstants.PUSH_URL.replace(TOKEN_REGEX, weChatToken);
} else if (sendType.equals(WeChatType.CHAT.getValue())) {
enterpriseWeChatPushUrlReplace = webhookUrl;
}
try { try {
return checkWeChatSendMsgResult(post(enterpriseWeChatPushUrlReplace, msg)); return checkWeChatSendMsgResult(post(enterpriseWeChatPushUrlReplace, msg));
} catch (Exception e) { } catch (Exception e) {
...@@ -168,6 +142,52 @@ public class WeChatSender { ...@@ -168,6 +142,52 @@ public class WeChatSender {
return alertResult; return alertResult;
} }
/**
* build wechat push url to send msg template
*
* @return
*/
private String buildPushUrl() {
if (sendType.equals(WeChatType.APP.getValue())) {
return WeChatConstants.WECHAT_PUSH_URL.replace(TOKEN_REGEX, weChatToken);
} else {
return webhookUrl;
}
}
/**
* replace params to build send msg template
*
* @param userList
* @param sendMsgOfResult
* @return
*/
private String replaceParamsToBuildSendMsgTemplate(
List<String> userList, String sendMsgOfResult) {
if (sendType.equals(WeChatType.APP.getValue())) {
return weChatUserSendMsg
.replace(USER_REG_EXP, buildAtUserList(userList))
.replace(AGENT_ID_REG_EXP, weChatAgentId)
.replace(MSG_REG_EXP, sendMsgOfResult)
.replace(SHOW_TYPE_REGEX, msgType);
} else {
return WeChatConstants.WECHAT_WEBHOOK_TEMPLATE
.replace(SHOW_TYPE_REGEX, msgType)
.replace(MSG_REG_EXP, sendMsgOfResult);
}
}
private List<String> getUserList() {
List<String> userList = new ArrayList<>();
if (Asserts.isNotNullString(weChatUsers)) {
userList = Arrays.asList(weChatUsers.split(","));
}
if (atAll) {
userList.add("all");
}
return userList;
}
private static String post(String url, String data) throws IOException { private static String post(String url, String data) throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) { try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(url); HttpPost httpPost = new HttpPost(url);
...@@ -181,11 +201,11 @@ public class WeChatSender { ...@@ -181,11 +201,11 @@ public class WeChatSender {
} finally { } finally {
response.close(); response.close();
} }
// logger.info("Enterprise WeChat send [{}], param:{}, resp:{}", url, data, resp);
return resp; return resp;
} }
} }
@Deprecated
private static String mkUserList(Iterable<String> list) { private static String mkUserList(Iterable<String> list) {
StringBuilder sb = new StringBuilder("["); StringBuilder sb = new StringBuilder("[");
for (String name : list) { for (String name : list) {
...@@ -196,7 +216,13 @@ public class WeChatSender { ...@@ -196,7 +216,13 @@ public class WeChatSender {
return sb.toString(); return sb.toString();
} }
private static String mkUserString(Iterable<String> list) { /**
* generate AtUser List
*
* @param list
* @return
*/
private static String buildAtUserList(Iterable<String> list) {
if (Asserts.isNull(list)) { if (Asserts.isNull(list)) {
return null; return null;
} }
...@@ -220,14 +246,14 @@ public class WeChatSender { ...@@ -220,14 +246,14 @@ public class WeChatSender {
* @param userList * @param userList
* @return java.lang.String * @return java.lang.String
*/ */
private static String mkMarkDownAtUsers(List<String> userList) { private static String generateMarkDownAtUsers(List<String> userList) {
StringBuilder builder = new StringBuilder("\n"); StringBuilder builder = new StringBuilder("\n");
if (Asserts.isNotNull(userList)) { if (Asserts.isNotNull(userList)) {
userList.forEach( userList.forEach(
value -> { value -> {
if (value.equals("所有人") && showType.equals(ShowType.TEXT.getValue())) { if ("all".equals(value) && msgType.equals(ShowType.TEXT.getValue())) {
builder.append("@所有人 "); builder.append("@all ");
} else { } else {
builder.append("<@").append(value).append("> "); builder.append("<@").append(value).append("> ");
} }
...@@ -236,26 +262,6 @@ public class WeChatSender { ...@@ -236,26 +262,6 @@ public class WeChatSender {
return builder.toString(); return builder.toString();
} }
private String markdownByAlert(String title, String content, List<String> userList) {
String result = "";
if (showType.equals(ShowType.MARKDOWN.getValue())) {
result = markdownTable(title, content, userList, sendType);
} else if (showType.equals(ShowType.TEXT.getValue())) {
result = markdownText(title, content, userList, sendType);
}
return result;
}
private static String markdownTable(
String title, String content, List<String> userList, String sendType) {
return getMsgResult(title, content, userList, sendType);
}
private static String markdownText(
String title, String content, List<String> userList, String sendType) {
return getMsgResult(title, content, userList, sendType);
}
/** /**
* @Author: zhumingye * @Author: zhumingye
* *
...@@ -266,7 +272,7 @@ public class WeChatSender { ...@@ -266,7 +272,7 @@ public class WeChatSender {
* @return java.lang.String * @return java.lang.String
* @throws * @throws
*/ */
private static String getMsgResult( private static String buildFinalResultMsgBody(
String title, String content, List<String> userList, String sendType) { String title, String content, List<String> userList, String sendType) {
List<LinkedHashMap> mapItemsList = JSONUtil.toList(content, LinkedHashMap.class); List<LinkedHashMap> mapItemsList = JSONUtil.toList(content, LinkedHashMap.class);
...@@ -274,21 +280,20 @@ public class WeChatSender { ...@@ -274,21 +280,20 @@ public class WeChatSender {
logger.error("itemsList is null"); logger.error("itemsList is null");
throw new RuntimeException("itemsList is null"); throw new RuntimeException("itemsList is null");
} }
String markDownAtUsers = mkMarkDownAtUsers(userList); String markDownAtUsers = generateMarkDownAtUsers(userList);
StringBuilder contents = new StringBuilder(200); StringBuilder contents = new StringBuilder(200);
for (LinkedHashMap mapItems : mapItemsList) { for (LinkedHashMap mapItems : mapItemsList) {
Set<Map.Entry<String, Object>> entries = mapItems.entrySet(); Set<Map.Entry<String, Object>> entries = mapItems.entrySet();
Iterator<Map.Entry<String, Object>> iterator = entries.iterator(); Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
StringBuilder t = StringBuilder t =
new StringBuilder( new StringBuilder(String.format("`%s`%s", title, WeChatConstants.ENTER_LINE));
String.format("`%s`%s", title, WeChatConstants.MARKDOWN_ENTER));
while (iterator.hasNext()) { while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next(); Map.Entry<String, Object> entry = iterator.next();
t.append(WeChatConstants.MARKDOWN_QUOTE); t.append(WeChatConstants.MARKDOWN_QUOTE_RIGHT_TAG_WITH_SPACE);
t.append(entry.getKey()).append(":").append(entry.getValue()); t.append(entry.getKey()).append(":").append(entry.getValue());
t.append(WeChatConstants.MARKDOWN_ENTER); t.append(WeChatConstants.ENTER_LINE);
} }
contents.append(t); contents.append(t);
} }
...@@ -300,14 +305,14 @@ public class WeChatSender { ...@@ -300,14 +305,14 @@ public class WeChatSender {
private String getToken() { private String getToken() {
try { try {
return get(weChatTokenUrlReplace); return getAccessToken(weChatTokenUrlReplace);
} catch (IOException e) { } catch (IOException e) {
logger.info("we chat alert get token error{}", e.getMessage()); logger.info("we chat alert get token error{}", e.getMessage());
} }
return null; return null;
} }
private static String get(String url) throws IOException { private static String getAccessToken(String url) throws IOException {
String resp; String resp;
try (CloseableHttpClient httpClient = HttpClients.createDefault()) { try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(url); HttpGet httpGet = new HttpGet(url);
...@@ -317,8 +322,8 @@ public class WeChatSender { ...@@ -317,8 +322,8 @@ public class WeChatSender {
EntityUtils.consume(entity); EntityUtils.consume(entity);
} }
HashMap<String, Object> map = JSONUtil.parseObject(resp, HashMap.class); HashMap<String, Object> map = JSONUtil.parseObject(resp, HashMap.class);
if (map != null && null != map.get("access_token")) { if (map != null && null != map.get(WeChatConstants.ACCESS_TOKEN)) {
return map.get("access_token").toString(); return map.get(WeChatConstants.ACCESS_TOKEN).toString();
} else { } else {
return null; return null;
} }
......
...@@ -57,13 +57,13 @@ public class WeChatSenderTest { ...@@ -57,13 +57,13 @@ public class WeChatSenderTest {
weChatConfig.put(WeChatConstants.CORP_ID, "CORP_ID"); weChatConfig.put(WeChatConstants.CORP_ID, "CORP_ID");
weChatConfig.put(WeChatConstants.CHARSET, "UTF-8"); weChatConfig.put(WeChatConstants.CHARSET, "UTF-8");
weChatConfig.put( weChatConfig.put(
WeChatConstants.USER_SEND_MSG, WeChatConstants.WECHAT_APP_TEMPLATE,
"{\"touser\":\"{toUser}\",\"agentid\":{agentId}" "{\"touser\":\"{toUser}\",\"agentid\":{agentId}"
+ ",\"msgtype\":\"{showType}\",\"{showType}\":{\"content\":\"{msg}\"}}"); + ",\"msgtype\":\"{showType}\",\"{showType}\":{\"content\":\"{msg}\"}}");
weChatConfig.put(WeChatConstants.USERS, "all"); weChatConfig.put(WeChatConstants.AT_USERS, "all");
weChatConfig.put(WeChatConstants.TEAM_SEND_MSG, "msg"); weChatConfig.put(WeChatConstants.TEAM_SEND_MSG, "msg");
weChatConfig.put( weChatConfig.put(
WeChatConstants.SHOW_TYPE, ShowType.MARKDOWN.getValue()); // default is "table" WeChatConstants.MSG_TYPE, ShowType.MARKDOWN.getValue()); // default is "table"
weChatConfig.put(WeChatConstants.SEND_TYPE, WeChatType.APP.getValue()); weChatConfig.put(WeChatConstants.SEND_TYPE, WeChatType.APP.getValue());
} }
...@@ -78,7 +78,7 @@ public class WeChatSenderTest { ...@@ -78,7 +78,7 @@ public class WeChatSenderTest {
@Ignore @Ignore
@Test @Test
public void testSendAPPTextMsg() { public void testSendAPPTextMsg() {
weChatConfig.put(WeChatConstants.SHOW_TYPE, ShowType.TEXT.getValue()); weChatConfig.put(WeChatConstants.MSG_TYPE, ShowType.TEXT.getValue());
WeChatSender weChatSender = new WeChatSender(weChatConfig); WeChatSender weChatSender = new WeChatSender(weChatConfig);
AlertResult alertResult = weChatSender.send("Dinky企微APP TEXT方式 告警测试", contentTest); AlertResult alertResult = weChatSender.send("Dinky企微APP TEXT方式 告警测试", contentTest);
Assert.assertEquals(true, alertResult.getSuccess()); Assert.assertEquals(true, alertResult.getSuccess());
...@@ -88,11 +88,12 @@ public class WeChatSenderTest { ...@@ -88,11 +88,12 @@ public class WeChatSenderTest {
@Test @Test
public void testChatMarkDownMsg() throws IOException { public void testChatMarkDownMsg() throws IOException {
weChatConfig.put( weChatConfig.put(
WeChatConstants.WEBHOOK, WeChatConstants.WEB_HOOK,
"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=8xxxxxxxxxxxxxxxxx6fe13396c"); "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=8xxxxxxxxxxxxxxxxx6fe13396c");
weChatConfig.put(WeChatConstants.SEND_TYPE, WeChatType.CHAT.getValue()); weChatConfig.put(WeChatConstants.SEND_TYPE, WeChatType.CHAT.getValue());
weChatConfig.put(WeChatConstants.USER_SEND_MSG, WeChatConstants.WEBHOOK_TEMPLATE); weChatConfig.put(
weChatConfig.put(WeChatConstants.SHOW_TYPE, ShowType.MARKDOWN.getValue()); WeChatConstants.WECHAT_APP_TEMPLATE, WeChatConstants.WECHAT_WEBHOOK_TEMPLATE);
weChatConfig.put(WeChatConstants.MSG_TYPE, ShowType.MARKDOWN.getValue());
weChatConfig.put(WeChatConstants.KEYWORD, "Dinky企微WEBHOOK MarkDown方式 告警测试"); weChatConfig.put(WeChatConstants.KEYWORD, "Dinky企微WEBHOOK MarkDown方式 告警测试");
WeChatSender weChatSender = new WeChatSender(weChatConfig); WeChatSender weChatSender = new WeChatSender(weChatConfig);
AlertResult alertResult = weChatSender.send("TEXT-TEST", contentTest); AlertResult alertResult = weChatSender.send("TEXT-TEST", contentTest);
...@@ -103,11 +104,12 @@ public class WeChatSenderTest { ...@@ -103,11 +104,12 @@ public class WeChatSenderTest {
@Test @Test
public void testChatTextMsg() throws IOException { public void testChatTextMsg() throws IOException {
weChatConfig.put( weChatConfig.put(
WeChatConstants.WEBHOOK, WeChatConstants.WEB_HOOK,
"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=822d17a1-d6e5-43c2-a566-4846fe13396c"); "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=822d17a1-d6e5-43c2-a566-4846fe13396c");
weChatConfig.put(WeChatConstants.SEND_TYPE, WeChatType.CHAT.getValue()); weChatConfig.put(WeChatConstants.SEND_TYPE, WeChatType.CHAT.getValue());
weChatConfig.put(WeChatConstants.USER_SEND_MSG, WeChatConstants.WEBHOOK_TEMPLATE); weChatConfig.put(
weChatConfig.put(WeChatConstants.SHOW_TYPE, ShowType.TEXT.getValue()); WeChatConstants.WECHAT_APP_TEMPLATE, WeChatConstants.WECHAT_WEBHOOK_TEMPLATE);
weChatConfig.put(WeChatConstants.MSG_TYPE, ShowType.TEXT.getValue());
weChatConfig.put(WeChatConstants.KEYWORD, "Dinky企微WEBHOOK TEXT方式 告警测试"); weChatConfig.put(WeChatConstants.KEYWORD, "Dinky企微WEBHOOK TEXT方式 告警测试");
WeChatSender weChatSender = new WeChatSender(weChatConfig); WeChatSender weChatSender = new WeChatSender(weChatConfig);
AlertResult alertResult = weChatSender.send("TEXT-TEST", contentTest); AlertResult alertResult = weChatSender.send("TEXT-TEST", contentTest);
......
...@@ -7,7 +7,7 @@ title: 扩展报警插件 ...@@ -7,7 +7,7 @@ title: 扩展报警插件
Dinky 告警机制遵循 SPI,可随意扩展所需要的告警机制。如需扩展可在 dlink-alert 模块中进行可插拔式扩展。现已经支持的告警机制包括如下: Dinky 告警机制遵循 SPI,可随意扩展所需要的告警机制。如需扩展可在 dinky-alert 模块中进行可插拔式扩展。现已经支持的告警机制包括如下:
- DingDingTalk - DingDingTalk
- 企业微信: 同时支持**APP** 和 **WeChat 群聊** 方式 - 企业微信: 同时支持**APP** 和 **WeChat 群聊** 方式
...@@ -21,39 +21,46 @@ Dinky 学习了 ``Apache Dolphinscheduler`` 的插件扩展机制,可以在 Di ...@@ -21,39 +21,46 @@ Dinky 学习了 ``Apache Dolphinscheduler`` 的插件扩展机制,可以在 Di
- 详见 [开发者本地调试手册](../../developer_guide/local_debug) - 详见 [开发者本地调试手册](../../developer_guide/local_debug)
## 后端开发 ## 后端开发
- 在 dlink-alert 新建子模块 , 命名规则为 `dlink-alert-{报警类型}` 在子模块中实现 `dlink-alert-{报警类型}` 的报警机制 - 在 **dinky-alert** 新建子模块 , 命名规则为 `dinky-alert-{报警类型}` 在子模块中实现相关告警机制
## 后端开发
- 在 **dlink-alert** 模块中, 右键**新建子模块**, 命名规则: **dlink-alert-{报警类型}**
- **代码层面** 根据告警场景自行实现报警逻辑 - **代码层面** 根据告警场景自行实现报警逻辑
- 注意事项: - 注意事项:
- 不可在父类的基础上修改代码,可以在子类中进行扩展 ,或者重写父类方法 - 不可在父类的基础上修改代码,可以在子类中进行扩展 ,或者重写父类方法
- 注意告警所使用到的常量需要继承**AlertBaseConstant** 其他差异的特殊常量在新建的模块中定义,参考其他告警类型代码
- 扩展告警类型需要同时提交**测试用例** - 扩展告警类型需要同时提交**测试用例**
- 在每个告警类型的 Constants 常量类中 必须声明 ``static final String TYPE = "Email";`` 否则会报错 - 需要在新建的此模块的 **resource** 下 新建包 ``META-INF.services`` , 在此包中新建文件 ``org.dinky.alert.Alert`` 内容如下:
- 需要在此模块的 **resource** 下 新建包 ``META-INF.services`` , 在此包中新建文件 ``com.dlink.alert.Alert`` 内容如下: - ``org.dinky.alert.{报警类型}.{报警类型Alert}`` 参考其他告警类型的此文件
- ``com.dlink.alert.{报警类型}.{报警类型Alert}`` 参考其他告警类型的此文件
- 打包相关配置 修改如下: - 打包相关配置 修改如下:
- 在 **dlink-core** 模块的 **pom.xml** 下 , 找到扩展告警相关的依赖 `放在一起方便管理` 并且新增如下内容: - 在 **dinky-core** 模块的 **pom.xml** 下 , 找到扩展告警相关的依赖 `放在一起方便管理` 并且新增如下内容:
```xml ```xml
<dependency> <dependency>
<groupId>com.dlink</groupId> <groupId>org.dinky</groupId>
<artifactId>模块名称</artifactId> <artifactId>模块名称</artifactId>
<scope>${scope.runtime}</scope> <scope>${scope.runtime}</scope>
</dependency> </dependency>
``` ```
- 在 **dlink** 根下 **pom.xml** 中 ,新增如下内容:
```xml - 在 **dinky-admin** 模块的 **pom.xml** 下 , 找到扩展告警相关的依赖 `放在一起方便管理` 并且新增如下内容:
```xml
<dependency> <dependency>
<groupId>com.dlink</groupId> <groupId>org.dinky</groupId>
<artifactId>模块名称</artifactId>
<scope>${expand.scope}</scope>
</dependency>
```
- 在 **dinky** 根下 **pom.xml** 中 ,新增如下内容:
```xml
<dependency>
<groupId>org.dinky</groupId>
<artifactId>模块名称</artifactId> <artifactId>模块名称</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
``` ```
- 在 **dlink-assembly** 模块中 , 找到 ``package.xml`` 路径: **/dlink-assembly/src/main/assembly/package.xml** , 新增如下内容: - 在 **dinky-assembly** 模块中 , 找到 ``package.xml`` 路径: **/dinky-assembly/src/main/assembly/package.xml** , 新增如下内容:
```xml ```xml
<fileSet> <fileSet>
<directory>${project.parent.basedir}/dlink-alert/模块名称/target <directory>${project.parent.basedir}/dinky-alert/模块名称/target
</directory> </directory>
<outputDirectory>lib</outputDirectory> <outputDirectory>lib</outputDirectory>
<includes> <includes>
...@@ -67,36 +74,36 @@ Dinky 学习了 ``Apache Dolphinscheduler`` 的插件扩展机制,可以在 Di ...@@ -67,36 +74,36 @@ Dinky 学习了 ``Apache Dolphinscheduler`` 的插件扩展机制,可以在 Di
## 前端开发 ## 前端开发
- **dlink-web** 为 Dinky 的前端模块 - **dlink-web** 为 Dinky 的前端模块
- 扩展告警插件相关表单所在路径: `dlink-web/src/pages/AlertInstance` - 扩展告警插件相关表单所在路径: `dlink-web/src/pages/RegistrationCenter/AlertManage/AlertInstance`
- 修改 `dlink-web/src/pages/AlertInstance/conf.ts` - 修改 `dlink-web/src/pages/RegistrationCenter/AlertManage/AlertInstance/conf.ts`
**ALERT_TYPE** 添加如下 eg: **ALERT_TYPE** 添加如下 eg:
``` ``` typescript
EMAIL:'Email', EMAIL:'Email',
``` ```
**ALERT_CONFIG_LIST** 添加如下 eg: **ALERT_CONFIG_LIST** 添加如下 eg:
``` ```typescript
{ {
type: ALERT_TYPE.EMAIL, type: ALERT_TYPE.EMAIL,
} }
``` ```
**注意:** 此处属性值需要与后端 `static final String TYPE = "Email";`变量值保持一致 **注意:** 此处属性值需要与后端 `AlertTypeEnum` 声明的值保持一致
如下图: 如下图:
![extend_alert_conf](http://www.aiwenmo.com/dinky/docs/zh-CN/extend/function_expansion/alert/extend_alert_conf.png) ![extend_alert_conf](http://www.aiwenmo.com/dinky/docs/zh-CN/extend/function_expansion/alert/extend_alert_conf.png)
修改 `dlink-web/src/pages/AlertInstance/icon.tsx` 的 **getAlertIcon** 中 修改 `dlink-web/src/pages/RegistrationCenter/AlertManage/AlertInstance/icon.tsx` 的 **getAlertIcon** 中
添加如下 eg: 添加如下 eg:
``` ```typescript
case ALERT_TYPE.EMAIL: case ALERT_TYPE.EMAIL:
return (<Icon component={EmailSvg}/>); return (<Icon component={EmailSvg}/>);
``` ```
同时在下方定义 SVG : `如不定义将使用默认 SVG` 同时在下方定义 SVG : `如不定义将使用默认 SVG`
svg 获取: [https://www.iconfont.cn](https://www.iconfont.cn) svg 获取: [https://www.iconfont.cn](https://www.iconfont.cn)
``` ``` typescript
export const EmailSvg = () => ( export const EmailSvg = () => (
{svg 相关代码} {svg 相关代码}
); );
...@@ -108,10 +115,10 @@ export const EmailSvg = () => ( ...@@ -108,10 +115,10 @@ export const EmailSvg = () => (
- 修改 `dlink-web/src/pages/AlertInstance/components/AlertInstanceChooseForm.tsx` - 修改 `dlink-web/src/pages/RegistrationCenter/AlertManage/AlertInstance/components/AlertInstanceChooseForm.tsx`
追加如下 eg: 追加如下 eg:
``` ```typescript
{(values?.type == ALERT_TYPE.EMAIL || alertType == ALERT_TYPE.EMAIL)? {(values?.type == ALERT_TYPE.EMAIL || alertType == ALERT_TYPE.EMAIL)?
<EmailForm <EmailForm
onCancel={() => { onCancel={() => {
...@@ -130,8 +137,8 @@ export const EmailSvg = () => ( ...@@ -130,8 +137,8 @@ export const EmailSvg = () => (
} }
``` ```
其中需要修改的地方为 其中需要修改的地方为
- `EMAIL` 替换为上述 **dlink-web/src/pages/AlertInstance/conf.ts** 中 **ALERT_TYPE** 的新增类型 - `EMAIL` 替换为上述 **dlink-web/src/pages/RegistrationCenter/AlertManage/AlertInstance/conf.ts** 中 **ALERT_TYPE** 的新增类型
- `EmailForm` 为新建告警表单文件 **dlink-web/src/pages/AlertInstance/components/EmailForm.tsx** 中的 **EmailForm** . - `EmailForm` 为新建告警表单文件 **dlink-web/src/pages/RegistrationCenter/AlertManage/AlertInstance/components/EmailForm.tsx** 中的 **EmailForm** .
如下图: 如下图:
![extened_alert_choose_form](http://www.aiwenmo.com/dinky/docs/zh-CN/extend/function_expansion/alert/extened_alert_choose_form.png) ![extened_alert_choose_form](http://www.aiwenmo.com/dinky/docs/zh-CN/extend/function_expansion/alert/extened_alert_choose_form.png)
...@@ -143,12 +150,12 @@ export const EmailSvg = () => ( ...@@ -143,12 +150,12 @@ export const EmailSvg = () => (
- 需要修改 如下的表单配置 - 需要修改 如下的表单配置
```shell ```typescript
找到如下相关代码: // 找到如下相关代码:
const [formVals, setFormVals] = useState<Partial<AlertInstanceTableListItem>>({ const [formVals, setFormVals] = useState<Partial<AlertInstanceTableListItem>>({
id: props.values?.id, id: props.values?.id,
name: props.values?.name, name: props.values?.name,
type: ALERT_TYPE.EMAIL, # 此处需要修改为新增的告警类型 type: ALERT_TYPE.EMAIL, // 此处需要修改为新增的告警类型
params: props.values?.params, params: props.values?.params,
enabled: props.values?.enabled, enabled: props.values?.enabled,
}); });
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment