Compare commits

...
8 Commits
27 changed files with 745 additions and 42 deletions
+4
View File
@@ -170,6 +170,10 @@ robot.callback_with_sender_info false
## 机器人回调信息是否带上目标的信息,单聊时是对方用户信息,群聊时是群组信息,频道时是频道信息
robot.callback_with_target_info false
## 是否允许@会话外的机器人。如果为true,单聊或者群聊时,可以@不在会话中的机器人。当机器人收到消息后,可以回复消息。
## 如果为false,不能@不在会话中的机器人。机器人不在会话中时,也不能回复消息。
robot.mention_external_robot true
## 频道回调信息是否带上用户clientId和平台类型。
channel.callback_with_client_info false
+1
View File
@@ -0,0 +1 @@
alter table `t_messages` modify column `_target` varchar(129) NOT NULL;
+37
View File
@@ -0,0 +1,37 @@
alter table `t_messages` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_0` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_1` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_2` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_3` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_4` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_5` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_6` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_7` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_8` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_9` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_10` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_11` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_12` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_13` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_14` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_15` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_16` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_17` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_18` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_19` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_20` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_21` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_22` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_23` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_24` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_25` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_26` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_27` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_28` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_29` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_30` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_31` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_32` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_33` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_34` modify column `_target` varchar(129) NOT NULL;
alter table `t_messages_35` modify column `_target` varchar(129) NOT NULL;
+1 -1
View File
@@ -5,7 +5,7 @@
<relativePath>../</relativePath>
<artifactId>wildfirechat-parent</artifactId>
<groupId>cn.wildfirechat</groupId>
<version>1.3.8</version>
<version>1.3.9</version>
</parent>
<artifactId>moquette-broker</artifactId>
@@ -0,0 +1,112 @@
/*
* This file is part of the Wildfire Chat package.
* (c) Heavyrain2012 <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package com.xiaoleilu.loServer.action.robot;
import cn.wildfirechat.common.APIPath;
import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.Conversation;
import cn.wildfirechat.pojos.ReplyMessageData;
import cn.wildfirechat.pojos.SendMessageData;
import cn.wildfirechat.pojos.SendMessageResult;
import cn.wildfirechat.proto.ProtoConstants;
import cn.wildfirechat.proto.WFCMessage;
import com.xiaoleilu.loServer.RestResult;
import com.xiaoleilu.loServer.annotation.HttpMethod;
import com.xiaoleilu.loServer.annotation.Route;
import com.xiaoleilu.loServer.handler.Request;
import com.xiaoleilu.loServer.handler.Response;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.jetbrains.annotations.NotNull;
import win.liyufan.im.IMTopic;
import java.util.Arrays;
@Route(APIPath.Robot_Message_Reply)
@HttpMethod("POST")
public class ReplyMessageAction extends RobotAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {
if (request.getNettyRequest() instanceof FullHttpRequest) {
ReplyMessageData replyMessageData = getRequestBody(request.getNettyRequest(), ReplyMessageData.class);
if (ReplyMessageData.isValide(replyMessageData)) {
WFCMessage.Message message = messagesStore.getMessage(replyMessageData.getMessageUid());
ErrorCode errorCode = null;
if(message == null) {
errorCode = ErrorCode.ERROR_CODE_NOT_EXIST;
} else if(!message.getContent().getMentionedTargetList().contains(robot.getUid())) {
errorCode = ErrorCode.ERROR_CODE_INVALID_MESSAGE;
} else if(message.getConversation().getType() != ProtoConstants.ConversationType.ConversationType_Private && message.getConversation().getType() != ProtoConstants.ConversationType.ConversationType_Group) {
errorCode = ErrorCode.ERROR_CODE_NOT_IMPLEMENT;
} else if(System.currentTimeMillis() - message.getServerTimestamp() > 15*60*1000) {
errorCode = ErrorCode.ERROR_CODE_RECALL_TIME_EXPIRED;
} else if(!messagesStore.isRobotMentionExternalRobot()) {
if(message.getConversation().getType() != ProtoConstants.ConversationType.ConversationType_Group) {
errorCode = ErrorCode.ERROR_CODE_NOT_IMPLEMENT;
} else {
WFCMessage.GroupMember member = messagesStore.getGroupMember(message.getConversation().getTarget(), robot.getUid());
if(member == null || member.getType() == ProtoConstants.GroupMemberType.GroupMemberType_Removed) {
errorCode = ErrorCode.ERROR_CODE_NOT_IMPLEMENT;
}
}
}
if(errorCode != null) {
response.setStatus(HttpResponseStatus.OK);
RestResult result = RestResult.resultOf(errorCode);
response.setContent(gson.toJson(result));
return true;
}
SendMessageData sendMessageData = getSendMessageData(message, replyMessageData);
WFCMessage.Message newMsg = sendMessageData.toProtoMessage().toBuilder().setMessageId(message.getMessageId()).build();
sendApiRequest(response, IMTopic.RobotReplyMessageTopic, newMsg.toByteArray(), result -> {
ByteBuf byteBuf = Unpooled.buffer();
byteBuf.writeBytes(result);
ErrorCode ec = ErrorCode.fromCode(byteBuf.readByte());
if (ec == ErrorCode.ERROR_CODE_SUCCESS) {
long messageId = byteBuf.readLong();
long timestamp = byteBuf.readLong();
sendResponse(response, null, new SendMessageResult(messageId, timestamp));
} else {
sendResponse(response, ec, null);
}
});
return false;
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
}
private @NotNull SendMessageData getSendMessageData(WFCMessage.Message message, ReplyMessageData replyMessageData) {
SendMessageData sendMessageData = new SendMessageData();
sendMessageData.setSender(robot.getUid());
Conversation conversation = new Conversation();
conversation.setType(message.getConversation().getType());
conversation.setLine(message.getConversation().getLine());
conversation.setTarget(message.getConversation().getTarget());
sendMessageData.setConv(conversation);
sendMessageData.setPayload(replyMessageData.getPayload());
if(replyMessageData.isOnly2Sender()) {
sendMessageData.setToUsers(Arrays.asList(message.getFromUser()));
}
return sendMessageData;
}
}
@@ -173,6 +173,8 @@ public final class BrokerConstants {
public static final String ROBOT_Callback_With_Client_Info = "robot.callback_with_client_info";
public static final String ROBOT_Callback_With_Sender_Info = "robot.callback_with_sender_info";
public static final String ROBOT_Callback_With_Target_Info = "robot.callback_with_target_info";
public static final String ROBOT_Mention_External_Robot = "robot.mention_external_robot";
public static final String CHANNEL_Callback_With_Client_Info = "channel.callback_with_client_info";
public static final String CHANNEL_Callback_With_Sender_Info = "channel.callback_with_sender_info";
@@ -0,0 +1,348 @@
/*
* This file is part of the Wildfire Chat package.
* (c) Heavyrain2012 <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package io.moquette.imhandler;
import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.MessagePayload;
import cn.wildfirechat.proto.ProtoConstants;
import cn.wildfirechat.proto.WFCMessage;
import com.hazelcast.util.StringUtil;
import io.moquette.BrokerConstants;
import io.moquette.spi.impl.Qos1PublishHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import win.liyufan.im.*;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import static cn.wildfirechat.common.ErrorCode.ERROR_CODE_NOT_IN_GROUP;
import static cn.wildfirechat.common.ErrorCode.ERROR_CODE_SUCCESS;
@Handler(value = IMTopic.RobotReplyMessageTopic)
public class ReplyMessageHandler extends IMHandler<WFCMessage.Message> {
private int mSensitiveType = 0; //命中敏感词时,0 失败,1 吞掉, 2 敏感词替换成*。
private String mForwardUrl = null;
private String mSensitiveMessageForwardUrl = null;
private Set<Integer> mForwardMessageTypes = new HashSet<>();
private Set<Integer> mForwardExcludeMessageTypes = new HashSet<>();
private String mMentionForwardUrl = null;
private int mBlacklistStrategy = 0; //黑名单中时,0失败,1吞掉。
private boolean mBlacklistAllowSend2Black = true;
private boolean mNoForwardAdminMessage = false;
private boolean mAllowSend2ForbiddenUser = false;
private String mRemoteSensitiveServerUrl = null;
private Set<Integer> mRemoteSensitiveMessageTypes;
private boolean mWaitRemoteSensitiveServerResponse = false;
public ReplyMessageHandler() {
super();
mForwardUrl = mServer.getConfig().getProperty(BrokerConstants.MESSAGE_Forward_Url);
if (!StringUtil.isNullOrEmpty(mForwardUrl)) {
String forwardTypes = mServer.getConfig().getProperty(BrokerConstants.MESSAGE_Forward_Types);
parseTypes(mForwardMessageTypes, forwardTypes);
String excludeTypes = mServer.getConfig().getProperty(BrokerConstants.MESSAGE_Forward_Exclude_Types);
parseTypes(mForwardExcludeMessageTypes, excludeTypes);
}
mSensitiveMessageForwardUrl = mServer.getConfig().getProperty(BrokerConstants.MESSAGE_Sensitive_Forward_Url);
mMentionForwardUrl = mServer.getConfig().getProperty(BrokerConstants.MESSAGE_MentionMsg_Forward_Url);
try {
mSensitiveType = Integer.parseInt(mServer.getConfig().getProperty(BrokerConstants.SENSITIVE_Filter_Type));
} catch (Exception e) {
e.printStackTrace();
Utility.printExecption(LOG, e);
}
try {
mBlacklistStrategy = Integer.parseInt(mServer.getConfig().getProperty(BrokerConstants.MESSAGE_Blacklist_Strategy));
} catch (Exception e) {
e.printStackTrace();
Utility.printExecption(LOG, e);
}
try {
mBlacklistAllowSend2Black = Boolean.parseBoolean(mServer.getConfig().getProperty(BrokerConstants.MESSAGE_Blacklist_Allow_Send, "true"));
} catch (Exception e) {
}
try {
mRemoteSensitiveServerUrl = mServer.getConfig().getProperty(BrokerConstants.SENSITIVE_Remote_Server_URL);
if(!StringUtil.isNullOrEmpty(mRemoteSensitiveServerUrl)) {
mWaitRemoteSensitiveServerResponse = Boolean.parseBoolean(mServer.getConfig().getProperty(BrokerConstants.SENSITIVE_Remote_Fail_When_Matched, "false"));
String types = mServer.getConfig().getProperty(BrokerConstants.SENSITIVE_Remote_Message_Type, "");
mRemoteSensitiveMessageTypes = new HashSet<>();
if(!StringUtil.isNullOrEmpty(types)) {
String[] ts = types.split(",");
for (String t:ts) {
mRemoteSensitiveMessageTypes.add(Integer.parseInt(t.trim()));
}
}
}
} catch (Exception e) {
e.printStackTrace();
Utility.printExecption(LOG, e);
}
try {
mNoForwardAdminMessage = Boolean.parseBoolean(mServer.getConfig().getProperty(BrokerConstants.MESSAGE_NO_Forward_Admin_Message, "false"));
} catch (Exception e) {
e.printStackTrace();
Utility.printExecption(LOG, e);
}
try {
mAllowSend2ForbiddenUser = Boolean.parseBoolean(mServer.getConfig().getProperty(BrokerConstants.MESSAGES_ALLOW_SEND_TO_FORBIDDEN_USER, "false"));
} catch (Exception e) {}
}
private void parseTypes(Collection<Integer> collection, String types) {
try {
if (!StringUtil.isNullOrEmpty(types)) {
String[] tss = types.split(",");
for (String ts:tss) {
if(ts.contains("-")) {
String[] ss = ts.split("-");
if(ss.length == 2) {
int begin = Integer.parseInt(ss[0]);
int end = Integer.parseInt(ss[1]);
for (int i = begin; i <= end ; i++) {
collection.add(i);
}
}
} else {
collection.add(Integer.parseInt(ts.trim()));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.Message message, Qos1PublishHandler.IMCallback callback) {
if(requestSourceType != ProtoConstants.RequestSourceType.Request_From_Robot) {
return ErrorCode.ERROR_CODE_NOT_IMPLEMENT;
}
ErrorCode errorCode = ErrorCode.ERROR_CODE_SUCCESS;
if (message != null) {
if(message.getContent().getContent().length() +
message.getContent().getSearchableContent().length() +
message.getContent().getData().size() +
message.getContent().getExtra().length() +
message.getContent().getPushContent().length() +
message.getContent().getPushData().length() > 64 * 1024) {
return ErrorCode.ERROR_CODE_MESSAGE_TOO_LARGE;
}
boolean ignoreMsg = false;
// 不能在端上直接发送撤回和群通知
if (message.getContent().getType() == 80 || message.getContent().getType() == 81 || (message.getContent().getType() >= 100 && message.getContent().getType() < 200)) {
return ErrorCode.INVALID_PARAMETER;
}
if(m_messagesStore.getClientForbiddenSendTypes().contains(message.getContent().getType())) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
int userStatus = m_messagesStore.getUserStatus(fromUser);
if (userStatus == ProtoConstants.UserStatus.Muted || userStatus == ProtoConstants.UserStatus.Forbidden) {
if(!m_messagesStore.getGlobalMuteExceptionTypes().contains(message.getContent().getType())) {
return ErrorCode.ERROR_CODE_FORBIDDEN_SEND_MSG;
}
}
if (message.getConversation().getType() == ProtoConstants.ConversationType.ConversationType_Private) {
if(!m_messagesStore.getBlackListExceptionTypes().contains(message.getContent().getType())) {
errorCode = m_messagesStore.isAllowUserMessage(message.getConversation().getTarget(), fromUser, message.getConversation().getLine());
if (errorCode != ErrorCode.ERROR_CODE_SUCCESS) {
if (errorCode == ErrorCode.ERROR_CODE_IN_BLACK_LIST && mBlacklistStrategy != ProtoConstants.BlacklistStrategy.Message_Reject) {
ignoreMsg = true;
errorCode = ErrorCode.ERROR_CODE_SUCCESS;
} else {
return errorCode;
}
}
if(!mBlacklistAllowSend2Black) {
errorCode = m_messagesStore.isBlacked(fromUser, message.getConversation().getTarget());
if (errorCode != ErrorCode.ERROR_CODE_SUCCESS) {
return errorCode;
}
}
}
if (!mAllowSend2ForbiddenUser) {
userStatus = m_messagesStore.getUserStatus(message.getConversation().getTarget());
if (userStatus == ProtoConstants.UserStatus.Forbidden) {
return ErrorCode.ERROR_CODE_USER_FORBIDDEN;
}
}
}
if (message.getConversation().getType() == ProtoConstants.ConversationType.ConversationType_Group ) {
if(!m_messagesStore.getGroupMuteExceptionTypes().contains(message.getContent().getType())) {
errorCode = m_messagesStore.canSendMessageInGroup(fromUser, message.getConversation().getTarget());
if(errorCode == ERROR_CODE_NOT_IN_GROUP) {
errorCode = ERROR_CODE_SUCCESS;
}
if (errorCode != ErrorCode.ERROR_CODE_SUCCESS) {
return errorCode;
}
}
} else if (message.getConversation().getType() == ProtoConstants.ConversationType.ConversationType_ChatRoom) {
if(!m_messagesStore.getGroupMuteExceptionTypes().contains(message.getContent().getType())) {
if (!m_messagesStore.checkUserClientInChatroom(fromUser, clientID, message.getConversation().getTarget())) {
return ErrorCode.ERROR_CODE_NOT_IN_CHATROOM;
}
}
} else if (message.getConversation().getType() == ProtoConstants.ConversationType.ConversationType_Channel) {
if(!m_messagesStore.getGroupMuteExceptionTypes().contains(message.getContent().getType())) {
if (!m_messagesStore.canSendMessageInChannel(fromUser, message.getConversation().getTarget())) {
return ErrorCode.ERROR_CODE_NOT_IN_CHANNEL;
}
}
}
if(message.getConversation().getType() == ProtoConstants.ConversationType.ConversationType_Private) {
long beforeMessageId = message.getMessageId();
WFCMessage.Message replyMsg = m_messagesStore.getMessage(beforeMessageId);
message = message.toBuilder().setConversation(message.getConversation().toBuilder().setTarget(replyMsg.getFromUser() + "|" + replyMsg.getConversation().getTarget())).build();
}
long timestamp = System.currentTimeMillis();
final long messageId;
try {
messageId = MessageShardingUtil.generateId();
} catch (Exception e) {
e.printStackTrace();
return ErrorCode.ERROR_CODE_SERVER_ERROR;
}
message = message.toBuilder().setFromUser(fromUser).setMessageId(messageId).setServerTimestamp(timestamp).build();
if (!StringUtil.isNullOrEmpty(mForwardUrl) && (mForwardMessageTypes.isEmpty() || mForwardMessageTypes.contains(message.getContent().getType())) && !mForwardExcludeMessageTypes.contains(message.getContent().getType())) {
publisher.forwardMessage(message, mForwardUrl, clientID);
}
if(!StringUtil.isNullOrEmpty(mMentionForwardUrl) && message.hasContent() && message.getContent().getMentionedType() != 0) {
publisher.forwardMessage(message, mMentionForwardUrl, clientID);
}
if(StringUtil.isNullOrEmpty(mRemoteSensitiveServerUrl)) {
Set<String> matched = m_messagesStore.handleSensitiveWord(message.getContent().getSearchableContent());
if (matched != null && !matched.isEmpty()) {
m_messagesStore.storeSensitiveMessage(message);
if (!StringUtil.isNullOrEmpty(mSensitiveMessageForwardUrl)) {
publisher.forwardMessage(message, mSensitiveMessageForwardUrl, clientID);
}
if (mSensitiveType == 0) {
errorCode = ErrorCode.ERROR_CODE_SENSITIVE_MATCHED;
} else if (mSensitiveType == 1) {
ignoreMsg = true;
} else if (mSensitiveType == 2) {
String text = message.getContent().getSearchableContent();
for (String word : matched) {
text = text.replace(word, "***");
}
message = message.toBuilder().setContent(message.getContent().toBuilder().setSearchableContent(text).build()).build();
}
}
} else {
if(mRemoteSensitiveMessageTypes.contains(message.getContent().getType())) {
final WFCMessage.Message finalMsg = message;
publisher.forwardMessageWithCallback(message, clientID, mRemoteSensitiveServerUrl, new HttpUtils.HttpCallback() {
@Override
public void onSuccess(String content) {
if(StringUtil.isNullOrEmpty(content)) {
saveAndPublish(fromUser, clientID, finalMsg, requestSourceType);
} else {
MessagePayload payload = GsonUtil.gson.fromJson(content, MessagePayload.class);
if (payload != null && payload.getType() > 0) {
WFCMessage.Message newMsg = finalMsg.toBuilder().setContent(payload.toProtoMessageContent()).build();
saveAndPublish(fromUser, clientID, newMsg, requestSourceType);
} else {
LOG.error("Response content {} from censor is invalid payload, ignore response and send original message", content);
saveAndPublish(fromUser, clientID, finalMsg, requestSourceType);
}
}
if(mWaitRemoteSensitiveServerResponse) {
ByteBuf ackPayload = Unpooled.buffer(21);
ErrorCode errorCode = ERROR_CODE_SUCCESS;
ackPayload.writeByte(errorCode.getCode());
ackPayload.writeLong(messageId);
ackPayload.writeLong(timestamp);
callback.onIMHandled(ErrorCode.ERROR_CODE_SUCCESS, ackPayload);
}
}
@Override
public void onFailure(int statusCode, String errorMessage) {
ByteBuf ackPayload = null;
ErrorCode errorCode = ERROR_CODE_SUCCESS;
if(statusCode == 403) {
if(mWaitRemoteSensitiveServerResponse) {
errorCode = ErrorCode.ERROR_CODE_SENSITIVE_MATCHED;
ackPayload = Unpooled.buffer(1);
ackPayload.writeByte(errorCode.getCode());
}
} else {
LOG.warn("Failed to censor message with status {}, errorMessage {}. Send the original message", statusCode, errorMessage);
saveAndPublish(fromUser, clientID, finalMsg, requestSourceType);
if(mWaitRemoteSensitiveServerResponse) {
errorCode = ERROR_CODE_SUCCESS;
ackPayload = Unpooled.buffer(21);
ackPayload.writeByte(errorCode.getCode());
ackPayload.writeLong(messageId);
ackPayload.writeLong(timestamp);
}
}
if(mWaitRemoteSensitiveServerResponse) {
callback.onIMHandled(errorCode, ackPayload);
}
}
});
if(mWaitRemoteSensitiveServerResponse) {
ackPayload.clear();
return ErrorCode.INVALID_ASYNC_HANDLING;
} else {
ackPayload = ackPayload.capacity(20);
ackPayload.writeLong(messageId);
ackPayload.writeLong(timestamp);
return ErrorCode.ERROR_CODE_SUCCESS;
}
}
}
if (errorCode == ErrorCode.ERROR_CODE_SUCCESS) {
if(!ignoreMsg) {
saveAndPublish(fromUser, clientID, message, requestSourceType);
}
ackPayload = ackPayload.capacity(20);
ackPayload.writeLong(messageId);
ackPayload.writeLong(timestamp);
}
} else {
errorCode = ErrorCode.ERROR_CODE_INVALID_MESSAGE;
}
return errorCode;
}
}
@@ -213,6 +213,7 @@ public class MemoryMessagesStore implements IMessagesStore {
private boolean mRobotCallbackWithClientInfo = false;
private boolean mRobotCallbackWithSenderInfo = false;
private boolean mRobotCallbackWithTargetInfo = false;
private boolean mRobotMentionExternalRobot = false;
private boolean mChannelCallbackWithClientInfo = false;
private boolean mChannelCallbackWithSenderInfo = false;
@@ -646,6 +647,9 @@ public class MemoryMessagesStore implements IMessagesStore {
try {
mRobotCallbackWithTargetInfo = Boolean.parseBoolean(server.getConfig().getProperty(BrokerConstants.ROBOT_Callback_With_Target_Info, "false"));
} catch (Exception e) {}
try {
mRobotMentionExternalRobot = Boolean.parseBoolean(server.getConfig().getProperty(BrokerConstants.ROBOT_Mention_External_Robot, "false"));
} catch (Exception e) {}
try {
mChannelCallbackWithClientInfo = Boolean.parseBoolean(server.getConfig().getProperty(BrokerConstants.CHANNEL_Callback_With_Client_Info, "false"));
@@ -742,13 +746,34 @@ public class MemoryMessagesStore implements IMessagesStore {
int pullType = ProtoConstants.PullType.Pull_Normal;
if (type == ProtoConstants.ConversationType.ConversationType_Private) {
notifyReceivers.add(fromUser);
if(message.getToCount() > 0) {
if(message.getToList().contains(message.getConversation().getTarget())) {
notifyReceivers.add(message.getConversation().getTarget());
if(mRobotMentionExternalRobot && message.getConversation().getTarget().contains("|")) {
String[] ss = message.getConversation().getTarget().split("\\|");
notifyReceivers.add(ss[0]);
notifyReceivers.add(ss[1]);
if(!message.getToList().isEmpty()) {
notifyReceivers.addAll(message.getToList());
} else if(!StringUtil.isNullOrEmpty(message.getToUser())) {
notifyReceivers.add(message.getToUser());
}
} else {
notifyReceivers.add(message.getConversation().getTarget());
notifyReceivers.add(fromUser);
if (message.getToCount() > 0) {
if (message.getToList().contains(message.getConversation().getTarget())) {
notifyReceivers.add(message.getConversation().getTarget());
}
} else {
notifyReceivers.add(message.getConversation().getTarget());
}
}
if (mRobotMentionExternalRobot && message.getContent().getMentionedTargetCount() > 0) {
for (String mentioned : message.getContent().getMentionedTargetList()) {
if (!notifyReceivers.contains(mentioned)) {
WFCMessage.User user = getUserInfo(mentioned);
if(user != null && user.getType() == ProtoConstants.UserType.UserType_Robot) {
notifyReceivers.add(mentioned);
}
}
}
}
pullType = ProtoConstants.PullType.Pull_Normal;
} else if (type == ProtoConstants.ConversationType.ConversationType_Group) {
@@ -778,6 +803,16 @@ public class MemoryMessagesStore implements IMessagesStore {
}
}
}
if (mRobotMentionExternalRobot && message.getContent().getMentionedTargetCount() > 0) {
for (String mentioned : message.getContent().getMentionedTargetList()) {
if (!notifyReceivers.contains(mentioned)) {
WFCMessage.User user = getUserInfo(mentioned);
if(user != null && user.getType() == ProtoConstants.UserType.UserType_Robot) {
notifyReceivers.add(mentioned);
}
}
}
}
pullType = ProtoConstants.PullType.Pull_Normal;
} else if (type == ProtoConstants.ConversationType.ConversationType_ChatRoom) {
boolean isDirect = !StringUtil.isNullOrEmpty(message.getToUser()) || !message.getToList().isEmpty();
@@ -4891,6 +4926,11 @@ public class MemoryMessagesStore implements IMessagesStore {
return mRobotCallbackWithTargetInfo;
}
@Override
public boolean isRobotMentionExternalRobot() {
return mRobotMentionExternalRobot;
}
@Override
public boolean isChannelCallbackWithClientInfo() {
return mChannelCallbackWithClientInfo;
@@ -254,6 +254,7 @@ public interface IMessagesStore {
boolean isRobotCallbackWithClientInfo();
boolean isRobotCallbackWithSenderInfo();
boolean isRobotCallbackWithTargetInfo();
boolean isRobotMentionExternalRobot();
boolean isChannelCallbackWithClientInfo();
boolean isChannelCallbackWithSenderInfo();
@@ -10,6 +10,7 @@ package win.liyufan.im;
public interface IMTopic {
String SendMessageTopic = "MS";
String RobotReplyMessageTopic = "RRM";
String MultiCastMessageTopic = "MMC";
String RecallMessageTopic = "MR";
String RecallMultiCastMessageTopic = "MRMC";
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>wildfirechat-parent</artifactId>
<groupId>cn.wildfirechat</groupId>
<version>1.3.8</version>
<version>1.3.9</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -21,6 +21,7 @@ public interface APIPath {
String Get_Domain = "/admin/domain/get";
String Destroy_Domain = "/admin/domain/destroy";
String List_Domain = "/admin/domain/list";
String Ping_Domain = "/admin/domain/ping";
String Create_User = "/admin/user/create";
String Update_User = "/admin/user/update";
@@ -138,6 +139,7 @@ public interface APIPath {
String Robot_User_Info = "/robot/user_info";
String Robot_Get_Profile = "/robot/profile";
String Robot_Message_Send = "/robot/message/send";
String Robot_Message_Reply = "/robot/message/reply";
String Robot_Message_Recall = "/robot/message/recall";
String Robot_Message_Update = "/robot/message/update";
String Robot_Set_Callback = "/robot/set_callback";
@@ -0,0 +1,52 @@
/*
* This file is part of the Wildfire Chat package.
* (c) Heavyrain2012 <heavyrain.lee@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package cn.wildfirechat.pojos;
import cn.wildfirechat.proto.WFCMessage;
import io.netty.util.internal.StringUtil;
import java.util.List;
public class ReplyMessageData {
private long messageUid;
private MessagePayload payload;
private boolean only2Sender;
public long getMessageUid() {
return messageUid;
}
public void setMessageUid(long messageUid) {
this.messageUid = messageUid;
}
public MessagePayload getPayload() {
return payload;
}
public void setPayload(MessagePayload payload) {
this.payload = payload;
}
public boolean isOnly2Sender() {
return only2Sender;
}
public void setOnly2Sender(boolean only2Sender) {
this.only2Sender = only2Sender;
}
public static boolean isValide(ReplyMessageData sendMessageData) {
if(sendMessageData.messageUid <=0 ||
sendMessageData.getPayload() == null) {
return false;
}
return true;
}
}
@@ -0,0 +1,14 @@
/*
* This file is part of the Wildfire Chat package.
* (c) Heavyrain2012 <heavyrain.lee@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package cn.wildfirechat.pojos.mesh;
public class PojoDomainPingRequest {
public String domainId;
}
@@ -0,0 +1,16 @@
/*
* This file is part of the Wildfire Chat package.
* (c) Heavyrain2012 <heavyrain.lee@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package cn.wildfirechat.pojos.mesh;
public class PojoDomainPingResponse {
public boolean success;
public String errorMessage;
public String myDomainName;
}
+1 -1
View File
@@ -6,7 +6,7 @@
<!--<relativePath>../pom.xml</relativePath>-->
<artifactId>wildfirechat-parent</artifactId>
<groupId>cn.wildfirechat</groupId>
<version>1.3.8</version>
<version>1.3.9</version>
</parent>
<artifactId>distribution</artifactId>
@@ -167,6 +167,10 @@ robot.callback_with_sender_info false
## 机器人回调信息是否带上目标的信息,单聊时是对方用户信息,群聊时是群组信息,频道时是频道信息
robot.callback_with_target_info false
## 是否允许@会话外的机器人。如果为true,单聊或者群聊时,可以@不在会话中的机器人。当机器人收到消息后,可以回复消息。
## 如果为false,不能@不在会话中的机器人。机器人不在会话中时,也不能回复消息。
robot.mention_external_robot true
## 频道回调信息是否带上用户clientId和平台类型。
channel.callback_with_client_info false
+1 -1
View File
@@ -12,7 +12,7 @@
<artifactId>wildfirechat-parent</artifactId>
<packaging>pom</packaging>
<version>1.3.8</version>
<version>1.3.9</version>
<name>Wildfire Chat</name>
<description>Wildfire Chat Server</description>
<inceptionYear>2019</inceptionYear>
+7
View File
@@ -12,6 +12,13 @@
11. *** 1.3.8版本添加了server api发送消息的限制,限制消息体最大内容不能超过64KB,如果升级请注意业务系统发送消息大小。***
# 更新记录
--------------
Release note 1.3.9:
1. 解决server sdk反复初始化内存泄漏的问题。
2. 群组支持用户@不在群组中的机器人。
3. 单聊会话支持@机器人。
4. 机器人支持回复消息,可以回复单聊或者群聊消息。
--------------
Release note 1.3.8:
1. 添加限制,server api发送消息,限制消息体不能大于64KB。
+1 -1
View File
@@ -3,7 +3,7 @@
<parent>
<artifactId>wildfirechat-parent</artifactId>
<groupId>cn.wildfirechat</groupId>
<version>1.3.8</version>
<version>1.3.9</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -9,12 +9,14 @@ import cn.wildfirechat.sdk.utilities.ChannelHttpUtils;
import com.google.gson.Gson;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.Closeable;
import java.io.IOException;
import java.util.List;
import static cn.wildfirechat.proto.ProtoConstants.ApplicationType.ApplicationType_Channel;
//仅专业版支持,社区版不支持
public class ChannelServiceApi {
public class ChannelServiceApi implements Closeable {
private final ChannelHttpUtils channelHttpUtils;
public ChannelServiceApi(String imurl, String channelId, String secret) {
@@ -66,7 +68,6 @@ public class ChannelServiceApi {
return channelHttpUtils.httpJsonPost(path, messageData, SendMessageResult.class);
}
//仅专业版支持
public IMResult<String> recallMessage(long messageUid) throws Exception {
String path = APIPath.Channel_Msg_Recall;
RecallMessageData messageData = new RecallMessageData();
@@ -74,7 +75,6 @@ public class ChannelServiceApi {
return channelHttpUtils.httpJsonPost(path, messageData, String.class);
}
//仅专业版支持
public IMResult<Void> republishMessage(long messageUid, List<String> targets) throws Exception {
String path = APIPath.Channel_Msg_Republish;
RepublishChannelMessageData messageData = new RepublishChannelMessageData();
@@ -131,4 +131,8 @@ public class ChannelServiceApi {
return configData;
}
@Override
public void close() throws IOException {
channelHttpUtils.close();
}
}
@@ -21,7 +21,7 @@ import static cn.wildfirechat.proto.ProtoConstants.ChannelState.*;
import static cn.wildfirechat.proto.ProtoConstants.SystemSettingType.Group_Max_Member_Count;
public class Main {
private static boolean commercialServer = false;
private static boolean commercialServer = true;
private static boolean advanceVoip = false;
private static boolean robotMomentsEnabled = false;
private static boolean momentsEnabled = false;
@@ -1413,6 +1413,7 @@ public class Main {
System.exit(-1);
}
//使用完需要释放
RobotService robotService = new RobotService(IMUrl, robotId, robotSecret);
//***********************************************
@@ -1812,6 +1813,9 @@ public class Main {
System.exit(-1);
}
}
//使用完需要释放
robotService.close();
}
//***测试频道API功能,仅专业版支持***
@@ -1882,7 +1886,7 @@ public class Main {
}
//2. 初始化api,注意端口是80,不是18080
//2. 初始化api,注意端口是80,不是18080 //使用完需要释放
ChannelServiceApi channelServiceApi = new ChannelServiceApi(IMUrl, channelId, secret);
@@ -2038,6 +2042,9 @@ public class Main {
}
OutputApplicationConfigData config = channelServiceApi.getApplicationSignature();
System.out.println(config);
//使用完需要释放
channelServiceApi.close();
}
static void testSensitiveApi() throws Exception {
List<String> words = Arrays.asList("a","b","c");
@@ -227,4 +227,10 @@ public class MeshAdmin {
return AdminHttpUtils.httpJsonPost(path, event, Void.class);
}
public static IMResult<PojoDomainPingResponse> pingDomain(String domainId) throws Exception {
String path = APIPath.Ping_Domain;
PojoDomainPingRequest request = new PojoDomainPingRequest();
request.domainId = domainId;
return AdminHttpUtils.httpJsonPost(path, request, PojoDomainPingResponse.class);
}
}
@@ -8,11 +8,13 @@ import cn.wildfirechat.sdk.model.IMResult;
import cn.wildfirechat.sdk.utilities.RobotHttpUtils;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.Closeable;
import java.io.IOException;
import java.util.List;
import static cn.wildfirechat.proto.ProtoConstants.ApplicationType.ApplicationType_Robot;
public class RobotService {
public class RobotService implements Closeable {
private final RobotHttpUtils robotHttpUtils;
public RobotService(String url, String robotId, String robotSecret) {
@@ -37,6 +39,15 @@ public class RobotService {
return robotHttpUtils.httpJsonPost(path, messageData, SendMessageResult.class);
}
public IMResult<SendMessageResult> replyMessage(long messageUid, MessagePayload payload, boolean only2Sender) throws Exception {
String path = APIPath.Robot_Message_Reply;
ReplyMessageData messageData = new ReplyMessageData();
messageData.setMessageUid(messageUid);
messageData.setOnly2Sender(only2Sender);
messageData.setPayload(payload);
return robotHttpUtils.httpJsonPost(path, messageData, SendMessageResult.class);
}
public IMResult<String> recallMessage(long messageUid) throws Exception {
String path = APIPath.Robot_Message_Recall;
RecallMessageData messageData = new RecallMessageData();
@@ -423,4 +434,9 @@ public class RobotService {
requestPojo.rl = removeList;
return robotHttpUtils.httpJsonPost(path, requestPojo, Void.class);
}
@Override
public void close() throws IOException {
robotHttpUtils.close();
}
}
@@ -41,28 +41,30 @@ public class AdminHttpUtils extends JsonUtils {
init(url, secret, 15000);
}
public static void init(String url, String secret, int timeout) {
public static synchronized void init(String url, String secret, int timeout) {
adminUrl = url.trim();
adminSecret = secret.trim();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setValidateAfterInactivity(1000);
int connectTimeout = 15000; // 连接超时时间
int connectionRequestTimeout = 3000; // 从连接池获取连接的超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setSocketTimeout(timeout)
.setConnectionRequestTimeout(connectionRequestTimeout)
.build();
if(httpClient == null) {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setValidateAfterInactivity(1000);
int connectTimeout = 15000; // 连接超时时间
int connectionRequestTimeout = 3000; // 从连接池获取连接的超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setSocketTimeout(timeout)
.setConnectionRequestTimeout(connectionRequestTimeout)
.build();
httpClient = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(cm)
.evictExpiredConnections()
.evictIdleConnections(60L, TimeUnit.SECONDS)
.setRetryHandler(DefaultHttpRequestRetryHandler.INSTANCE)
.setMaxConnTotal(100)
.setMaxConnPerRoute(50)
.build();
httpClient = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(cm)
.evictExpiredConnections()
.evictIdleConnections(60L, TimeUnit.SECONDS)
.setRetryHandler(DefaultHttpRequestRetryHandler.INSTANCE)
.setMaxConnTotal(100)
.setMaxConnPerRoute(50)
.build();
}
}
public static <T> IMResult<T> httpGet(String path, Class<T> clazz) throws Exception {
@@ -20,6 +20,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
@@ -28,7 +30,7 @@ import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
public class ChannelHttpUtils extends JsonUtils {
public class ChannelHttpUtils extends JsonUtils implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(ChannelHttpUtils.class);
public static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
@@ -40,7 +42,7 @@ public class ChannelHttpUtils extends JsonUtils {
private final int port;
private void checkPort() {
if (port != 80 && port != 443) {
if (port != 80 && port != 443 && port != -1) {
if (port == 18080) {
LOG.warn("您传入的频道API地址中的端口是18080,18080端口默认为管理API端口,频道API端口应该为IM服务的HTTP端口,默认为80,请确认是否使用错误!");
} else {
@@ -54,8 +56,12 @@ public class ChannelHttpUtils extends JsonUtils {
this.channelId = channelId.trim();
this.channelSecret = secret.trim();
try {
URL url = new URL(this.imurl);
this.port = url.getPort();
URL u = new URL(this.imurl);
int port = u.getPort();
if(port == -1) {
port = u.getDefaultPort();
}
this.port = port;
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
@@ -156,4 +162,9 @@ public class ChannelHttpUtils extends JsonUtils {
public String getChannelSecret() {
return channelSecret;
}
@Override
public void close() throws IOException {
httpClient.close();
}
}
@@ -3,29 +3,35 @@ package cn.wildfirechat.sdk.utilities;
import cn.wildfirechat.sdk.model.IMResult;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import ikidou.reflect.TypeBuilder;
import io.netty.util.internal.StringUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
public class RobotHttpUtils extends JsonUtils {
public class RobotHttpUtils extends JsonUtils implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(RobotHttpUtils.class);
public static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
@@ -37,7 +43,7 @@ public class RobotHttpUtils extends JsonUtils {
private final int port;
private void checkPort() {
if (port != 80 && port != 443) {
if (port != 80 && port != 443 && port != -1) {
if (port == 18080) {
LOG.warn("您传入的机器人API地址中的端口是18080,18080端口默认为管理API端口,机器人API端口应该为IM服务的HTTP端口,默认为80,请确认是否使用错误!");
} else {
@@ -52,7 +58,11 @@ public class RobotHttpUtils extends JsonUtils {
this.robotSecret = robotSecret.trim();
try {
URL u = new URL(this.url);
this.port = u.getPort();
int port = u.getPort();
if(port == -1) {
port = u.getDefaultPort();
}
this.port = port;
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
@@ -78,6 +88,7 @@ public class RobotHttpUtils extends JsonUtils {
.build();
}
public <T> IMResult<T> httpJsonPost(String path, Object object, Class<T> clazz) throws Exception{
if (isNullOrEmpty(url) || isNullOrEmpty(path)) {
LOG.error("Not init IM SDK correctly. Do you forget init it?");
@@ -154,4 +165,9 @@ public class RobotHttpUtils extends JsonUtils {
public String getRobotSecret() {
return robotSecret;
}
@Override
public void close() throws IOException {
httpClient.close();
}
}