Compare commits

..
56 Commits
Author SHA1 Message Date
heavyrian2012 6a806aa10b fix build error 2023-03-10 11:02:52 +08:00
heavyrian2012 6542b8ba55 version and release note 2023-03-10 10:55:32 +08:00
heavyrian2012 c3bc62f1e1 单聊会话发送定向消息时,分发目标需要包括自己。 2023-03-10 10:48:39 +08:00
heavyrian2012 8b649200d2 添加检查会议是否存在的接口 2023-03-06 15:17:46 +08:00
heavyrian2012 5f95b18e77 release note 2023-03-06 12:25:11 +08:00
imndx 4d45aedc73 禁止客户端群操作flag 解析错误 2023-03-06 11:41:23 +08:00
heavyrian2012 a038bedb12 version and release note 2023-03-06 10:54:26 +08:00
heavyrian2012 43892dbe41 解决关闭roaming,且message.compensate_time_limit配置为-1时,首次消息无法同步的问题 2023-03-02 08:52:43 +08:00
heavyrian2012 ad33abc424 用户消息表中的target优化 2023-02-28 21:01:20 +08:00
heavyrian2012 290a3cea0e 支持单聊会话的定向消息 2023-02-28 20:45:41 +08:00
imndx ca3bbb6435 添加日志 2023-02-23 10:41:11 +08:00
heavyrian2012 704e6e0ec2 搜索用户时,过滤掉被删除的用户 2023-02-20 19:30:08 +08:00
heavyrian2012 23871487e4 当用户获取群组信息时,如果不在群中返回-1,如果已经离开群了返回离开时间的负数 2023-02-20 19:27:30 +08:00
heavyrian2012 6e1ba9440e 更新版本号和release note 2023-02-15 15:25:33 +08:00
heavyrian2012 c284272b06 文件存储路径中加上分钟和秒 2023-02-15 15:20:57 +08:00
heavyrian2012 6746a54659 优化内置存储功能 2023-02-14 21:35:58 +08:00
heavyrian2012 93be667e17 日志文件精确到分钟,避免出现问题时被复写 2023-02-14 08:45:34 +08:00
heavyrian2012 f11da6225d 添加修改频道菜单接口 2023-02-12 11:06:35 +08:00
heavyrian2012 e28a4c6cbf server api发送消息检查对象是否存在 2023-02-11 13:51:05 +08:00
heavyrian2012 fa8a2bef32 channel api添加检查是否是订阅者的接口 2023-02-08 11:13:32 +08:00
heavyrian2012 1c9d238734 update readme 2023-01-19 16:14:17 +08:00
heavyrian2012 2f7f4e6456 update readme 2023-01-10 11:57:35 +08:00
heavyrian2012 6e83ec85c7 server sdk http request add log 2023-01-04 09:20:12 +08:00
heavyrian2012 cc561b846e 更新版本号和release note 2022-12-28 08:49:40 +08:00
heavyrian2012 4628b3b0b6 sdk add conference rtp forward api 2022-12-22 11:53:38 +08:00
heavyrian2012 9c69fbc7d4 sdk add conference rtp forward api 2022-12-13 17:38:21 +08:00
heavyrian2012 9047020d69 添加停止命令 2022-12-12 12:37:31 +08:00
heavyrian2012 1c18d862a1 会议离开加上原因 2022-12-07 16:25:18 +08:00
heavyrian2012 b0ddca985a route时可能不能携带正确的推送类型 2022-12-06 14:35:16 +08:00
heavyrian2012 996e06c451 添加禁止客户端群操作配置 2022-11-26 22:21:43 +08:00
imndx 612747203a 创建群组时,支持组织群 2022-11-25 10:48:29 +08:00
heavyrian2012 f7853ae299 解决短连接端口被扫描时打印出异常日志的问题 2022-11-24 19:06:27 +08:00
heavyrian2012 7443db3078 检查工具添加help命令 2022-11-22 10:12:09 +08:00
heavyrian2012 ad5f6cb228 添加注释 2022-11-21 08:34:08 +08:00
heavyrian2012 1486b19ce1 更新版本和release note 2022-11-19 09:44:09 +08:00
heavyrian2012 3e1095f745 移动release note文件的位置 2022-11-19 09:38:26 +08:00
heavyrian2012 17039bd3c1 http请求错误时不打印数据内容,防止内容泄露 2022-11-19 09:31:22 +08:00
heavyrian2012 b5d8feab62 客户端连接时检查是否跟获取token的平台一致 2022-11-18 22:10:53 +08:00
heavyrian2012 95b08ff7a3 Revert "mqtt proto version error"
This reverts commit ab8ae9d0c9.
2022-11-18 21:55:49 +08:00
heavyrian2012 ab8ae9d0c9 mqtt proto version error 2022-11-18 21:27:18 +08:00
heavyrian2012 b4d163e144 添加android客户端签名验证功能 2022-11-18 16:01:17 +08:00
heavyrian2012 3ccfd9a29b 解决user setting并发问题,fix #566 2022-11-15 17:12:51 +08:00
heavyrian2012 90504d1305 打包dockerfile 2022-11-14 15:47:42 +08:00
heavyrian2012 88199189a2 当禁止陌生人聊天时,添加例外允许用户id,用于比如管理员、文件助手等场景 2022-11-14 15:23:03 +08:00
heavyrian2012 0b6612eacc 内置对象存储支持绝对路径和相对路径 2022-11-14 15:13:06 +08:00
heavyrian2012 d706f545d2 解决启动脚本中的小错误 2022-11-14 15:04:51 +08:00
heavyrian2012 ae8d63b162 update docker readme 2022-11-14 14:42:04 +08:00
heavyrian2012 77e742e812 添加server sdk检查server api的工具 2022-11-12 19:25:24 +08:00
heavyrian2012 b2ee8b8d94 linux安装包创建日志目录 2022-11-12 19:24:57 +08:00
heavyrian2012 7080d85605 只有server api才能创建组织群 2022-11-12 15:01:57 +08:00
heavyrian2012 1275b2109f fix build error 2022-11-12 14:18:26 +08:00
heavyrian2012 b2eab28cb9 组织群客户端不能自主退出 2022-11-12 14:17:15 +08:00
heavyrian2012 67234ceaa6 添加新的群组类型:组织群 2022-11-12 14:00:24 +08:00
heavyrian2012 45f9e20e97 支持转发消息include/exclude类型,支持配置消息区间 2022-11-12 12:51:25 +08:00
heavyrian2012 6b7edc713a API获取用户信息时,过滤掉被删除的用户 2022-11-09 10:36:52 +08:00
heavyrian2012 1ef8f94d67 忽略掉无效的请求和日志 2022-11-05 17:05:31 +08:00
62 changed files with 886 additions and 136 deletions
+2 -1
View File
@@ -39,6 +39,7 @@
| [open-platform](https://github.com/wildfirechat/open-platform) | [open-platform](https://gitee.com/wfchat/open-platform) | 野火开放平台服务。 |
| [daily-report](https://github.com/wildfirechat/daily-report) | [daily-report](https://github.com/wildfirechat/daily-report) | 野火开放平台日报 demo服务。 |
| [channel-platform](https://github.com/wildfirechat/channel-platform) | [channel-platform](https://gitee.com/wfchat/channel-platform) | 野火频道(公众号)平台服务。 |
| [organization-platform](https://github.com/wildfirechat/organization-platform) | [organization-platform](https://gitee.com/wfchat/organization-platform) | 野火组织通讯录服务。 |
| [android-chat](https://github.com/wildfirechat/android-chat) | [android-chat](https://gitee.com/wfchat/android-chat) | 野火IM Android SDK源码和App源码。 |
| [ios-chat](https://github.com/wildfirechat/ios-chat) | [ios-chat](https://gitee.com/wfchat/ios-chat) | 野火IM iOS SDK源码和App源码。|
| [pc-chat](https://github.com/wildfirechat/vue-pc-chat) | [pc-chat](https://gitee.com/wfchat/vue-pc-chat) | 基于[Electron](https://electronjs.org/)的PC 端,支持Windows、Mac、Linux(包括国产化linux系统和CPU)。 |
@@ -46,7 +47,7 @@
| [wx-chat](https://github.com/wildfirechat/wx-chat) | [wx-chat](https://gitee.com/wfchat/wx-chat) | 小程序平台的Demo(支持微信、百度、阿里、字节、QQ 等小程序平台)。 |
| [uni-chat](https://github.com/wildfirechat/uni-chat) | [uni-chat](https://gitee.com/wfchat/uni-chat) | UniApp平台移动端应用(使用原生插件)。 |
| [uni-wfc-client](https://github.com/wildfirechat/uni-wfc-client) | [uni-wfc-client](https://gitee.com/wfchat/uni-wfc-client) | UniApp平台原生插件。已[商店](https://ext.dcloud.net.cn/plugin?id=7895)上架 |
| [flutter_imclient](https://github.com/wildfirechat/flutter_imclient) | [flutter_imclient](https://gitee.com/wfchat/flutter_imclient) | Flutter平台原生插件。 |
| [wfc_flutter_plugins](https://github.com/wildfirechat/wfc_flutter_plugins) | [flutter_imclient](https://gitee.com/wfchat/wfc_flutter_plugins) | Flutter平台原生插件,支持IM和音视频通话。 |
| [docs](https://github.com/wildfirechat/docs) | [docs](https://gitee.com/wfchat/docs) | 野火IM相关文档,包含设计、概念、开发、使用说明,[在线查看](https://docs.wildfirechat.cn/)。 |
## 野火开发文档
+19 -3
View File
@@ -59,6 +59,12 @@ token.key testim
##token的过期时间,单位为毫秒,默认为无限期。如果需要设置无限期,客户端上一定需要加上token过期的处理。token过期的处理请参考文档的常见问题
##token.expire_time 2592000000
##客户端(目前只有android)的应用签名(一个应用最取第一个签名),如果有多个签名(多个客户端),用英文逗号分开。获取签名方法请参考文档:https://docs.wildfirechat.cn/blogs/签名验证.html
#connect.client_signature_list eNkezQ1g9OsnhfLSFUY1vzKDzhs=,xykezQ1g9OsnhfLSFUY1vzKDzhs=
##是否拒绝空签名的android客户端, 默认为true。当有旧的客户端需要兼容时改成false,当所有都是新客户端时,改成true。
#connect.reject_empty_signature true
##首次登录,是否接收之前的历史消息。
##0 不接收历史消息,只接收${message.compensate_time_limit}毫秒以内的消息,由于服务器没有保存已经收取记录,所以如果有超过${message.compensate_time_limit}毫秒之前未收取的消息也不会收取下拉;
##1接收,会接收 message.max_queue 配置的条数的历史消息
@@ -79,6 +85,9 @@ message.chatroom_remote_history_message 1
##是否禁止陌生人聊天
message.disable_stranger_chat false
##当禁止陌生人聊天时,允许聊天的用户id,比如管理员或者文件传输助手等。用户id以英文逗号分割。
message.allow_stranger_chat_list admin,FireRobot,wfc_file_transfer
##黑名单策略,0 发送失败,返回被拉黑的错误码;1 发送成功但消息被服务器直接丢弃
message.blacklist.strategy 0
@@ -161,6 +170,10 @@ group.allow_robot_custom_operation_notification true
## 0 不发送,1 退群时发送,2 踢人时发送,3 退群和踢人时都发送。
group.visible_quit_or_kickoff_notification 0
## 禁止客户端群操作。第1位是禁止创建群组,第2位是禁止销毁群组,3位禁止加入群,4位禁止退出群,5位禁止邀请群成员,6位禁止移出群成员,7位禁止转移群,8位禁止设置群管理员,9位禁止白名单处理,10位禁止群禁言,11位禁止修改群组信息,12位禁止群成员禁言。
## Server API不受此限制。
#group.forbidden_client_operation 0xFFF
## 隐藏用户信息属性类型,2是性别,3是电话号码,4是邮箱,5是地址,6是公司信息,7是社交账号,8是Extra信息。当需要隐藏多个时以英文逗号分开;
## 本配置是为了提高安全性,避免把对应信息同步到客户端,这样就能防止程序被破解从而拿到用户关键信息。仅对客户端有效,server api不受影响。
## 注意,修改本配置不会对已经同步的信息产生影响。
@@ -293,14 +306,17 @@ push.ios.server.address http://localhost:8085/ios/push
##消息转发地址
##注意回调是单线程回调,接收服务必须在同一内网,且异步处理快速返回,否则会有延迟问题!!
#message.forward.url http://localhost:8888/im_event/message
##需要转发的消息类型,当有多个时以英文逗号分割。如果转发所有消息,请注释掉配置或者设置为空
#message.forward.types 1,2,3
##需要转发的消息类型,当有多个时以英文逗号分割,可以用-来指定区间,注意区间不能太大,因为要把区间内的所有数字都放入到Set中。如果转发所有消息,请注释掉配置或者设置为空
#message.forward.types 1,2,3,5-10
##需要转发的消息类型,当有多个时以英文逗号分割,可以用-来指定区间,注意区间不能太大,因为要把区间内的所有数字都放入到Set中。
#message.forward.exclude_types 1,2,3,5-10
##敏感消息转发地址
##注意回调是单线程回调,接收服务必须在同一内网,且异步处理快速返回,否则会有延迟问题!!
#message.sensitive.forward.url http://localhost:8888/im_event/message
##提醒消息转发地址,@全体用户和@某个用户消息会回调此地址。此转发不受${message.forward.types}限制。
##提醒消息转发地址,@全体用户和@某个用户消息会回调此地址。
##此转发不受${message.forward.types}和${message.forward.exclude_types}限制。
##注意回调是单线程回调,接收服务必须在同一内网,且异步处理快速返回,否则会有延迟问题!!
#message.mentionmsg.forward.url http://localhost:8888/im_event/message
+1 -1
View File
@@ -5,7 +5,7 @@
<relativePath>../</relativePath>
<artifactId>wildfirechat-parent</artifactId>
<groupId>cn.wildfirechat</groupId>
<version>0.98</version>
<version>1.1.2</version>
</parent>
<artifactId>moquette-broker</artifactId>
@@ -90,6 +90,8 @@ public class FileAction extends Action {
}
response.setContent(file);
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
return true;
}
@@ -187,6 +187,10 @@ public class UploadFileAction extends Action {
return false;
}
if(remoteFileName != null && remoteFileName.length() > 2 && remoteFileName.startsWith("'") && remoteFileName.endsWith("'")) {
remoteFileName = remoteFileName.substring(1, remoteFileName.length()-1);
}
if (StringUtil.isNullOrEmpty(remoteFileName)) {
logger.warn("remoteFileName is empty!");
@@ -235,12 +239,17 @@ public class UploadFileAction extends Action {
int offset = 0; // 断点续传开始位置
Date nowTime=new Date();
SimpleDateFormat time=new SimpleDateFormat("yyyy/MM/dd/HH");
SimpleDateFormat time=new SimpleDateFormat("yyyy/MM/dd/HH/mm/ss");
String datePath = time.format(nowTime);
datePath = "fs/" + bucket[0] + "/" + datePath; //add bucket
String dir = "./" + MediaServerConfig.FILE_STROAGE_ROOT + "/" + datePath;
String dir;
if(MediaServerConfig.FILE_STROAGE_ROOT.startsWith("/") || MediaServerConfig.FILE_STROAGE_ROOT.startsWith("~/") || MediaServerConfig.FILE_STROAGE_ROOT.startsWith("./")) {
dir = MediaServerConfig.FILE_STROAGE_ROOT + "/" + datePath;
} else {
dir = "./" + MediaServerConfig.FILE_STROAGE_ROOT + "/" + datePath;
}
File dirFile = new File(dir);
boolean bFile = dirFile.exists();
@@ -248,6 +257,7 @@ public class UploadFileAction extends Action {
if(!bFile) {
bFile = dirFile.mkdirs();
if (!bFile) {
logger.error("create dirs error! {}", dir);
response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
response.setContent("服务器错误:无法创建文件");
return false;
@@ -49,7 +49,7 @@ public class GetUserAction extends AdminAction {
}
RestResult result;
if (user == null) {
if (user == null || user.getDeleted() > 0) {
result = RestResult.resultOf(ErrorCode.ERROR_CODE_NOT_EXIST);
} else {
result = RestResult.ok(InputOutputUserInfo.fromPbUser(user));
@@ -0,0 +1,37 @@
/*
* 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.channel;
import cn.wildfirechat.common.APIPath;
import cn.wildfirechat.pojos.InputChannelSubscribe;
import cn.wildfirechat.pojos.InputUserId;
import cn.wildfirechat.pojos.OutputStringList;
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.handler.codec.http.FullHttpRequest;
import java.util.ArrayList;
@Route(APIPath.Channel_Is_Subscriber)
@HttpMethod("POST")
public class GetIsChannelSubscriberAction extends ChannelAction {
@Override
public boolean action(Request request, Response response) {
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputUserId input = getRequestBody(request.getNettyRequest(), InputUserId.class);
boolean isSubscriber = messagesStore.checkUserInChannel(input.getUserId(), channelInfo.getTargetId());
setResponseContent(RestResult.ok(isSubscriber), response);
}
return true;
}
}
@@ -44,7 +44,7 @@ public class GetUserAction extends ChannelAction {
RestResult result;
if (user == null || StringUtil.isNullOrEmpty(user.getName())) {
if (user == null || StringUtil.isNullOrEmpty(user.getName()) || user.getDeleted() > 0) {
result = RestResult.resultOf(ErrorCode.ERROR_CODE_NOT_EXIST);
} else {
if (channelInfo.getOwner().equals(inputUserId.getUserId()) ||
@@ -44,7 +44,7 @@ public class GetUserAction extends RobotAction {
}
RestResult result;
if (user == null) {
if (user == null || user.getDeleted() > 0) {
result = RestResult.resultOf(ErrorCode.ERROR_CODE_NOT_EXIST);
} else {
result = RestResult.ok(InputOutputUserInfo.fromPbUser(user));
@@ -15,6 +15,7 @@ import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.internal.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import win.liyufan.im.Utility;
@@ -34,7 +35,6 @@ abstract public class ActionHandler extends SimpleChannelInboundHandler<FullHttp
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) throws Exception {
Logger.info("Http request whit url {}", fullHttpRequest.uri());
final Request request = Request.build(ctx, fullHttpRequest);
final Response response = Response.build(ctx, request);
@@ -109,7 +109,7 @@ abstract public class ActionHandler extends SimpleChannelInboundHandler<FullHttp
* @param response 响应对象
*/
private void doAction(ChannelHandlerContext ctx, Request request, Response response){
if(("/route".equalsIgnoreCase(request.getPath()) || request.getPath().startsWith("/fs/"))
if(("/route".equalsIgnoreCase(request.getPath()) || (!StringUtil.isNullOrEmpty(request.getPath()) && request.getPath().startsWith("/fs/")))
&& "OPTIONS".equalsIgnoreCase(request.getMethod())){
handleOptions(ctx, request, response);
return;
@@ -124,6 +124,9 @@ abstract public class ActionHandler extends SimpleChannelInboundHandler<FullHttp
Action action;
if (isValidePath(request.getPath())) {
action = ServerSetting.getAction(request.getPath(), request.getMethod().toUpperCase());
if (action != null) {
Logger.info("Http request whit url {}", request.getPath());
}
} else {
action = ServerSetting.getErrorAction(ServerSetting.MAPPING_ERROR);
}
@@ -137,7 +140,11 @@ abstract public class ActionHandler extends SimpleChannelInboundHandler<FullHttp
action = ServerSetting.getAction(ServerSetting.MAPPING_ALL, request.getMethod());
if(null == action){
// 非Action方法,调用静态文件读取
action = Singleton.get(FileAction.class);
if(request.getPath().startsWith("/fs")) {
action = Singleton.get(FileAction.class);
} else {
action = ServerSetting.getErrorAction(ServerSetting.MAPPING_ERROR);
}
}
}
action.ctx = ctx;
@@ -110,6 +110,9 @@ public final class BrokerConstants {
public static final String TOKEN_SECRET_KEY = "token.key";
public static final String TOKEN_EXPIRE_TIME = "token.expire_time";
public static final String CONNECT_CLIENT_SIGNATURE_LIST = "connect.client_signature_list";
public static final String CONNECT_REJECT_EMPTY_SIGNATURE = "connect.reject_empty_signature";
public static final String EMBED_DB_PROPERTY_NAME = "embed.db";
public static final String DB_AUTO_CLEAN_HISTORY_MESSAGES = "db.auto_clean_history_messages";
public static final String H2DB_PATH = "h2db.path";
@@ -124,6 +127,7 @@ public final class BrokerConstants {
public static final String MESSAGE_Forward_Url = "message.forward.url";
public static final String MESSAGE_Sensitive_Forward_Url = "message.sensitive.forward.url";
public static final String MESSAGE_Forward_Types = "message.forward.types";
public static final String MESSAGE_Forward_Exclude_Types = "message.forward.exclude_types";
public static final String MESSAGE_MentionMsg_Forward_Url = "message.mentionmsg.forward.url";
@@ -141,6 +145,7 @@ public final class BrokerConstants {
public static final String MESSAGE_Max_Queue = "message.max_queue";
public static final String MESSAGE_Disable_Stranger_Chat = "message.disable_stranger_chat";
public static final String MESSAGE_Allow_Stranger_Chat_List = "message.allow_stranger_chat_list";
public static final String MESSAGE_Blacklist_Strategy = "message.blacklist.strategy";
@@ -166,6 +171,7 @@ public final class BrokerConstants {
public static final String GROUP_Allow_Robot_Custom_Operation_Notification = "group.allow_robot_custom_operation_notificatio";
public static final String GROUP_Visible_Quit_Kickoff_Notification = "group.visible_quit_or_kickoff_notification";
public static final String GROUP_Forbidden_Client_Operation = "group.forbidden_client_operation";
public static final String USER_HIDE_PROPERTIES = "user.hide_properties";
public static final String USER_KEEP_DISPLAY_NAME_WHEN_DESTROY = "user.keep_display_name_when_destroy";
@@ -24,6 +24,20 @@ public class AddGroupMember extends GroupHandler<WFCMessage.AddGroupMemberReques
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.AddGroupMemberRequest request, Qos1PublishHandler.IMCallback callback) {
boolean isAdmin = requestSourceType == ProtoConstants.RequestSourceType.Request_From_Admin;
if(requestSourceType == ProtoConstants.RequestSourceType.Request_From_User) {
int forbiddenClientOperation = m_messagesStore.getGroupForbiddenClientOperation();
if(request.getAddedMemberList().size() == 1 && request.getAddedMember(0).getMemberId().equals(fromUser)) {
if ((forbiddenClientOperation & ProtoConstants.ForbiddenClientGroupOperationMask.Forbidden_Join_Group) > 0) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
} else {
if ((forbiddenClientOperation & ProtoConstants.ForbiddenClientGroupOperationMask.Forbidden_Invite_Group_Member) > 0) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
}
}
ErrorCode errorCode = m_messagesStore.addGroupMembers(fromUser, isAdmin, request.getGroupId(), request.getAddedMemberList(), request.getExtra());
if (errorCode == ERROR_CODE_SUCCESS) {
if (request.hasNotifyContent() && request.getNotifyContent().getType() > 0) {
@@ -21,7 +21,7 @@ import win.liyufan.im.IMTopic;
public class CreateGroupHandler extends GroupHandler<WFCMessage.CreateGroupRequest> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.CreateGroupRequest request, Qos1PublishHandler.IMCallback callback) {
if(request.getGroup().getGroupInfo().getType() < 0 || request.getGroup().getGroupInfo().getType() > 2) {
if(request.getGroup().getGroupInfo().getType() < 0 || request.getGroup().getGroupInfo().getType() > 3) {
return ErrorCode.ERROR_CODE_INVALID_DATA;
}
@@ -40,6 +40,16 @@ public class CreateGroupHandler extends GroupHandler<WFCMessage.CreateGroupReque
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(!isAdmin && request.getGroup().getGroupInfo().getType() == ProtoConstants.GroupType.GroupType_Organization) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(requestSourceType == ProtoConstants.RequestSourceType.Request_From_User) {
int forbiddenClientOperation = m_messagesStore.getGroupForbiddenClientOperation();
if((forbiddenClientOperation & ProtoConstants.ForbiddenClientGroupOperationMask.Forbidden_Create_Group) > 0) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
}
WFCMessage.GroupInfo groupInfo = m_messagesStore.createGroup(fromUser, request.getGroup().getGroupInfo(), request.getGroup().getMembersList(), request.getMemberExtra(), isAdmin);
if (groupInfo != null) {
if(request.hasNotifyContent() && request.getNotifyContent().getType() > 0) {
@@ -26,7 +26,6 @@ public class DismissGroupHandler extends GroupHandler<WFCMessage.DismissGroupReq
ErrorCode errorCode;
if (groupInfo == null) {
errorCode = m_messagesStore.dismissGroup(fromUser, request.getGroupId(), isAdmin);
} else if (isAdmin || (groupInfo.getType() == ProtoConstants.GroupType.GroupType_Normal || groupInfo.getType() == ProtoConstants.GroupType.GroupType_Restricted)
&& groupInfo.getOwner() != null && groupInfo.getOwner().equals(fromUser)) {
@@ -38,6 +37,13 @@ public class DismissGroupHandler extends GroupHandler<WFCMessage.DismissGroupReq
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(requestSourceType == ProtoConstants.RequestSourceType.Request_From_User) {
int forbiddenClientOperation = m_messagesStore.getGroupForbiddenClientOperation();
if((forbiddenClientOperation & ProtoConstants.ForbiddenClientGroupOperationMask.Forbidden_Dismiss_Group) > 0) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
}
//send notify message first, then dismiss group
if (request.hasNotifyContent() && request.getNotifyContent().getType() > 0) {
sendGroupNotification(fromUser, groupInfo.getTargetId(), request.getToLineList(), request.getNotifyContent());
@@ -21,7 +21,7 @@ import java.util.List;
public class GetGroupInfoHandler extends IMHandler<WFCMessage.PullUserRequest> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.PullUserRequest request, Qos1PublishHandler.IMCallback callback) {
List<WFCMessage.GroupInfo> infos = m_messagesStore.getGroupInfos(request.getRequestList());
List<WFCMessage.GroupInfo> infos = m_messagesStore.getGroupInfos(request.getRequestList(), fromUser, requestSourceType == ProtoConstants.RequestSourceType.Request_From_Admin);
WFCMessage.PullGroupInfoResult result = WFCMessage.PullGroupInfoResult.newBuilder().addAllInfo(infos).build();
byte[] data = result.toByteArray();
@@ -29,6 +29,10 @@ public class KickoffGroupMember extends GroupHandler<WFCMessage.RemoveGroupMembe
errorCode = ErrorCode.ERROR_CODE_NOT_EXIST;
} else {
boolean isAdmin = requestSourceType == ProtoConstants.RequestSourceType.Request_From_Admin;
if (!isAdmin && groupInfo.getType() == ProtoConstants.GroupType.GroupType_Organization) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
boolean isAllow = isAdmin;
if (!isAllow) {
if (groupInfo.getOwner() != null) {
@@ -58,6 +62,13 @@ public class KickoffGroupMember extends GroupHandler<WFCMessage.RemoveGroupMembe
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(requestSourceType == ProtoConstants.RequestSourceType.Request_From_User) {
int forbiddenClientOperation = m_messagesStore.getGroupForbiddenClientOperation();
if((forbiddenClientOperation & ProtoConstants.ForbiddenClientGroupOperationMask.Forbidden_Kickoff_Group_Member) > 0) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
}
//send notify message first, then kickoff the member
if (request.hasNotifyContent() && request.getNotifyContent().getType() > 0) {
sendGroupNotification(fromUser, groupInfo.getTargetId(), request.getToLineList(), request.getNotifyContent());
@@ -31,6 +31,19 @@ public class ModifyGroupInfoHandler extends GroupHandler<WFCMessage.ModifyGroupI
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(requestSourceType == ProtoConstants.RequestSourceType.Request_From_User) {
int forbiddenClientOperation = m_messagesStore.getGroupForbiddenClientOperation();
if(request.getType() == Modify_Group_Mute) {
if((forbiddenClientOperation & ProtoConstants.ForbiddenClientGroupOperationMask.Forbidden_Mute_Group) > 0) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
} else {
if((forbiddenClientOperation & ProtoConstants.ForbiddenClientGroupOperationMask.Forbidden_Modify_Group_Info) > 0) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
}
}
ErrorCode errorCode= m_messagesStore.modifyGroupInfo(fromUser, request.getGroupId(), request.getType(), request.getValue(), isAdmin);
if (errorCode == ERROR_CODE_SUCCESS) {
if(request.hasNotifyContent() && request.getNotifyContent().getType() > 0) {
@@ -31,7 +31,14 @@ public class QuitGroupHandler extends GroupHandler<WFCMessage.QuitGroupRequest>
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
ErrorCode errorCode = m_messagesStore.quitGroup(fromUser, request.getGroupId());
if(requestSourceType == ProtoConstants.RequestSourceType.Request_From_User) {
int forbiddenClientOperation = m_messagesStore.getGroupForbiddenClientOperation();
if((forbiddenClientOperation & ProtoConstants.ForbiddenClientGroupOperationMask.Forbidden_Quit_Group) > 0) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
}
ErrorCode errorCode = m_messagesStore.quitGroup(fromUser, request.getGroupId(), isAdmin);
if (errorCode == ErrorCode.ERROR_CODE_SUCCESS) {
if (request.hasNotifyContent() && request.getNotifyContent().getType() > 0) {
sendGroupNotification(fromUser, request.getGroupId(), request.getToLineList(), request.getNotifyContent());
@@ -40,6 +40,11 @@ public class RouteHandler extends IMHandler<WFCMessage.RouteRequest> {
return ErrorCode.ERROR_CODE_SECRECT_KEY_MISMATCH;
}
if(request.getPlatform() != session.getPlatform() && m_messagesStore.existSignatures()) {
LOG.error("Session <{}, {}> platform is {} mismatch the request {}", session.getUsername(), session.getClientID(), session.getPlatform(), request.getPlatform());
return ErrorCode.ERROR_CODE_SECRECT_KEY_MISMATCH;
}
String serverIp = mServer.getServerIp();
String longPort = mServer.getLongPort();
String shortPort = mServer.getShortPort();
@@ -22,6 +22,7 @@ import cn.wildfirechat.common.ErrorCode;
import io.netty.buffer.Unpooled;
import win.liyufan.im.*;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
@@ -33,6 +34,7 @@ public class SendMessageHandler extends IMHandler<WFCMessage.Message> {
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 mNoForwardAdminMessage = false;
@@ -47,12 +49,9 @@ public class SendMessageHandler extends IMHandler<WFCMessage.Message> {
mForwardUrl = mServer.getConfig().getProperty(BrokerConstants.MESSAGE_Forward_Url);
if (!StringUtil.isNullOrEmpty(mForwardUrl)) {
String forwardTypes = mServer.getConfig().getProperty(BrokerConstants.MESSAGE_Forward_Types);
if (!StringUtil.isNullOrEmpty(forwardTypes)) {
String[] tss = forwardTypes.split(",");
for (String ts:tss) {
mForwardMessageTypes.add(Integer.parseInt(ts.trim()));
}
}
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);
@@ -97,6 +96,30 @@ public class SendMessageHandler extends IMHandler<WFCMessage.Message> {
}
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) {
ErrorCode errorCode = ErrorCode.ERROR_CODE_SUCCESS;
@@ -159,6 +182,15 @@ public class SendMessageHandler extends IMHandler<WFCMessage.Message> {
}
}
}
} else if (message.getConversation().getType() == ProtoConstants.ConversationType.ConversationType_Group) {
if(m_messagesStore.getGroupInfo(message.getConversation().getTarget()) == null) {
return ErrorCode.ERROR_CODE_NOT_EXIST;
}
} else if (message.getConversation().getType() == ProtoConstants.ConversationType.ConversationType_Channel) {
WFCMessage.ChannelInfo channelData = m_messagesStore.getChannelInfo(message.getConversation().getTarget());
if(channelData == null || channelData.getStatus() == ProtoConstants.ChannelState.Channel_State_Mask_Deleted) {
return ErrorCode.ERROR_CODE_NOT_EXIST;
}
}
long timestamp = System.currentTimeMillis();
@@ -179,7 +211,7 @@ public class SendMessageHandler extends IMHandler<WFCMessage.Message> {
}
}
if (!StringUtil.isNullOrEmpty(mForwardUrl) && (mForwardMessageTypes.isEmpty() || mForwardMessageTypes.contains(message.getContent().getType())) && !(isAdmin && mNoForwardAdminMessage)) {
if (!StringUtil.isNullOrEmpty(mForwardUrl) && (mForwardMessageTypes.isEmpty() || mForwardMessageTypes.contains(message.getContent().getType())) && !(isAdmin && mNoForwardAdminMessage) && !mForwardExcludeMessageTypes.contains(message.getContent().getType())) {
publisher.forwardMessage(message, mForwardUrl, outputClient);
}
@@ -30,6 +30,13 @@ public class SetGroupManagerHandler extends GroupHandler<WFCMessage.SetGroupMana
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(requestSourceType == ProtoConstants.RequestSourceType.Request_From_User) {
int forbiddenClientOperation = m_messagesStore.getGroupForbiddenClientOperation();
if((forbiddenClientOperation & ProtoConstants.ForbiddenClientGroupOperationMask.Forbidden_Set_Group_Manage) > 0) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
}
ErrorCode errorCode = m_messagesStore.setGroupManager(fromUser, request.getGroupId(), request.getType(), request.getUserIdList(), isAdmin);
if (errorCode == ERROR_CODE_SUCCESS) {
if (request.hasNotifyContent() && request.getNotifyContent().getType() > 0) {
@@ -30,6 +30,13 @@ public class TransferGroupHandler extends GroupHandler<WFCMessage.TransferGroupR
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(requestSourceType == ProtoConstants.RequestSourceType.Request_From_User) {
int forbiddenClientOperation = m_messagesStore.getGroupForbiddenClientOperation();
if((forbiddenClientOperation & ProtoConstants.ForbiddenClientGroupOperationMask.Forbidden_Transfer_Group) > 0) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
}
ErrorCode errorCode = m_messagesStore.transferGroup(fromUser, request.getGroupId(), request.getNewOwner(), isAdmin);
if (errorCode == ERROR_CODE_SUCCESS) {
if (request.hasNotifyContent() && request.getNotifyContent().getType() > 0) {
@@ -25,9 +25,11 @@ public class UploadDeviceTokenHandler extends IMHandler<WFCMessage.UploadDeviceT
session.setPlatform(request.getPlatform());
session.setAppName(request.getAppName());
if (request.getPlatform() == ProtoConstants.Platform.Platform_iOS && request.getPushType() == 2) {
LOG.info("Set device token, userId {}", fromUser);
session.setVoipDeviceToken(request.getDeviceToken());
m_sessionsStore.updateSessionToken(session, true);
} else {
LOG.info("Set device token, userId {}, platform {}, pushType {}", fromUser, session.getPlatform(), request.getPushType());
session.setDeviceToken(request.getDeviceToken());
session.setPushType(request.getPushType());
m_sessionsStore.updateSessionToken(session, false);
@@ -203,7 +203,7 @@ public class DatabaseStore {
}
sql += " and _type <> 2"; //can search normal user(0) and robot(1) and admin(100), can not search things
sql += " and `_type` <> 2 and `_deleted` = 0"; //can search normal user(0) and robot(1) and admin(100), can not search things
if (searchType == SearchUserType_Name_Mobile || searchType == SearchUserType_Name || searchType == SearchUserType_Mobile) {
sql += " limit 1";
@@ -815,7 +815,7 @@ public class DatabaseStore {
long beforeUid = before[0];
String sql = "select `_mid`, `_from`, `_type`, `_target`, `_line`, `_data`, `_dt`, `_to` from " + table +" where";
if (conversation.getType() == ProtoConstants.ConversationType.ConversationType_Private) {
sql += " _type = ? and _line = ? and _mid < ? and ((_target = ? and _from = ?) or (_target = ? and _from = ?))";
sql += " _type = ? and _line = ? and _mid < ? and ((_target = ? and _from = ?) or (_target = ? and _from = ?)) and (_to = '' or _to = ?)";
} else if (conversation.getType() == ProtoConstants.ConversationType.ConversationType_Channel && !user.equals(channelOwner)) {
sql += " _type = ? and _line = ? and _mid < ? and _target = ? and ((_from = ? and (_to = '' or _to = ?)) or (_from = ?))";
} else {
@@ -853,6 +853,7 @@ public class DatabaseStore {
statement.setString(index++, user);
statement.setString(index++, user);
statement.setString(index++, conversation.getTarget());
statement.setString(index++, user);
} else if (conversation.getType() == ProtoConstants.ConversationType.ConversationType_Channel && !user.equals(channelOwner)) {
statement.setString(index++, channelOwner);
statement.setString(index++, user);
@@ -914,7 +915,7 @@ public class DatabaseStore {
return false;
}
void persistUserMessage(final String userId, final long messageId, final long messageSeq, int type, String target, int line, boolean directing, final int messageContentType) {
void persistUserMessage(final String userId, final String sender, final long messageId, final long messageSeq, int type, String target, int line, boolean directing, final int messageContentType) {
mScheduler.execute(()->{
Connection connection = null;
PreparedStatement statement = null;
@@ -929,7 +930,7 @@ public class DatabaseStore {
statement.setString(index++, userId);
statement.setLong(index++, messageSeq);
statement.setInt(index++, type);
statement.setString(index++, target);
statement.setString(index++, getPrivateChatUserMessageTarget(type, target, sender));
statement.setInt(index++, line);
statement.setInt(index++, directing ? 1 :0);
statement.setInt(index++, messageContentType);
@@ -945,6 +946,14 @@ public class DatabaseStore {
});
}
String getPrivateChatUserMessageTarget(int conversationType, String target, String userId) {
if(conversationType == ProtoConstants.ConversationType.ConversationType_Private) {
return target.compareTo(userId) > 0 ? (userId + "|" + target) : (target + "|" + userId);
} else {
return target;
}
}
void clearUserMessage(final String userId) {
mScheduler.execute(()->{
String tableName = getUserMessageTable(userId);
@@ -1493,12 +1502,6 @@ public class DatabaseStore {
if (!strEqual(session.getAppName(), request.getApp())) {
sql += " `_package_name` = ?,";
}
if (session.getPlatform() != request.getPlatform()) {
sql += " `_platform` = ?,";
}
if (session.getPushType() != request.getPushType()) {
sql += " `_push_type` = ?,";
}
if (!strEqual(session.getDeviceName(), request.getDeviceName())) {
sql += " `_device_name` = ?,";
}
@@ -1526,12 +1529,6 @@ public class DatabaseStore {
if (!strEqual(session.getAppName(), request.getApp())) {
statement.setString(index++, request.getApp());
}
if (session.getPlatform() != request.getPlatform()) {
statement.setInt(index++, request.getPlatform());
}
if (session.getPushType() != request.getPushType()) {
statement.setInt(index++, request.getPushType() >= 32 ? 0 : request.getPushType());
}
if (!strEqual(session.getDeviceName(), request.getDeviceName())) {
statement.setString(index++, request.getDeviceName());
}
@@ -49,6 +49,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Consumer;
@@ -121,6 +122,8 @@ public class MemoryMessagesStore implements IMessagesStore {
private Lock mReadLock = mLock.readLock();
private Lock mWriteLock = mLock.writeLock();
private Lock mUserSettingLock = new ReentrantLock();
private final DatabaseStore databaseStore;
private ConcurrentHashMap<String, Long> userMaxPullSeq = new ConcurrentHashMap<>();
@@ -142,6 +145,10 @@ public class MemoryMessagesStore implements IMessagesStore {
private boolean mMultiPlatformNotification = false;
private boolean mMobileDefaultSilentWhenPCOnline = true;
private boolean mDisableStrangerChat = false;
private Set<String> mAllowStrangerChatSet = new HashSet<>();
private Set<String> mClientSignatureSet = new HashSet<>();
private boolean mRejectEmptySignature = true;
private long mChatroomParticipantIdleTime = 900000;
private boolean mChatroomRejoinWhenActive = true;
@@ -164,6 +171,7 @@ public class MemoryMessagesStore implements IMessagesStore {
private boolean mGroupAllowClientCustomOperationNotification;
private boolean mGroupAllowRobotCustomOperationNotification;
private int mGroupVisibleQuitKickoffNotification;
private int mGroupForbiddenClientOperation;
private int mSyncDataPartSize = 0;
private boolean keepDisplayNameWhenDestroyUser = true;
@@ -187,6 +195,27 @@ public class MemoryMessagesStore implements IMessagesStore {
IS_CHATROOM_MESSAGE_REMOTE_HISTORY_MESSAGE = "1".equals(m_Server.getConfig().getProperty(MESSAGE_Remote_Chatroom_History_Message, "1"));
Constants.MAX_MESSAGE_QUEUE = Integer.parseInt(m_Server.getConfig().getProperty(MESSAGE_Max_Queue));
try {
String signatureList = m_Server.getConfig().getProperty(BrokerConstants.CONNECT_CLIENT_SIGNATURE_LIST);
if(!StringUtil.isNullOrEmptyAfterTrim(signatureList)) {
signatureList = signatureList.replace(",", ",");
for (String s : signatureList.split(",")) {
mClientSignatureSet.add(s.trim());
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if(!mClientSignatureSet.isEmpty()) {
mRejectEmptySignature = Boolean.parseBoolean(m_Server.getConfig().getProperty(BrokerConstants.CONNECT_REJECT_EMPTY_SIGNATURE, "true"));
} else {
mRejectEmptySignature = false;
}
} catch (Exception e) {
}
try {
mDisableStrangerChat = Boolean.parseBoolean(m_Server.getConfig().getProperty(BrokerConstants.MESSAGE_Disable_Stranger_Chat));
} catch (Exception e) {
@@ -195,6 +224,18 @@ public class MemoryMessagesStore implements IMessagesStore {
printMissConfigLog(MESSAGE_Disable_Stranger_Chat, mDisableStrangerChat + "");
}
try {
String allowStrangerList = m_Server.getConfig().getProperty(BrokerConstants.MESSAGE_Allow_Stranger_Chat_List);
if(!StringUtil.isNullOrEmptyAfterTrim(allowStrangerList)) {
allowStrangerList = allowStrangerList.replace(",", ",");
for (String s : allowStrangerList.split(",")) {
mAllowStrangerChatSet.add(s.trim());
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
mMultiPlatformNotification = Boolean.parseBoolean(m_Server.getConfig().getProperty(BrokerConstants.SERVER_MULTI_PLATFROM_NOTIFICATION, "false"));
} catch (Exception e) {
@@ -420,6 +461,21 @@ public class MemoryMessagesStore implements IMessagesStore {
}
try {
String s = server.getConfig().getProperty(GROUP_Forbidden_Client_Operation, null);
if(!StringUtil.isNullOrEmptyAfterTrim(s)) {
s = s.toLowerCase();
if(s.startsWith("0x")) {
s = s.substring(2);
mGroupForbiddenClientOperation = Integer.parseInt(s, 16);
} else {
mGroupForbiddenClientOperation = Integer.parseInt(s);
}
}
} catch (NumberFormatException e) {
LOG.error("Invalid group.forbidden_client_operation {}", server.getConfig().getProperty(GROUP_Forbidden_Client_Operation, null));
}
try {
mSyncDataPartSize = Integer.parseInt(server.getConfig().getProperty(SYNC_Data_Part_Size, "0"));
} catch (Exception e) {
@@ -529,21 +585,17 @@ 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(fromUser)) {
notifyReceivers.add(fromUser);
}
if(message.getToList().contains(message.getConversation().getTarget())) {
notifyReceivers.add(message.getConversation().getTarget());
}
} else {
notifyReceivers.add(fromUser);
notifyReceivers.add(message.getConversation().getTarget());
}
pullType = ProtoConstants.PullType.Pull_Normal;
} else if (type == ProtoConstants.ConversationType.ConversationType_Group) {
notifyReceivers.add(fromUser);
if (!StringUtil.isNullOrEmpty(message.getToUser())) {
notifyReceivers.add(message.getToUser());
} else if(message.getToList()!=null && !message.getToList().isEmpty()) {
@@ -569,9 +621,6 @@ public class MemoryMessagesStore implements IMessagesStore {
}
}
}
//如果是群助手的消息,返回pull type group,否则返回normal
//群助手还没有实现
pullType = ProtoConstants.PullType.Pull_Normal;
} else if (type == ProtoConstants.ConversationType.ConversationType_ChatRoom) {
boolean isDirect = !StringUtil.isNullOrEmpty(message.getToUser());
@@ -777,6 +826,10 @@ public class MemoryMessagesStore implements IMessagesStore {
mReadLock.unlock();
}
if(current == 0) {
current = 2;
head = 2;
}
builder.setCurrent(current);
builder.setHead(head);
return builder.build();
@@ -930,7 +983,7 @@ public class MemoryMessagesStore implements IMessagesStore {
messageSeq = maxPullSeq + 1;
}
if (messageSeq == 0) {
if (messageSeq < messageId) {
messageSeq = messageId;
}
@@ -942,7 +995,7 @@ public class MemoryMessagesStore implements IMessagesStore {
mWriteLock.unlock();
}
databaseStore.persistUserMessage(user, messageId, messageSeq, conversationType, target, line, directing, messageContentType);
databaseStore.persistUserMessage(user, sender, messageId, messageSeq, conversationType, target, line, directing, messageContentType);
return messageSeq;
}
@@ -1266,6 +1319,9 @@ public class MemoryMessagesStore implements IMessagesStore {
int maxCount = Integer.MAX_VALUE;
if (!isAdmin) {
if (groupInfo.getType() == ProtoConstants.GroupType.GroupType_Organization) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
boolean isMember = false;
boolean isManager = false;
WFCMessage.GroupMember gm = getGroupMember(groupId, operator);
@@ -1406,18 +1462,22 @@ public class MemoryMessagesStore implements IMessagesStore {
void removeFavGroup(String groupId, List<String> memberIds) {
HazelcastInstance hzInstance = m_Server.getHazelcastInstance();
MultiMap<String, WFCMessage.UserSettingEntry> userSettingMap = hzInstance.getMultiMap(USER_SETTING);
databaseStore.removeFavGroup(groupId, memberIds);
for (String member : memberIds) {
userSettingMap.remove(member);
try {
mUserSettingLock.lock();
MultiMap<String, WFCMessage.UserSettingEntry> userSettingMap = hzInstance.getMultiMap(USER_SETTING);
for (String member : memberIds) {
userSettingMap.remove(member);
}
} finally {
mUserSettingLock.unlock();
}
}
@Override
public ErrorCode quitGroup(String operator, String groupId) {
public ErrorCode quitGroup(String operator, String groupId, boolean admin) {
HazelcastInstance hzInstance = m_Server.getHazelcastInstance();
IMap<String, WFCMessage.GroupInfo> mIMap = hzInstance.getMap(GROUPS_MAP);
@@ -1437,6 +1497,10 @@ public class MemoryMessagesStore implements IMessagesStore {
return ErrorCode.ERROR_CODE_NOT_EXIST;
}
if(!admin && groupInfo.getType() == ProtoConstants.GroupType.GroupType_Organization) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if (groupInfo.getType() != ProtoConstants.GroupType.GroupType_Free && groupInfo.getOwner() != null && groupInfo.getOwner().equals(operator)) {
MultiMap<String, WFCMessage.GroupMember> groupMembers = hzInstance.getMultiMap(GROUP_MEMBERS);
Collection<WFCMessage.GroupMember> members = groupMembers.get(groupId);
@@ -1479,7 +1543,7 @@ public class MemoryMessagesStore implements IMessagesStore {
int[] removedCount = new int[1];
for (String groupId : groupIds) {
removedCount[0] = 0;
ErrorCode errorCode = quitGroup(userId, groupId);
ErrorCode errorCode = quitGroup(userId, groupId, true);
LOG.info("clear user {} group {} result {}", userId, groupId, errorCode);
}
}
@@ -1487,13 +1551,17 @@ public class MemoryMessagesStore implements IMessagesStore {
private void removeGroupUserSettings(String groupId, List<String> users) {
HazelcastInstance hzInstance = m_Server.getHazelcastInstance();
MultiMap<String, WFCMessage.UserSettingEntry> userSettingMap = hzInstance.getMultiMap(USER_SETTING);
databaseStore.removeGroupUserSettings(groupId, users);
for (String userId:users) {
userSettingMap.remove(userId);
try {
mUserSettingLock.lock();
MultiMap<String, WFCMessage.UserSettingEntry> userSettingMap = hzInstance.getMultiMap(USER_SETTING);
for (String userId:users) {
userSettingMap.remove(userId);
}
} finally {
mUserSettingLock.unlock();
}
}
@Override
@@ -1511,6 +1579,7 @@ public class MemoryMessagesStore implements IMessagesStore {
}
if (!isAdmin && (groupInfo.getType() == ProtoConstants.GroupType.GroupType_Free ||
groupInfo.getType() == ProtoConstants.GroupType.GroupType_Organization ||
(groupInfo.getType() == ProtoConstants.GroupType.GroupType_Restricted || groupInfo.getType() == ProtoConstants.GroupType.GroupType_Normal)
&& (groupInfo.getOwner() == null || !groupInfo.getOwner().equals(operator)))) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
@@ -1554,7 +1623,11 @@ public class MemoryMessagesStore implements IMessagesStore {
}
if (!isAdmin) {
if (oldInfo.getType() == ProtoConstants.GroupType.GroupType_Restricted) {
if (oldInfo.getType() == ProtoConstants.GroupType.GroupType_Organization && modifyType != Modify_Group_Extra && modifyType != Modify_Group_Mute && modifyType != Modify_Group_PrivateChat) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if (oldInfo.getType() == ProtoConstants.GroupType.GroupType_Restricted || oldInfo.getType() == ProtoConstants.GroupType.GroupType_Organization) {
boolean isAllow = false;
if ((oldInfo.getOwner() != null && oldInfo.getOwner().equals(operator))) {
isAllow = true;
@@ -1796,7 +1869,7 @@ public class MemoryMessagesStore implements IMessagesStore {
}
@Override
public List<WFCMessage.GroupInfo> getGroupInfos(List<WFCMessage.UserRequest> requests) {
public List<WFCMessage.GroupInfo> getGroupInfos(List<WFCMessage.UserRequest> requests, String fromUser, boolean isAdmin) {
HazelcastInstance hzInstance = m_Server.getHazelcastInstance();
IMap<String, WFCMessage.GroupInfo> mIMap = hzInstance.getMap(GROUPS_MAP);
ArrayList<WFCMessage.GroupInfo> out = new ArrayList<>();
@@ -1810,6 +1883,14 @@ public class MemoryMessagesStore implements IMessagesStore {
}
if (groupInfo != null && groupInfo.getUpdateDt() > request.getUpdateDt()) {
if(!isAdmin && !StringUtil.isNullOrEmpty(fromUser)) {
WFCMessage.GroupMember gm = getGroupMember(groupInfo.getTargetId(), fromUser);
if(gm == null) {
groupInfo = groupInfo.toBuilder().setMemberUpdateDt(-1).build();
} else if(gm.getType() == GroupMemberType_Removed) {
groupInfo = groupInfo.toBuilder().setMemberUpdateDt(-groupInfo.getMemberUpdateDt()).build();
}
}
out.add(groupInfo);
}
}
@@ -1920,6 +2001,10 @@ public class MemoryMessagesStore implements IMessagesStore {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if (!isAdmin && groupInfo.getType() == ProtoConstants.GroupType.GroupType_Organization) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
//check the new owner is in member list? is that necessary?
long updateDt = System.currentTimeMillis();
groupInfo = groupInfo.toBuilder().setOwner(newOwner).setUpdateDt(updateDt).setMemberUpdateDt(updateDt).build();
@@ -2784,6 +2869,11 @@ public class MemoryMessagesStore implements IMessagesStore {
if (mDisableStrangerChat) {
//在禁止私聊时,是否是允许私聊的用户id
if(mAllowStrangerChatSet.contains(targetUser)) {
return ErrorCode.ERROR_CODE_SUCCESS;
}
//在禁止私聊时,允许机器人,物联网设备及管理员进行私聊。
IMap<String, WFCMessage.User> mUserMap = hzInstance.getMap(USERS);
WFCMessage.User target = mUserMap.get(targetUser);
@@ -3553,9 +3643,15 @@ public class MemoryMessagesStore implements IMessagesStore {
IMap<String, WFCMessage.GroupInfo> mGroups = hzInstance.getMap(GROUPS_MAP);
IMap<String, WFCMessage.ChannelInfo> mChannels = hzInstance.getMap(CHANNELS);
Collection<WFCMessage.UserSettingEntry> entries = userSettingMap.get(userId);
if (entries == null || entries.size() == 0) {
entries = loadPersistedUserSettings(userId, userSettingMap);
Collection<WFCMessage.UserSettingEntry> entries;
try {
mUserSettingLock.lock();
entries = userSettingMap.get(userId);
if (entries == null || entries.size() == 0) {
entries = loadPersistedUserSettings(userId, userSettingMap);
}
} finally {
mUserSettingLock.unlock();
}
ErrorCode ec = ErrorCode.ERROR_CODE_NOT_MODIFIED;
@@ -3634,17 +3730,22 @@ public class MemoryMessagesStore implements IMessagesStore {
HazelcastInstance hzInstance = m_Server.getHazelcastInstance();
MultiMap<String, WFCMessage.UserSettingEntry> userSettingMap = hzInstance.getMultiMap(USER_SETTING);
Collection<WFCMessage.UserSettingEntry> entries = userSettingMap.get(userId);
if (entries == null || entries.size() == 0) {
entries = loadPersistedUserSettings(userId, userSettingMap);
}
try {
mUserSettingLock.lock();
Collection<WFCMessage.UserSettingEntry> entries = userSettingMap.get(userId);
if (entries == null || entries.size() == 0) {
entries = loadPersistedUserSettings(userId, userSettingMap);
}
if (entries != null) {
for (WFCMessage.UserSettingEntry entry : entries) {
if (entry.getScope() == scope && (key== null || key.equals(entry.getKey()))) {
return entry;
if (entries != null) {
for (WFCMessage.UserSettingEntry entry : entries) {
if (entry.getScope() == scope && (key== null || key.equals(entry.getKey()))) {
return entry;
}
}
}
} finally {
mUserSettingLock.unlock();
}
return null;
@@ -3655,19 +3756,25 @@ public class MemoryMessagesStore implements IMessagesStore {
HazelcastInstance hzInstance = m_Server.getHazelcastInstance();
MultiMap<String, WFCMessage.UserSettingEntry> userSettingMap = hzInstance.getMultiMap(USER_SETTING);
Collection<WFCMessage.UserSettingEntry> entries = userSettingMap.get(userId);
if (entries == null || entries.size() == 0) {
entries = loadPersistedUserSettings(userId, userSettingMap);
}
List<WFCMessage.UserSettingEntry> result;
try {
mUserSettingLock.lock();
Collection<WFCMessage.UserSettingEntry> entries = userSettingMap.get(userId);
if (entries == null || entries.size() == 0) {
entries = loadPersistedUserSettings(userId, userSettingMap);
}
List<WFCMessage.UserSettingEntry> result = new ArrayList<>();
if (entries != null) {
for (WFCMessage.UserSettingEntry entry : entries
) {
if (entry.getScope() == scope) {
result.add(entry);
result = new ArrayList<>();
if (entries != null) {
for (WFCMessage.UserSettingEntry entry : entries
) {
if (entry.getScope() == scope) {
result.add(entry);
}
}
}
} finally {
mUserSettingLock.unlock();
}
return result;
@@ -3678,28 +3785,34 @@ public class MemoryMessagesStore implements IMessagesStore {
HazelcastInstance hzInstance = m_Server.getHazelcastInstance();
MultiMap<String, WFCMessage.UserSettingEntry> userSettingMap = hzInstance.getMultiMap(USER_SETTING);
Collection<WFCMessage.UserSettingEntry> entries = userSettingMap.get(userId);
if (entries == null || entries.size() == 0) {
entries = loadPersistedUserSettings(userId, userSettingMap);
if (entries == null) {
entries = new ArrayList<>();
long updateDt = 0;
try {
mUserSettingLock.lock();
Collection<WFCMessage.UserSettingEntry> entries = userSettingMap.get(userId);
if (entries == null || entries.size() == 0) {
entries = loadPersistedUserSettings(userId, userSettingMap);
if (entries == null) {
entries = new ArrayList<>();
}
}
}
long updateDt = System.currentTimeMillis();
WFCMessage.UserSettingEntry settingEntry = WFCMessage.UserSettingEntry.newBuilder().setScope(request.getScope()).setKey(request.getKey()).setValue(request.getValue()).setUpdateDt(updateDt).build();
databaseStore.persistUserSetting(userId, settingEntry);
updateDt = System.currentTimeMillis();
WFCMessage.UserSettingEntry settingEntry = WFCMessage.UserSettingEntry.newBuilder().setScope(request.getScope()).setKey(request.getKey()).setValue(request.getValue()).setUpdateDt(updateDt).build();
databaseStore.persistUserSetting(userId, settingEntry);
for (WFCMessage.UserSettingEntry entry : entries
) {
if (entry.getScope() == request.getScope() && entry.getKey().equals(request.getKey())) {
userSettingMap.remove(userId, entry);
userSettingMap.put(userId, settingEntry);
break;
for (WFCMessage.UserSettingEntry entry : entries
) {
if (entry.getScope() == request.getScope() && entry.getKey().equals(request.getKey())) {
userSettingMap.remove(userId, entry);
userSettingMap.put(userId, settingEntry);
break;
}
}
}
userSettingMap.put(userId, settingEntry);
userSettingMap.put(userId, settingEntry);
} finally {
mUserSettingLock.unlock();
}
if(request.getScope() == UserSettingScope.kUserSettingConversationSilent) {
int firstSplit = request.getKey().indexOf("-");
@@ -3724,8 +3837,14 @@ public class MemoryMessagesStore implements IMessagesStore {
public void clearUserSettings(String userId) {
databaseStore.clearUserSetting(userId);
HazelcastInstance hzInstance = m_Server.getHazelcastInstance();
MultiMap<String, WFCMessage.UserSettingEntry> userSettingMap = hzInstance.getMultiMap(USER_SETTING);
userSettingMap.remove(userId);
try {
mUserSettingLock.lock();
MultiMap<String, WFCMessage.UserSettingEntry> userSettingMap = hzInstance.getMultiMap(USER_SETTING);
userSettingMap.remove(userId);
} finally {
mUserSettingLock.unlock();
}
}
@Override
@@ -4116,6 +4235,11 @@ public class MemoryMessagesStore implements IMessagesStore {
return mGroupVisibleQuitKickoffNotification;
}
@Override
public int getGroupForbiddenClientOperation() {
return mGroupForbiddenClientOperation;
}
@Override
public boolean isForwardMessageWithClientInfo() {
return mForwardMessageWithClientInfo;
@@ -4256,6 +4380,34 @@ public class MemoryMessagesStore implements IMessagesStore {
return UUIDGenerator.getUUID();
}
@Override
public boolean checkSignature(String signature) {
if(mClientSignatureSet.isEmpty()) {
return true;
}
if(StringUtil.isNullOrEmptyAfterTrim(signature)) {
if(mRejectEmptySignature) {
LOG.info("Failed check signature, no signature");
return false;
} else {
return true;
}
} else {
if(mClientSignatureSet.contains(signature)) {
return true;
} else {
LOG.info("Failed check signature, signature no matched");
return false;
}
}
}
@Override
public boolean existSignatures() {
return !mClientSignatureSet.isEmpty();
}
@Override
public void storeRetained(Topic topic, StoredMessage storedMessage) {
LOG.debug("Store retained message for topic={}, CId={}", topic, storedMessage.getClientID());
@@ -110,13 +110,13 @@ public interface IMessagesStore {
WFCMessage.GroupInfo createGroup(String operator, WFCMessage.GroupInfo groupInfo, List<WFCMessage.GroupMember> memberList, String memberExtra, boolean isAdmin);
ErrorCode addGroupMembers(String operator, boolean isAdmin, String groupId, List<WFCMessage.GroupMember> memberList, String extra);
ErrorCode kickoffGroupMembers(String operator, boolean isAdmin, String groupId, List<String> memberList);
ErrorCode quitGroup(String operator, String groupId);
ErrorCode quitGroup(String operator, String groupId, boolean admin);
void clearUserGroups(String userId);
ErrorCode dismissGroup(String operator, String groupId, boolean isAdmin);
ErrorCode modifyGroupInfo(String operator, String groupId, int modifyType, String value, boolean isAdmin);
ErrorCode modifyGroupMemberAlias(String operator, String groupId, String alias, String memberId, boolean isAdmin);
ErrorCode modifyGroupMemberExtra(String operator, String groupId, String extra, String memberId, boolean isAdmin);
List<WFCMessage.GroupInfo> getGroupInfos(List<WFCMessage.UserRequest> requests);
List<WFCMessage.GroupInfo> getGroupInfos(List<WFCMessage.UserRequest> requests, String fromUser, boolean isAdmin);
WFCMessage.GroupInfo getGroupInfo(String groupId);
Set<String> getUserGroupIds(String userId);
Set<String> getCommonGroupIds(String userId1, String userId2);
@@ -233,6 +233,8 @@ public interface IMessagesStore {
boolean isAllowRobotCustomGroupNotification();
int getVisibleQuitKickoffNotification();
int getGroupForbiddenClientOperation();
boolean isForwardMessageWithClientInfo();
boolean isRobotCallbackWithClientInfo();
boolean isChannelCallbackWithClientInfo();
@@ -249,6 +251,9 @@ public interface IMessagesStore {
//使用了数据库,会比较慢,仅能用户用户/群组等id的生成
String getShortUUID();
boolean checkSignature(String signature);
boolean existSignatures();
/**
* Used to initialize all persistent store structures
*/
@@ -48,6 +48,7 @@ import win.liyufan.im.HttpUtils;
import win.liyufan.im.IMTopic;
import win.liyufan.im.Utility;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -339,6 +340,24 @@ public class ProtocolProcessor {
failedCredentials(channel);
return false;
}
if(session.getPlatform() == ProtoConstants.Platform.Platform_Android || session.getPlatform() == ProtoConstants.Platform.Platform_APad) {
byte[] signature = msg.payload().signatureInBytes();
String basedSign = null;
if (signature != null && signature.length > 0) {
signature = AES.AESDecrypt(signature, session.getSecret(), true);
}
if (signature != null && signature.length > 0) {
basedSign = Base64.getEncoder().encodeToString(signature);
}
if (!m_messagesStore.checkSignature(basedSign)) {
LOG.error("Bad signature of session <{}, {}>", session.getUsername(), session.getClientID());
failedBadSignature(channel);
return false;
}
}
session.setMqttVersion(mqttVersion);
} else {
LOG.error("Client didn't supply any password and MQTT anonymous mode is disabled CId={}", clientId);
@@ -446,6 +465,11 @@ public class ProtocolProcessor {
LOG.info("Client {} failed to connect with bad username or password.", session);
}
private void failedBadSignature(Channel session) {
session.writeAndFlush(connAck(CONNECTION_REFUSED_SIGNATURE_FAILURE));
LOG.info("Client {} failed to connect with bad signature.", session);
}
private void setIdleTime(ChannelPipeline pipeline, int idleTime) {
if (pipeline.names().contains("idleStateHandler")) {
pipeline.remove("idleStateHandler");
@@ -32,6 +32,7 @@ public final class MqttConnectPayload {
private final byte[] willMessage;
private final String userName;
private final byte[] password;
private final byte[] signature;
/**
* @deprecated use {@link MqttConnectPayload#MqttConnectPayload(String,
@@ -50,7 +51,7 @@ public final class MqttConnectPayload {
willTopic,
willMessage.getBytes(CharsetUtil.UTF_8),
userName,
password.getBytes(CharsetUtil.UTF_8));
password.getBytes(CharsetUtil.UTF_8), null);
}
public MqttConnectPayload(
@@ -64,7 +65,7 @@ public final class MqttConnectPayload {
willTopic,
willMessage,
userName,
password);
password, null);
}
public MqttConnectPayload(
@@ -73,13 +74,15 @@ public final class MqttConnectPayload {
String willTopic,
byte[] willMessage,
String userName,
byte[] password) {
byte[] password,
byte[] signature) {
this.clientIdentifier = clientIdentifier;
this.willProperties = MqttProperties.withEmptyDefaults(willProperties);
this.willTopic = willTopic;
this.willMessage = willMessage;
this.userName = userName;
this.password = password;
this.signature = signature;
}
public String clientIdentifier() {
@@ -122,6 +125,10 @@ public final class MqttConnectPayload {
return password;
}
public byte[] signatureInBytes() {
return signature;
}
@Override
public String toString() {
return new StringBuilder(StringUtil.simpleClassName(this))
@@ -29,6 +29,7 @@ public enum MqttConnectReturnCode {
CONNECTION_REFUSED_NOT_AUTHORIZED((byte) 0x05),
CONNECTION_REFUSED_UNEXPECT_NODE((byte) 0X06),
CONNECTION_REFUSED_SESSION_NOT_EXIST((byte) 0x07),
CONNECTION_REFUSED_SIGNATURE_FAILURE((byte) 0x08),
//MQTT 5 codes
CONNECTION_REFUSED_UNSPECIFIED_ERROR((byte) 0x80),
CONNECTION_REFUSED_MALFORMED_PACKET((byte) 0x81),
@@ -146,7 +146,7 @@ public final class MqttDecoder extends ReplayingDecoder<MqttDecoder.DecoderState
* bytes for the remaining length.
*
* @see
* https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/errata01/os/mqtt-v3.1.1-errata01-os-complete.html#_Toc442180841
* <a href="https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/errata01/os/mqtt-v3.1.1-errata01-os-complete.html#_Toc442180841">...</a>
*
* @param buffer the buffer to decode from
* @return the fixed header
@@ -534,7 +534,7 @@ public final class MqttDecoder extends ReplayingDecoder<MqttDecoder.DecoderState
final MqttProperties willProperties;
if (mqttConnectVariableHeader.isWillFlag()) {
if (mqttVersion == MqttVersion.MQTT_5) {
if (mqttVersion.protocolLevel() <= MqttVersion.MQTT_5.protocolLevel()) {
final Result<MqttProperties> propertiesResult = decodeProperties(buffer);
willProperties = propertiesResult.value;
numberOfBytesConsumed += propertiesResult.numberOfBytesConsumed;
@@ -550,6 +550,7 @@ public final class MqttDecoder extends ReplayingDecoder<MqttDecoder.DecoderState
}
Result<String> decodedUserName = null;
byte[] decodedPassword = null;
byte[] decodedSignature = null;
if (mqttConnectVariableHeader.hasUserName()) {
decodedUserName = decodeString(buffer);
numberOfBytesConsumed += decodedUserName.numberOfBytesConsumed;
@@ -558,6 +559,10 @@ public final class MqttDecoder extends ReplayingDecoder<MqttDecoder.DecoderState
decodedPassword = decodeByteArray(buffer);
numberOfBytesConsumed += decodedPassword.length + 2;
}
if (mqttConnectVariableHeader.isWillRetain()) {
decodedSignature = decodeByteArray(buffer);
numberOfBytesConsumed += decodedSignature.length + 2;
}
final MqttConnectPayload mqttConnectPayload =
new MqttConnectPayload(
@@ -566,7 +571,9 @@ public final class MqttDecoder extends ReplayingDecoder<MqttDecoder.DecoderState
decodedWillTopic != null ? decodedWillTopic.value : null,
decodedWillMessage,
decodedUserName != null ? decodedUserName.value : null,
decodedPassword);
decodedPassword,
decodedSignature
);
return new Result<MqttConnectPayload>(mqttConnectPayload, numberOfBytesConsumed);
}
@@ -208,7 +208,7 @@ public final class MqttMessageBuilders {
keepAliveSecs,
properties);
MqttConnectPayload mqttConnectPayload =
new MqttConnectPayload(clientId, willProperties, willTopic, willMessage, username, password);
new MqttConnectPayload(clientId, willProperties, willTopic, willMessage, username, password, null);
return new MqttConnectMessage(mqttFixedHeader, mqttConnectVariableHeader, mqttConnectPayload);
}
}
@@ -88,7 +88,7 @@ public class HttpUtils {
System.out.println(logText);
e.printStackTrace();
LOG.error(logText);
LOG.error("POST to {} with data {} failure", url, jsonStr);
LOG.error("POST to {} failed", url);
if(httpCallback != null) {
httpCallback.onFailure(-1, e.getMessage());
}
+2 -2
View File
@@ -20,14 +20,14 @@
<RollingRandomAccessFile name="RollingFileInfo" immediateFlush="false"
fileName="${MSG_LOG_HOME}/wildfirechat.log"
filePattern="${MSG_LOG_HOME}/backup/wildfirechat.%d{yyyyMMddHH}.zip">
filePattern="${MSG_LOG_HOME}/backup/wildfirechat.%d{yyyyMMddHHmm}.zip">
<Filters>
<ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
</Filters>
<PatternLayout pattern="${pattern}" />
<Policies>
<!-- TimeBasedTriggeringPolicy :时间滚动策略,默认0点小时产生新的文件,interval="6" : 自定义文件滚动时间间隔,每隔6小时产生新文件, modulate="true" : 产生文件是否以0点偏移时间,即6点,12点,18点,0点-->
<!-- <TimeBasedTriggeringPolicy interval="6" modulate="true"/>-->
<TimeBasedTriggeringPolicy interval="6" modulate="true"/>
<!-- SizeBasedTriggeringPolicy :文件大小滚动策略-->
<SizeBasedTriggeringPolicy size="100 MB"/>
</Policies>
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>wildfirechat-parent</artifactId>
<groupId>cn.wildfirechat</groupId>
<version>0.98</version>
<version>1.1.2</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -90,10 +90,14 @@ public interface APIPath {
String Health = "/admin/health";
String Conference_List = "/admin/conference/list";
String Conference_Exist = "/admin/conference/exist";
String Conference_List_Participant = "/admin/conference/list_participant";
String Conference_Create = "/admin/conference/create";
String Conference_Destroy = "/admin/conference/destroy";
String Conference_Recording = "/admin/conference/recording";
String Conference_Rtp_Forward = "/admin/conference/rtp_forward";
String Conference_Stop_Rtp_Forward = "/admin/conference/stop_rtp_forward";
String Conference_List_Rtp_Forward = "/admin/conference/list_rtp_forward";
String Channel_User_Info = "/channel/user_info";
String Channel_Update_Profile = "/channel/update_profile";
@@ -101,6 +105,7 @@ public interface APIPath {
String Channel_Message_Send = "/channel/message/send";
String Channel_Subscribe = "/channel/subscribe";
String Channel_Subscriber_List = "/channel/subscriber_list";
String Channel_Is_Subscriber = "/channel/is_subscriber";
String Channel_Application_Get_UserInfo = "/channel/application/get_user_info";
String Robot_User_Info = "/robot/user_info";
@@ -61,6 +61,8 @@ public enum ErrorCode {
ERROR_CODE_SECRET_CHAT_MO_DISABLED(86, "origin side disable secret chat"),
ERROR_CODE_SECRET_CHAT_MT_DISABLED(87, "target side disable secret chat"),
ERROR_CODE_CONFERENCE_ERROR(90, "Conference server response error"),
ERROR_CODE_FUNCTION_DISABLED(220, "function disabled"),
ERROR_CODE_CHANNEL_NO_EXIST(236, "channel no exist"),
@@ -3,5 +3,7 @@ package cn.wildfirechat.pojos;
public class ConferenceLeaveEvent {
public String userId;
public String roomId;
public boolean rejoin;
public boolean kicked;
public boolean screenSharing;
}
@@ -1,6 +1,15 @@
package cn.wildfirechat.pojos;
import java.util.List;
public class PojoConferenceParticipant {
public static class Stream {
public String type;
public String mid;
public String codec;
}
public String userId;
public boolean publishing;
public List<Stream> streams;
}
@@ -0,0 +1,28 @@
package cn.wildfirechat.pojos;
public class PojoConferenceRtpForwardReq {
public String roomId;
public String publisherId;
public String host;
public int audioPort;
public int audioPt;
public long audioSSRC;
public int videoPort;
public int videoPt;
public long videoSSRC;
public PojoConferenceRtpForwardReq() {
}
public PojoConferenceRtpForwardReq(String roomId, String publisherId, String host, int audioPort, int audioPt, long audioSSRC, int videoPort, int videoPt, long videoSSRC) {
this.roomId = roomId;
this.publisherId = publisherId;
this.host = host;
this.audioPort = audioPort;
this.audioPt = audioPt;
this.audioSSRC = audioSSRC;
this.videoPort = videoPort;
this.videoPt = videoPt;
this.videoSSRC = videoSSRC;
}
}
@@ -0,0 +1,21 @@
package cn.wildfirechat.pojos;
import java.util.List;
public class PojoConferenceRtpForwarders {
public static class RtpForwarder {
public static class RtpStream {
public long streamId;
public String type;
public String host;
public int port;
public long ssrc;
public int pt;
}
public String publisherId;
public List<RtpStream> streams;
}
public String roomId;
public List<RtpForwarder> forwarders;
}
@@ -0,0 +1,16 @@
package cn.wildfirechat.pojos;
public class PojoConferenceStopRtpForwardReq {
public String roomId;
public String publisherId;
public long streamId;
public PojoConferenceStopRtpForwardReq() {
}
public PojoConferenceStopRtpForwardReq(String roomId, String publisherId, long streamId) {
this.roomId = roomId;
this.publisherId = publisherId;
this.streamId = streamId;
}
}
@@ -19,6 +19,8 @@ public class ProtoConstants {
int GroupType_Free = 1;
//member can only quit, owner can do all the operations
int GroupType_Restricted = 2;
//member can not do anything, server api manage the group
int GroupType_Organization = 3;
}
//message GroupMember -> type
@@ -290,6 +292,34 @@ public class ProtoConstants {
int ApplicationType_Admin = 2;
}
//禁止客户端群操作。
// 第1位是禁止创建群组,
// 第2位是禁止销毁群组,
// 3位禁止加入群,
// 4位禁止退出群,
// 5位禁止邀请群成员,
// 6位禁止移出群成员,
// 7位禁止转移群
// 8位禁止设置群管理员
// 9位禁止允许群成员(专业版支持),
// 10位禁止群禁言
// 11位禁止修改群组信息,
// 12位禁止群成员禁言(专业版支持)
public interface ForbiddenClientGroupOperationMask {
int Forbidden_Create_Group = 0x01;
int Forbidden_Dismiss_Group = 0x02;
int Forbidden_Join_Group = 0x04;
int Forbidden_Quit_Group = 0x08;
int Forbidden_Invite_Group_Member = 0x10;
int Forbidden_Kickoff_Group_Member = 0x20;
int Forbidden_Transfer_Group = 0x40;
int Forbidden_Set_Group_Manage = 0x80;
int Forbidden_Allow_Group_Member = 0x100;
int Forbidden_Mute_Group = 0x200;
int Forbidden_Modify_Group_Info = 0x400;
int Forbidden_Mute_Group_Member = 0x800;
}
public static final int MESSAGE_CONTENT_TYPE_CREATE_GROUP = 104;
public static final int MESSAGE_CONTENT_TYPE_ADD_GROUP_MEMBER = 105;
public static final int MESSAGE_CONTENT_TYPE_KICKOF_GROUP_MEMBER = 106;
+1 -1
View File
@@ -6,7 +6,7 @@
<!--<relativePath>../pom.xml</relativePath>-->
<artifactId>wildfirechat-parent</artifactId>
<groupId>cn.wildfirechat</groupId>
<version>0.98</version>
<version>1.1.2</version>
</parent>
<artifactId>distribution</artifactId>
+27 -2
View File
@@ -29,6 +29,11 @@
<directory>../systemd/</directory>
<outputDirectory>/systemd</outputDirectory>
</fileSet>
<fileSet>
<directory>src/main/checker/</directory>
<outputDirectory>checker/</outputDirectory>
</fileSet>
</fileSets>
<files>
@@ -39,6 +44,12 @@
<fileMode>0755</fileMode>
</file>
<file>
<source>src/main/scripts/stop.sh</source>
<outputDirectory>bin</outputDirectory>
<fileMode>0755</fileMode>
</file>
<file>
<source>src/main/scripts/wildfirechat.bat</source>
<outputDirectory>bin</outputDirectory>
@@ -49,7 +60,7 @@
</file>
<file>
<source>src/main/files/release_note.md</source>
<source>../release_note.md</source>
</file>
<file>
@@ -75,8 +86,22 @@
<outputDirectory>server_sdk/</outputDirectory>
<destName>common-${project.version}.jar</destName>
</file>
</files>
<file>
<source>../sdk/target/checker.jar</source>
<outputDirectory>checker/</outputDirectory>
</file>
<file>
<source>../docker/Dockerfile</source>
<outputDirectory>docker/</outputDirectory>
</file>
<file>
<source>../docker/README.md</source>
<outputDirectory>docker/</outputDirectory>
</file>
</files>
<dependencySets>
<dependencySet>
+5
View File
@@ -0,0 +1,5 @@
部署IM服务后,可以使用Server SDK通过API来检查服务的部署情况,可以执行:
```shell
java -jar checker.jar http://127.0.0.1:18080 123456 http://127.0.0.1 true false
```
来检查。检查之后会产生垃圾数据,请在检查之后停掉IM服务后,再删除掉IM服务数据库。此检查仅检查API,检查通过并不代表部署肯定成功,还需要客户端来验证。
@@ -8,8 +8,13 @@ if [ ! -d /etc/im-server ]; then
mkdir /etc/im-server
fi
if [ ! -d /var/log/im-server ]; then
mkdir /var/log/im-server
fi
mv -f /opt/im-server/config /etc/im-server
systemctl daemon-reload
echo "IM server folders:"
echo "/etc/im-server/config config"
echo "/opt/im-server binary files"
+2 -2
View File
@@ -20,14 +20,14 @@
<RollingRandomAccessFile name="RollingFileInfo" immediateFlush="false"
fileName="${MSG_LOG_HOME}/wildfirechat.log"
filePattern="${MSG_LOG_HOME}/backup/wildfirechat.%d{yyyyMMddHH}.zip">
filePattern="${MSG_LOG_HOME}/backup/wildfirechat.%d{yyyyMMddHHmm}.zip">
<Filters>
<ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
</Filters>
<PatternLayout pattern="${pattern}" />
<Policies>
<!-- TimeBasedTriggeringPolicy :时间滚动策略,默认0点小时产生新的文件,interval="6" : 自定义文件滚动时间间隔,每隔6小时产生新文件, modulate="true" : 产生文件是否以0点偏移时间,即6点,12点,18点,0点-->
<!-- <TimeBasedTriggeringPolicy interval="6" modulate="true"/>-->
<TimeBasedTriggeringPolicy interval="6" modulate="true"/>
<!-- SizeBasedTriggeringPolicy :文件大小滚动策略-->
<SizeBasedTriggeringPolicy size="100 MB"/>
</Policies>
@@ -32,6 +32,7 @@ local_port 80
## 是否使用内置DB。0使用mysql;1使用h2db。
## MySQL需要把事物隔离级别改成"Read committed",使用命令来修改"set global transaction_isolation='read-committed';",其他数据库默认已经是这个级别不用修改
## 如果使用MySQL,请在c3p0.xml文件中配置JDBC信息。
## 如果是MySQL5.7,需要开启长索引的支持,在数据库中执行命令:"set global innodb_large_prefix=on;"。其他版本默认支持,不用修改。
embed.db 1
## 是否自动清理历史消息记录,当为true时,IM服务会定时扫描t_messages_x和t_user_messages_x表,清除掉3年前的历史消息。
@@ -56,6 +57,12 @@ token.key testim
##token的过期时间,单位为毫秒,默认为无限期。如果需要设置无限期,客户端上一定需要加上token过期的处理。token过期的处理请参考文档的常见问题
##token.expire_time 2592000000
##客户端(目前只有android)的应用签名(一个应用最取第一个签名),如果有多个签名(多个客户端),用英文逗号分开。获取签名方法请参考文档:https://docs.wildfirechat.cn/blogs/签名验证.html
#connect.client_signature_list eNkezQ1g9OsnhfLSFUY1vzKDzhs=,xykezQ1g9OsnhfLSFUY1vzKDzhs=
##是否拒绝空签名的android客户端, 默认为true。当有旧的客户端需要兼容时改成false,当所有都是新客户端时,改成true。
#connect.reject_empty_signature true
##首次登录,是否接收之前的历史消息。
##0 不接收历史消息,只接收${message.compensate_time_limit}毫秒以内的消息,由于服务器没有保存已经收取记录,所以如果有超过${message.compensate_time_limit}毫秒之前未收取的消息也不会收取下拉;
##1接收,会接收 message.max_queue 配置的条数的历史消息
@@ -76,6 +83,9 @@ message.chatroom_remote_history_message 1
##是否禁止陌生人聊天
message.disable_stranger_chat false
##当禁止陌生人聊天时,允许聊天的用户id,比如管理员或者文件传输助手等。用户id以英文逗号分割。
message.allow_stranger_chat_list admin,FireRobot,wfc_file_transfer
##黑名单策略,0 发送失败,返回被拉黑的错误码;1 发送成功但消息被服务器直接丢弃
message.blacklist.strategy 0
@@ -159,6 +169,10 @@ group.allow_robot_custom_operation_notification true
## 如果应用需要退群或者踢人不通知普通成员,请设置此参数为3,然后修改客户端踢人或退群消息的flag为not_presist。
group.visible_quit_or_kickoff_notification 0
## 禁止客户端群操作。第1位是禁止创建群组,第2位是禁止销毁群组,3位禁止加入群,4位禁止退出群,5位禁止邀请群成员,6位禁止移出群成员,7位禁止转移群,8位禁止设置群管理员,9位禁止白名单处理,10位禁止群禁言,11位禁止修改群组信息,12位禁止群成员禁言。
## 如果有客户端有被破解的风险,可以禁止客户端群操作,然后通过Server API操作。Server API不受限制。
#group.forbidden_client_operation 0xFFF
## 隐藏用户信息属性类型,2是性别,3是电话号码,4是邮箱,5是地址,6是公司信息,7是社交账号,8是Extra信息。当需要隐藏多个时以英文逗号分开;
## 本配置是为了提高安全性,避免把对应信息同步到客户端,这样就能防止程序被破解从而拿到用户关键信息。仅对客户端有效,server api不受影响。
## 注意,修改本配置不会对已经同步的信息产生影响。
@@ -289,15 +303,18 @@ push.ios.server.address http://localhost:8085/ios/push
##消息转发地址
##注意回调是单线程回调,接收服务必须在同一内网,且异步处理快速返回,否则会有延迟问题!!
#message.forward.url http://localhost:8087/im_event/message
##需要转发的消息类型,当有多个时以英文逗号分割。如果转发所有消息,请注释掉配置或者设置为空
#message.forward.types 1,2,3
#message.forward.url http://localhost:8888/im_event/message
##需要转发的消息类型,当有多个时以英文逗号分割,可以用-来指定区间,注意区间不能太大,因为要把区间内的所有数字都放入到Set中。如果转发所有消息,请注释掉配置或者设置为空
#message.forward.types 1,2,3,5-10
##需要转发的消息类型,当有多个时以英文逗号分割,可以用-来指定区间,注意区间不能太大,因为要把区间内的所有数字都放入到Set中。
#message.forward.exclude_types 1,2,3,5-10
##敏感消息转发地址
##注意回调是单线程回调,接收服务必须在同一内网,且异步处理快速返回,否则会有延迟问题!!
#message.sensitive.forward.url http://localhost:8888/im_event/message
##提醒消息转发地址,@全体用户和@某个用户消息会回调此地址。此转发不受${message.forward.types}限制。
##提醒消息转发地址,@全体用户和@某个用户消息会回调此地址。
##此转发不受${message.forward.types}和${message.forward.exclude_types}限制。
##注意回调是单线程回调,接收服务必须在同一内网,且异步处理快速返回,否则会有延迟问题!!
#message.mentionmsg.forward.url http://localhost:8888/im_event/message
+4
View File
@@ -12,6 +12,10 @@ if [ ! -d /etc/im-server ]; then
mkdir /etc/im-server
fi
if [ ! -d /var/log/im-server ]; then
mkdir /var/log/im-server
fi
mv -f /opt/im-server/config /etc/im-server
systemctl daemon-reload
+25
View File
@@ -0,0 +1,25 @@
#!/bin/sh
pid=`ps -ef | grep wildfirechat.server.Server | grep -v grep | awk '{print $2}'`
if [ -z $pid ]; then
echo "野火IM服务不存在"
exit 0
fi
kill -15 $pid
for i in {1..15}
do
pid=`ps -ef | grep wildfirechat.server.Server | grep -v grep | awk '{print $2}'`
if [ -z $pid ]; then
echo "野火IM服务已结束"
exit 0
else
echo "正在结束中,请等待..."
sleep 1
fi
done
echo "正常结束失败,强制结束!"
kill -9 $pid
@@ -18,7 +18,6 @@ while [ -h "$PRG" ]; do
done
PRGDIR=`dirname "$PRG"`
cd $PRGDIR
cd ..
WILDFIRECHAT_HOME=`pwd`
+1 -1
View File
@@ -1,6 +1,6 @@
FROM openjdk:8-jre-alpine
ADD ../distribution/target/distribution-*-bundle-tar.tar.gz /opt/im-server/
ADD distribution-*-bundle-tar.tar.gz /opt/im-server/
RUN sed -i 's/#JAVA_OPTS="$JAVA_OPTS -Xmx128M"/JAVA_OPTS="$JAVA_OPTS -Xmx$JVM_XMX"/g' /opt/im-server/bin/wildfirechat.sh
RUN sed -i 's/#JAVA_OPTS="$JAVA_OPTS -Xms128M"/JAVA_OPTS="$JAVA_OPTS -Xms$JVM_XMS"/g' /opt/im-server/bin/wildfirechat.sh
+3 -2
View File
@@ -5,17 +5,18 @@
```
mvn clean package
```
生成的软件包在```distribution/target/distribution-XX-bundle-tar.tar.gz```,把此软件包拷贝到docker目录下。
然后进入到docker目录下,编译镜像
```
sudo docker build -t im-server -f Dockerfile ..
sudo docker build -t im-server .
```
## 运行
配置:
运行需要手动指定配置目录,手动指定配置目录的方法如下,其中$PATH_TO_CONFIG为im配置目录,需要为绝对路径,模版为```distribution/src/main/resources```目录。另外需要创建h2数据库目录(如果用mysql就不需要了)、日志目录、内置存储服务目录(如果使用其它对象存储服务就不需要了)。
```
sudo docker run -it -v $PATH_TO_CONFIG:/opt/im-server/config -v $PATH_TO_LOGS:/opt/im-server/logs -v $PATH_TO_H2DB:/opt/im-server/h2db -v $PATH_TO_MEDIA:/opt/im-server/media -e JVM_XMX=256M -e JVM_XMS=256M -p 80:80 -p 1883:1883 -p 8083:8083 -p 8084:8084 -p 18080:18080 im-server
sudo docker run -it --name im-server -v $PATH_TO_CONFIG:/opt/im-server/config -v $PATH_TO_LOGS:/opt/im-server/logs -v $PATH_TO_H2DB:/opt/im-server/h2db -v $PATH_TO_MEDIA:/opt/im-server/media -e JVM_XMX=256M -e JVM_XMS=256M -p 80:80 -p 1883:1883 -p 8083:8083 -p 8084:8084 -p 18080:18080 im-server
```
## 导出镜像
+1 -1
View File
@@ -12,7 +12,7 @@
<artifactId>wildfirechat-parent</artifactId>
<packaging>pom</packaging>
<version>0.98</version>
<version>1.1.2</version>
<name>Wildfire Chat</name>
<description>Wildfire Chat Server</description>
<inceptionYear>2019</inceptionYear>
@@ -12,6 +12,47 @@
# 更新记录
--------------
Release note 1.1.2:
1. 会议SDK添加查询会议是否存在的接口
2. 单聊会话定向消息分发包含发送者
--------------
Release note 1.1.1:
1. 当用户获取群组信息,可以根据返回信息判断是否在群中。
2. 搜索用户时,过滤掉已删除用户
3. 支持单聊消息的定向消息
4. 解决关闭roaming,且message.compensate_time_limit配置为-1时,首次消息无法同步的问题
5. 解决禁止客户端群操作flag 解析错误
--------------
Release note 1.1:
1. Channel API添加检查用户是否订阅接口
2. Server API发送消息时添加检查对象是否存在
3. Channel API添加修改频道菜单接口
4. 内置对象存储的优化
--------------
Release note 1.0:
1. SDK检查工具添加help命令
2. 去掉短连接端口被网络爬虫扫描输出的异常日志
3. API支持创建组织群
4. 添加配置禁止客户端进行某些群操作
5. 解决route请求时可能不能正确携带推送类型的问题
6. 会议成员离开加上离开原因
7. 添加停止程序的命令
8. 添加RTP Forward的API
--------------
Release note 0.99:
1. API获取用户信息时,过滤掉已经删除用户。
2. 消息转发功能支持设置include/exclude功能,支持按区间过滤。
3. 添加新的群组类型:组织群。组织群适用于公司部门群场景。
4. 内置对象存储支持绝对路径和相对路径配置
5. 当开启禁止陌生人聊天时,可以添加例外人员
6. 解决user setting并发问题
7. 添加可选的android平台签名验证功能。
--------------
Release note 0.98:
1. 解决linux多端登录错误问题
+33 -1
View File
@@ -3,7 +3,7 @@
<parent>
<artifactId>wildfirechat-parent</artifactId>
<groupId>cn.wildfirechat</groupId>
<version>0.98</version>
<version>1.1.2</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -81,4 +81,36 @@
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}-${version}</finalName>
<defaultGoal>install</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<finalName>checker</finalName>
<appendAssemblyId>false</appendAssemblyId>
<archive>
<manifest>
<mainClass>cn.wildfirechat.sdk.Main</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>assemble-all</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
@@ -2,14 +2,15 @@ package cn.wildfirechat.sdk;
import cn.wildfirechat.common.APIPath;
import cn.wildfirechat.pojos.*;
import cn.wildfirechat.proto.ProtoConstants;
import cn.wildfirechat.sdk.model.IMResult;
import cn.wildfirechat.sdk.utilities.ChannelHttpUtils;
import com.google.gson.Gson;
import org.apache.commons.codec.digest.DigestUtils;
import java.util.List;
import static cn.wildfirechat.proto.ProtoConstants.ApplicationType.ApplicationType_Channel;
import static cn.wildfirechat.proto.ProtoConstants.ApplicationType.ApplicationType_Robot;
//仅专业版支持,社区版不支持
public class ChannelServiceApi {
@@ -50,6 +51,11 @@ public class ChannelServiceApi {
return channelHttpUtils.httpJsonPost(path, null, OutputGetChannelInfo.class);
}
public IMResult<Void> modifyChannelMenu(List<OutputGetChannelInfo.OutputMenu> menus) throws Exception {
String menuStr = new Gson().toJson(menus);
return modifyChannelInfo(ProtoConstants.ModifyChannelInfoType.Modify_Channel_Menu, menuStr);
}
public IMResult<SendMessageResult> sendMessage(int line, List<String> targets, MessagePayload payload) throws Exception {
String path = APIPath.Channel_Message_Send;
SendChannelMessageData messageData = new SendChannelMessageData();
@@ -80,6 +86,12 @@ public class ChannelServiceApi {
return channelHttpUtils.httpJsonPost(path, null, OutputStringList.class);
}
public IMResult<Boolean> isSubscriber(String userId) throws Exception {
String path = APIPath.Channel_Is_Subscriber;
InputUserId input = new InputUserId(userId);
return channelHttpUtils.httpJsonPost(path, input, Boolean.class);
}
public IMResult<OutputApplicationUserInfo> applicationGetUserInfo(String authCode) throws Exception {
String path = APIPath.Channel_Application_Get_UserInfo;
InputApplicationGetUserInfo input = new InputApplicationGetUserInfo();
@@ -11,6 +11,12 @@ public class ConferenceAdmin {
return AdminHttpUtils.httpJsonPost(path, null, PojoConferenceInfoList.class);
}
public static IMResult<Boolean> existsConferences(String conferenceId) throws Exception {
String path = APIPath.Conference_Exist;
PojoConferenceRoomId data = new PojoConferenceRoomId(conferenceId, false);
return AdminHttpUtils.httpJsonPost(path, data, Boolean.class);
}
public static IMResult<PojoConferenceParticipantList> listParticipants(String roomId, boolean advance) throws Exception {
String path = APIPath.Conference_List_Participant;
PojoConferenceRoomId data = new PojoConferenceRoomId(roomId, advance);
@@ -45,4 +51,23 @@ public class ConferenceAdmin {
PojoConferenceRoomId conferenceRoomId = new PojoConferenceRoomId(roomId, advance);
return AdminHttpUtils.httpJsonPost(path, conferenceRoomId, Void.class);
}
public static IMResult<Void> rtpForward(String roomId, String userId, String rtpHost, int audioPort, int audioPt, long audioSSRC, int videoPort, int videoPt, long videoSSRC) throws Exception {
String path = APIPath.Conference_Rtp_Forward;
PojoConferenceRtpForwardReq req = new PojoConferenceRtpForwardReq(roomId, userId, rtpHost, audioPort, audioPt, audioSSRC, videoPort, videoPt, videoSSRC);
return AdminHttpUtils.httpJsonPost(path, req, Void.class);
}
public static IMResult<Void> stopRtpForward(String roomId, String userId, long streamId) throws Exception {
String path = APIPath.Conference_Stop_Rtp_Forward;
PojoConferenceStopRtpForwardReq req = new PojoConferenceStopRtpForwardReq(roomId, userId, streamId);
return AdminHttpUtils.httpJsonPost(path, req, Void.class);
}
public static IMResult<PojoConferenceRtpForwarders> listRtpForwarders(String roomId) throws Exception {
String path = APIPath.Conference_List_Rtp_Forward;
PojoConferenceRoomId req = new PojoConferenceRoomId();
req.roomId = roomId;
return AdminHttpUtils.httpJsonPost(path, req, PojoConferenceRtpForwarders.class);
}
}
@@ -31,11 +31,29 @@ public class Main {
public static void main(String[] args) throws Exception {
if (args.length == 5) {
AdminUrl = args[0];
AdminSecret = args[1];
IMUrl = args[2];
commercialServer = Boolean.parseBoolean(args[3]);
advanceVoip = Boolean.parseBoolean(args[4]);
} else {
if(args.length == 1 && (args[0].equals("-h") || args[0].equals("--help") || args[0].equals("-help"))) {
System.out.println("Usage: java -jar checker.jar adminUrl adminSecret imUrl commercialServer advanceVoip \n e.g. java -jar checker.jar http://192.168.1.80:18080 123456 http://192.168.1.80 false false");
return;
}
System.out.println("Usage: java -jar checker.jar adminUrl adminSecret imUrl commercialServer advanceVoip \n e.g. java -jar checker.jar http://192.168.1.80:18080 123456 http://192.168.1.80 false false");
System.out.println();
System.out.println();
System.out.println("Use default value: java -jar checker.jar http://127.0.0.1:18080 123456 http://127.0.0.1 false false");
}
//admin使用的是18080端口,超级管理接口,理论上不能对外开放端口,也不能让非内部服务知悉密钥。
testAdmin();
// testAdmin();
//Robot和Channel都是使用的80端口,第三方可以创建或者为第三方创建,第三方可以使用robot或者channel与IM系统进行对接。
testRobot();
// testRobot();
testChannel();
}
@@ -1425,6 +1443,14 @@ public class Main {
System.exit(-1);
}
IMResult<Boolean> booleanIMResult = channelServiceApi.isSubscriber("userId2");
if(booleanIMResult != null && booleanIMResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS && booleanIMResult.getResult()) {
System.out.println("is subscriber success");
} else {
System.out.println("is subscriber failure");
System.exit(-1);
}
resultVoid = channelServiceApi.unsubscribe("userId2");
if (resultVoid != null && resultVoid.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("unsubscriber done");
@@ -1665,6 +1691,14 @@ public class Main {
System.out.println("create conference");
}
IMResult<Boolean> booleanIMResult = ConferenceAdmin.existsConferences("helloroomid2");
if(booleanIMResult == null || booleanIMResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("exist conference failure");
System.exit(-1);
} else {
System.out.println("exit conference success");
}
voidIMResult = ConferenceAdmin.enableRecording("helloroomid2", true, true);
if(voidIMResult == null || voidIMResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("recording conference failure");
@@ -1690,5 +1724,31 @@ public class Main {
System.out.println("list participants success");
}
}
IMResult<PojoConferenceRtpForwarders> listForwarderResult = ConferenceAdmin.listRtpForwarders("6366963312");
if(listForwarderResult == null || listForwarderResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("list rtp forward failure");
} else {
System.out.println("list rtp forward success");
listForwarderResult.getResult().forwarders.forEach(rtpForwarder -> rtpForwarder.streams.forEach(rtpStream -> {
try {
IMResult<Void> stopRtpForwardResult = ConferenceAdmin.stopRtpForward(listForwarderResult.getResult().roomId, rtpForwarder.publisherId, rtpStream.streamId);
if(stopRtpForwardResult == null || stopRtpForwardResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("rtp forward stop failure");
} else {
System.out.println("rtp forward stop success");
}
} catch (Exception e) {
e.printStackTrace();
}
}));
}
IMResult<Void> rtpForwardResult = ConferenceAdmin.rtpForward("6366963312", "cygqmws2k", "192.168.1.81", 10000, 111, 0, 10005, 98, 0);
if(rtpForwardResult == null || rtpForwardResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("rtp forward failure");
} else {
System.out.println("rtp forward success");
}
}
}
@@ -128,7 +128,7 @@ public class AdminHttpUtils extends JsonUtils {
if (object != null) {
jsonStr = gson.toJson(object);
}
LOG.info("http request content: {}", jsonStr);
LOG.info("http request:{} content: {}", path, jsonStr);
StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
@@ -78,7 +78,7 @@ public class ChannelHttpUtils extends JsonUtils {
if (object != null) {
jsonStr = gson.toJson(object);
}
LOG.info("http request content: {}", jsonStr);
LOG.info("http request:{} content: {}", path, jsonStr);
StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
@@ -79,7 +79,7 @@ public class RobotHttpUtils extends JsonUtils {
if (object != null) {
jsonStr = gson.toJson(object);
}
LOG.info("http request content: {}", jsonStr);
LOG.info("http request:{} content: {}", path, jsonStr);
if(!StringUtil.isNullOrEmpty(jsonStr)) {
StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8"));