Compare commits

..
24 Commits
Author SHA1 Message Date
heavyrian2012 daa4767ed8 update version and release note 2026-01-20 10:35:22 +08:00
heavyrian2012 44a916892b 解决server sdk有内存泄漏的问题 2026-01-20 10:30:28 +08:00
heavyrian2012 51dd94d3a7 同步专业版IM服务数据库 2026-01-08 15:57:52 +08:00
heavyrian2012 2609a4251c 同步专业版Server SDK 2025-12-31 22:15:34 +08:00
heavyrian2012 7d36775c27 添加客户预留对象存储文件类型 2025-12-25 16:02:38 +08:00
heavyrian2012 6c9df5c071 接受好友请求后发的通知的发送者改为接受者发送 2025-12-17 09:38:55 +08:00
heavyrian2012 2f9c4e028c 解决上传文件中的逻辑问题 2025-12-02 14:46:00 +08:00
heavyrian2012 a9b83a14ed update readme 2025-12-01 15:07:15 +08:00
heavyrian2012 919b81139d update version and release note 2025-11-30 19:25:45 +08:00
heavyrian2012 52959a5e63 解决有些平台解析文本消息解析不出来的问题 2025-11-30 19:13:13 +08:00
heavyrian2012 31dad28fde update version and release note 2025-11-23 14:02:19 +08:00
heavyrian2012 3094089658 添加搜索限频配置 2025-11-23 13:59:11 +08:00
heavyrian2012 24d24fe1e9 添加配置当销毁用户时是否销毁用户信息和消息 2025-11-22 23:02:56 +08:00
heavyrian2012 47039f53b2 群组成员表添加一个索引 2025-11-20 11:51:17 +08:00
heavyrian2012 554243d553 解决移动平台多端未收消息计数重复的问题 2025-11-20 11:41:54 +08:00
heavyrian2012 b65282f8e2 更新readme 2025-11-13 22:36:41 +08:00
heavyrian2012 a5f64df2de update version and release note 2025-11-09 11:42:48 +08:00
heavyrian2012 c7f1ea57dc 解决某些平台SDK内置消息没有注册的问题 2025-11-06 18:31:12 +08:00
heavyrian2012 c9b2de076d 默认用户ID搜索用户功能开启 2025-10-31 07:31:57 +08:00
heavyrian2012 552fadaa87 记录客户端来源IP地址 2025-10-26 16:57:33 +08:00
heavyrian2012 765572db36 移除掉无用的编译plugin,解决java8编译错误问题 2025-10-13 09:57:32 +08:00
heavyrian2012 a5f194b385 server api测试代码默认为社区版 2025-10-13 09:56:56 +08:00
heavyrian2012 c74cd7e290 解决server sdk解析图片消息不带缩略图解析错误问题 2025-09-29 20:39:12 +08:00
heavyrian2012 70cf65f0c0 解决Server SDK发送引用消息客户端无法正确解析的问题 2025-09-20 09:41:29 +08:00
55 changed files with 860 additions and 386 deletions
+8
View File
@@ -158,6 +158,14 @@ mvn clean package
## 服务对象
因为野火的使用范围比较广,难免被一些不法分子利用,国内反诈反赌力度很大,所以国内多地警方都跟我们都有过联系。***为了预防我们的产品被用于非法目的,试用及购买只能支持境内法人单位,不接受个人或者境外团体。如果我们发现产品被用于非法目的,我们会立即停止技术支持服务并且报警和配合警方调查。请用于非法目的用户绕行!***
## 群的性能问题
群的大小和性能不是线性相关的,而是O(N²)的关系,这是群的特性决定的。所以社区版IM服务很难支持很大的群人数,我们建议最大群不要超过500人,像微信的群大小一样。修改方法是修改数据库中```t_settings```表中的群最大人数。
如果是专业版IM服务,普通群性能会有些加强,但也不会提高太多,所以我们就开发了超级群,可以支持上万群成员。关于超级群,请参考[野火超级群组](https://mp.weixin.qq.com/s/ov5ZiaEIUZuvgFBXOrcjbg)。现有客户有接近10W的群组成员能够流畅稳定地运行。
## 网络问题
如果是自建机房或者私有网络,可能会有跨运营商瓶颈,详情请参考[《从野火 IM 的网络踩坑经历,聊聊跨运营商访问的那些坑》](https://mp.weixin.qq.com/s/Pa8b93oMk58fjMgwtwmePQ)。
## 常见问题
请参考文档[常见问题](https://docs.wildfirechat.cn/faq/server.html)
+25 -2
View File
@@ -193,8 +193,8 @@ friend.disable_search false
##禁止按照昵称搜索用户。
friend.disable_nick_name_search false
##禁止按照用户id搜索用户,默认为true。
friend.disable_user_id_search true
##禁止按照用户id搜索用户,默认为false。
friend.disable_user_id_search false
##禁止发送好友邀请,通过server api添加好友不受此限制(force参数需要为true)
friend.disable_friend_request false
@@ -211,6 +211,12 @@ friend.request_expiration_duration 604800000
##好友请求限制频率,一个用户24小时之内允许请求好友的次数,默认不限频。
friend.request_rate_limit 30
##如果搜索电话号码,24小时内搜索错误号码几次就不再允许电话号码搜素。防止有人遍历搜索电话号码
friend.search_mobile_empty_rate_limit 5
##如果搜索用户,24小时内搜索次数。防止有人遍历用户名或者用户ID乱加好友。另外可以禁止ID搜索friend.disable_user_id_search
friend.search_rate_limit 100
##请求添加机器人为好友时,机器人是否自动接受,默认为true
friend.robot_auto_accept true
@@ -267,6 +273,16 @@ group.enable_mark_deletion true
## 销毁用户时,用户信息会被清空,deleted字段设置为1,这个开关控制是否保留用户昵称,默认为true。
user.keep_display_name_when_destroy true
## 销毁用户时deleted字段设置为1,这个开关控制是否保留其他信息,默认是false。
user.keep_full_info_when_destroy false
## 销毁用户时,如果user.keep_full_info_when_destroy为true,会保留所有信息,这个开关控制是否保留这个用户信息的电话号码,默认为false。
## 当保留所有信息且保留电话号码时,用户如果再注册会用到原来的UID,能够看到原来用户的消息,需要考虑一下是否让已删除用户再次注册登录看到之前的消息。
user.keep_mobile_when_destroy false
## 销毁用户时是否保留归属于这个用户的所有消息记录,默认为false。
user.keep_messages_when_destroy false
# 好友/好友请求/用户设置 这三类数据同步的最大条目数。之前是客户第一次登录时,会把所有的对应数据一次下载到客户端,但如果有特别多的信息,会导致无法同步到客户端,
# 因此需要分段多次同步,此开关定义了每次同步的数据的条数。此需要客户端支持,客户端SDK在2021.5.25日后支持此功能。如果确认所有客户端都在这个日志之后才可以打开此设置。
#sync.data_part_size 1000
@@ -318,6 +334,13 @@ qiniu.bucket_portrait_name storage
qiniu.bucket_portrait_domain http://cdn2.wildfirechat.cn
qiniu.bucket_favorite_name storage
qiniu.bucket_favorite_domain http://cdn2.wildfirechat.cn
## custom的桶是给客户预留的,客户可以上传自己的文件到这3个桶中,野火不会用到这几个桶。如果不需要,可以忽略这几个配置
qiniu.bucket_custom1_name temp1
qiniu.bucket_custom1_domain http://temp1.wildfirechat.cn
qiniu.bucket_custom2_name temp2
qiniu.bucket_custom2_domain http://temp2.wildfirechat.cn
qiniu.bucket_custom3_name temp3
qiniu.bucket_custom3_domain http://temp3.wildfirechat.cn
##媒体类型分类
#Media_Type_GENERAL = 0,
+1
View File
@@ -0,0 +1 @@
ALTER TABLE `t_user_session` ADD COLUMN `_ip` varchar(40) DEFAULT '';
+1
View File
@@ -0,0 +1 @@
CREATE INDEX `user_gid_type_index` ON `t_group_member` (`_gid`, `_type`);
+13
View File
@@ -0,0 +1,13 @@
DROP TABLE IF EXISTS `t_conference`;
CREATE TABLE `t_conference` (
`_id` varchar(64) NOT NULL PRIMARY KEY,
`_des` varchar(64) NOT NULL,
`_pin` varchar(16) NOT NULL,
`_max_publishers` int(11) NOT NULL DEFAULT 0,
`_bitrate` int(11) NOT NULL DEFAULT 0,
`_advance` tinyint NOT NULL DEFAULT 0,
`_recording` tinyint NOT NULL DEFAULT 0,
`_create_dt` bigint(20) NOT NULL
);
+17
View File
@@ -0,0 +1,17 @@
DROP TABLE IF EXISTS `t_join_group_request`;
CREATE TABLE `t_join_group_request` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`_uid` varchar(64) NOT NULL,
`_gid` varchar(64) NOT NULL,
`_mid` varchar(64) NOT NULL,
`_request_uid` varchar(64) NOT NULL,
`_accept_uid` varchar(64) DEFAULT NULL,
`_reason` TEXT DEFAULT NULL,
`_extra` TEXT DEFAULT NULL,
`_status` tinyint NOT NULL DEFAULT 0,
`_dt` bigint(20) NOT NULL,
`_read_status` tinyint DEFAULT 0,
UNIQUE INDEX `join_group_request_key_index` (`_uid` DESC, `_gid` DESC, `_mid` DESC, `_request_uid` DESC),
INDEX `join_group_request_gm_index` (`_gid` DESC, `_mid` DESC),
INDEX `join_group_request_sync_index` (`_uid` DESC, `_dt` DESC)
);
+1
View File
@@ -0,0 +1 @@
ALTER TABLE `t_user_session` ADD COLUMN `_ip` varchar(40) DEFAULT '';
+1
View File
@@ -0,0 +1 @@
CREATE INDEX `user_gid_type_index` ON `t_group_member` (`_gid`, `_type`);
+16
View File
@@ -0,0 +1,16 @@
DROP TABLE IF EXISTS `t_conference`;
CREATE TABLE `t_conference` (
`_id` varchar(64) NOT NULL PRIMARY KEY,
`_des` varchar(64) NOT NULL,
`_pin` varchar(16) NOT NULL,
`_max_publishers` int(11) NOT NULL DEFAULT 0,
`_bitrate` int(11) NOT NULL DEFAULT 0,
`_advance` tinyint NOT NULL DEFAULT 0,
`_recording` tinyint NOT NULL DEFAULT 0,
`_create_dt` bigint(20) NOT NULL
)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_unicode_ci;
@@ -0,0 +1,21 @@
DROP TABLE IF EXISTS `t_join_group_request`;
CREATE TABLE `t_join_group_request` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`_uid` varchar(64) NOT NULL,
`_gid` varchar(64) NOT NULL,
`_mid` varchar(64) NOT NULL,
`_request_uid` varchar(64) NOT NULL,
`_accept_uid` varchar(64) DEFAULT NULL,
`_reason` TEXT DEFAULT NULL,
`_extra` TEXT DEFAULT NULL,
`_status` tinyint NOT NULL DEFAULT 0,
`_dt` bigint(20) NOT NULL,
`_read_status` tinyint DEFAULT 0,
UNIQUE INDEX `join_group_request_key_index` (`_uid` DESC, `_gid` DESC, `_mid` DESC, `_request_uid` DESC),
INDEX `join_group_request_gm_index` (`_gid` DESC, `_mid` DESC),
INDEX `join_group_request_sync_index` (`_uid` DESC, `_dt` DESC)
)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_unicode_ci;
+1 -55
View File
@@ -5,7 +5,7 @@
<relativePath>../</relativePath>
<artifactId>wildfirechat-parent</artifactId>
<groupId>cn.wildfirechat</groupId>
<version>1.3.9</version>
<version>1.4.3</version>
</parent>
<artifactId>moquette-broker</artifactId>
@@ -211,60 +211,6 @@
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<includes>
<include>**/*Test.java</include>
</includes>
</configuration>
</plugin>
<!-- Generate the test-jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Includes to generate OSGi headers -->
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<executions>
<execution>
<id>bundle-manifest</id>
<phase>process-classes</phase>
<goals>
<goal>manifest</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
@@ -11,6 +11,7 @@ package com.xiaoleilu.loServer.action;
import cn.wildfirechat.proto.ProtoConstants;
import cn.wildfirechat.proto.WFCMessage;
import com.google.protobuf.InvalidProtocolBufferException;
import com.hazelcast.util.StringUtil;
import com.xiaoleilu.loServer.annotation.HttpMethod;
import com.xiaoleilu.loServer.annotation.Route;
import com.xiaoleilu.loServer.handler.Request;
@@ -28,7 +29,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.wildfirechat.common.ErrorCode;
import java.net.InetSocketAddress;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.Executor;
@Route("/route")
@@ -111,6 +114,12 @@ public class RouteAction extends Action {
WFCMessage.IMHttpWrapper wrapper = WFCMessage.IMHttpWrapper.parseFrom(bytes);
String token = wrapper.getToken();
String userId = Tokenor.getUserId(token.getBytes());
String remote = ((InetSocketAddress) ctx.channel().remoteAddress())
.getAddress().getHostAddress();
String ip = computeRealIp(request.getHeaders(), remote);
LOG.info("RouteAction token={}, userId={}", token, userId);
if (userId == null) {
sendResponse(response, ErrorCode.ERROR_CODE_TOKEN_ERROR, null);
@@ -119,6 +128,8 @@ public class RouteAction extends Action {
@Override
public void onSuccess(byte[] result) {
sendResponse(response, null, result);
//save ip after success response.
sessionsStore.updateSessionIp(userId, wrapper.getClientId(), ip);
}
@Override
@@ -147,6 +158,20 @@ public class RouteAction extends Action {
return true;
}
private String computeRealIp(Map<String, String> h, String remote) {
String xff = h.get("X-Forwarded-For");
if (xff != null && !xff.isEmpty() && !"unknown".equalsIgnoreCase(xff)) {
int idx = xff.indexOf(',');
String first = (idx > 0 ? xff.substring(0, idx) : xff).trim();
return first;
}
String xri = h.get("X-Real-IP");
if (xri != null && !xri.isEmpty() && !"unknown".equalsIgnoreCase(xri)) {
return xri;
}
return remote;
}
private void sendResponse(Response response, ErrorCode errorCode, byte[] contents) {
response.setStatus(HttpResponseStatus.OK);
if (contents == null) {
@@ -24,6 +24,8 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@@ -213,7 +215,7 @@ public class UploadFileAction extends Action {
return false;
}
remoteFileName = getSafeFileName(remoteFileName);
String remoteFileExt = "";
if (remoteFileName.lastIndexOf(".") == -1) {
@@ -339,6 +341,15 @@ public class UploadFileAction extends Action {
return true;
}
private static String getSafeFileName(String originalFilename) {
// Paths.get() 会解析路径,getFileName() 只取最后一部分(纯文件名)
Path filenamePath = Paths.get(originalFilename.trim());
String safeFilename = filenamePath.getFileName().toString();
// 额外过滤特殊字符(可选,根据业务需要)
safeFilename = safeFilename.replaceAll("[\\\\/:*?\"<>|]", "_");
return safeFilename.isEmpty() ? "default_file_" + System.currentTimeMillis() : safeFilename;
}
public static void put(File file, long pos, byte[] data) throws Exception {
RandomAccessFile raf = null;
try {
@@ -82,6 +82,13 @@ public final class BrokerConstants {
public static final String QINIU_BUCKET_PORTRAIT_DOMAIN = "qiniu.bucket_portrait_domain";
public static final String QINIU_BUCKET_FAVORITE_NAME= "qiniu.bucket_favorite_name";
public static final String QINIU_BUCKET_FAVORITE_DOMAIN = "qiniu.bucket_favorite_domain";
public static final String QINIU_BUCKET_CUSTOM1_NAME= "qiniu.bucket_custom1_name";
public static final String QINIU_BUCKET_CUSTOM1_DOMAIN = "qiniu.bucket_custom1_domain";
public static final String QINIU_BUCKET_CUSTOM2_NAME= "qiniu.bucket_custom2_name";
public static final String QINIU_BUCKET_CUSTOM2_DOMAIN = "qiniu.bucket_custom2_domain";
public static final String QINIU_BUCKET_CUSTOM3_NAME= "qiniu.bucket_custom3_name";
public static final String QINIU_BUCKET_CUSTOM3_DOMAIN = "qiniu.bucket_custom3_domain";
public static final String FILE_STORAGE_ROOT = "local.media.storage.root";
public static final String FILE_STORAGE_REMOTE_SERVER_URL = "local.media.storage.remote_server_url";
@@ -190,6 +197,8 @@ public final class BrokerConstants {
public static final String FRIEND_Reject_Request_Duration = "friend.reject_request_duration";
public static final String FRIEND_Request_Expiration_Duration = "friend.request_expiration_duration";
public static final String FRIEND_Request_Rate_Limit = "friend.request_rate_limit";
public static final String FRIEND_Search_Mobile_Empty_Rate_Limit = "friend.search_mobile_empty_rate_limit";
public static final String FRIEND_Search_Rate_Limit = "friend.search_rate_limit";
public static final String FRIEND_Request_Robot_Auto_Accept = "friend.robot_auto_accept";
@@ -213,6 +222,9 @@ public final class BrokerConstants {
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";
public static final String USER_KEEP_FULL_INFO_WHEN_DESTROY = "user.keep_full_info_when_destroy";
public static final String USER_KEEP_MOBILE_WHEN_DESTROY = "user.keep_mobile_when_destroy";
public static final String USER_KEEP_MESSAGES_WHEN_DESTROY = "user.keep_messages_when_destroy";
public static final String SYNC_Data_Part_Size = "sync.data_part_size";
@@ -32,7 +32,6 @@ public class GetMediaUploadTokenHandler extends IMHandler<WFCMessage.GetUploadTo
if (MediaServerConfig.USER_QINIU) {
Auth auth = Auth.create(MediaServerConfig.QINIU_ACCESS_KEY, MediaServerConfig.QINIU_SECRET_KEY);
String bucketName;
String bucketDomain;
switch (type) {
@@ -72,6 +71,18 @@ public class GetMediaUploadTokenHandler extends IMHandler<WFCMessage.GetUploadTo
bucketName = MediaServerConfig.QINIU_BUCKET_MOMENTS_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_MOMENTS_DOMAIN;
break;
case 9:
bucketName = MediaServerConfig.QINIU_BUCKET_CUSTOM1_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_CUSTOM1_DOMAIN;
break;
case 10:
bucketName = MediaServerConfig.QINIU_BUCKET_CUSTOM2_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_CUSTOM2_DOMAIN;
break;
case 11:
bucketName = MediaServerConfig.QINIU_BUCKET_CUSTOM3_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_CUSTOM3_DOMAIN;
break;
default:
bucketName = MediaServerConfig.QINIU_BUCKET_GENERAL_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_GENERAL_DOMAIN;
@@ -77,6 +77,18 @@ public class GetQiniuUploadTokenHandler extends IMHandler<Byte> {
bucketName = MediaServerConfig.QINIU_BUCKET_MOMENTS_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_MOMENTS_DOMAIN;
break;
case 9:
bucketName = MediaServerConfig.QINIU_BUCKET_CUSTOM1_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_CUSTOM1_DOMAIN;
break;
case 10:
bucketName = MediaServerConfig.QINIU_BUCKET_CUSTOM2_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_CUSTOM2_DOMAIN;
break;
case 11:
bucketName = MediaServerConfig.QINIU_BUCKET_CUSTOM3_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_CUSTOM3_DOMAIN;
break;
default:
bucketName = MediaServerConfig.QINIU_BUCKET_GENERAL_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_GENERAL_DOMAIN;
@@ -45,20 +45,20 @@ public class HandleFriendRequestHandler extends IMHandler<WFCMessage.HandleFrien
contentBuilder.setType(92);
builder = WFCMessage.Message.newBuilder();
builder.setFromUser(request.getTargetUid());
builder.setConversation(WFCMessage.Conversation.newBuilder().setTarget(fromUser).setLine(0).setType(ProtoConstants.ConversationType.ConversationType_Private).build());
builder.setFromUser(fromUser);
builder.setConversation(WFCMessage.Conversation.newBuilder().setTarget(request.getTargetUid()).setLine(0).setType(ProtoConstants.ConversationType.ConversationType_Private).build());
builder.setContent(contentBuilder);
builder.setServerTimestamp(++timestamp);
messageId = MessageShardingUtil.generateId();
builder.setMessageId(messageId);
saveAndPublish(request.getTargetUid(), null, builder.build(), requestSourceType);
saveAndPublish(fromUser, null, builder.build(), requestSourceType);
contentBuilder.setType(93);
builder.setContent(contentBuilder);
messageId = MessageShardingUtil.generateId();
builder.setMessageId(messageId);
builder.setServerTimestamp(++timestamp);
saveAndPublish(request.getTargetUid(), null, builder.build(), requestSourceType);
saveAndPublish(fromUser, null, builder.build(), requestSourceType);
} catch (Exception e) {
e.printStackTrace();
}
@@ -15,13 +15,18 @@ import io.netty.buffer.ByteBuf;
import cn.wildfirechat.common.ErrorCode;
import win.liyufan.im.IMTopic;
import java.util.ArrayList;
import java.util.List;
@Handler(IMTopic.UserSearchTopic)
public class UserSearchHandler extends IMHandler<WFCMessage.SearchUserRequest> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.SearchUserRequest request, Qos1PublishHandler.IMCallback callback) {
List<WFCMessage.User> users = m_messagesStore.searchUser(request.getKeyword(), request.getFuzzy(), request.getType(), request.getPage());
List<WFCMessage.User> users = new ArrayList<>();
ErrorCode errorCode = m_messagesStore.searchUser(fromUser, request.getKeyword(), request.getFuzzy(), request.getType(), request.getPage(), users);
if(errorCode != ErrorCode.ERROR_CODE_SUCCESS) {
return errorCode;
}
WFCMessage.SearchUserResult.Builder builder = WFCMessage.SearchUserResult.newBuilder();
builder.addAllEntry(users);
byte[] data = builder.build().toByteArray();
@@ -1832,6 +1832,31 @@ public class DatabaseStore {
});
}
void updateSessionIp(String uid, String cid, String ip) {
mScheduler.execute(()->{
Connection connection = null;
PreparedStatement statement = null;
try {
connection = DBUtil.getConnection();
String sql = "update t_user_session set _ip = ? where `_uid` = ? and `_cid` = ?";
statement = connection.prepareStatement(sql);
int index = 1;
statement.setString(index++, ip);
statement.setString(index++, uid);
statement.setString(index++, cid);
int c = statement.executeUpdate();
LOG.info("Update rows {}", c);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Utility.printExecption(LOG, e, RDBS_Exception);
} finally {
DBUtil.closeDB(connection, statement);
}
});
}
void clearMultiEndpoint(String uid, String clientId, int platform) {
LOG.info("clearMultiEndpoint {}, {}", uid, clientId);
Connection connection = null;
@@ -58,6 +58,8 @@ import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static cn.wildfirechat.common.IMExceptionEvent.EventType.EVENT_CALLBACK_Exception;
import static cn.wildfirechat.proto.ProtoConstants.ChannelState.*;
@@ -157,6 +159,8 @@ public class MemoryMessagesStore implements IMessagesStore {
private long mFriendRejectDuration = 30 * 24 * 60 * 60 * 1000;
private long mFriendRequestExpiration = 7 * 24 * 60 * 60 * 1000;
private RateLimiter mFriendRateLimiter;
private RateLimiter mFriendSearchEmpthMobileRateLimiter;
private RateLimiter mFriendSearchRateLimiter;
private boolean mFriendRobotAutoAccept = true;
private long mPushExpiredTimes = 604800000L;
@@ -202,6 +206,10 @@ public class MemoryMessagesStore implements IMessagesStore {
private int mGroupForbiddenClientOperation;
private int mSyncDataPartSize = 0;
private boolean keepDisplayNameWhenDestroyUser = true;
private boolean keepFullInfoWhenDestroyUser = false;
private boolean keepMobileWhenDestroyUser = false;
private boolean keepMessagesWhenDestroyUser = false;
private String mRecallForwardUrl = null;
private boolean mBroadcastTargetFromUserTable = false;
@@ -332,7 +340,7 @@ public class MemoryMessagesStore implements IMessagesStore {
printMissConfigLog(FRIEND_Disable_NickName_Search, mDisableNicknameSearch + "");
}
try {
mDisableUserIdSearch = Boolean.parseBoolean(m_Server.getConfig().getProperty(BrokerConstants.FRIEND_Disable_UserId_Search, "true"));
mDisableUserIdSearch = Boolean.parseBoolean(m_Server.getConfig().getProperty(BrokerConstants.FRIEND_Disable_UserId_Search, "false"));
} catch (Exception e) {
}
@@ -376,6 +384,21 @@ public class MemoryMessagesStore implements IMessagesStore {
}
} catch (Exception e) {
}
try {
int rateLimit = Integer.parseInt(m_Server.getConfig().getProperty(FRIEND_Search_Mobile_Empty_Rate_Limit, "0"));
if(rateLimit > 0) {
mFriendSearchEmpthMobileRateLimiter = new RateLimiter(86400, rateLimit);
}
} catch (Exception e) {
}
try {
int rateLimit = Integer.parseInt(m_Server.getConfig().getProperty(FRIEND_Search_Rate_Limit, "0"));
if(rateLimit > 0) {
mFriendSearchRateLimiter = new RateLimiter(86400, rateLimit);
}
} catch (Exception e) {
}
try {
mFriendRobotAutoAccept = Boolean.parseBoolean(m_Server.getConfig().getProperty(BrokerConstants.FRIEND_Request_Robot_Auto_Accept, "true"));
@@ -600,6 +623,17 @@ public class MemoryMessagesStore implements IMessagesStore {
} catch (Exception e) {
}
try {
keepFullInfoWhenDestroyUser = "true".equals(server.getConfig().getProperty(USER_KEEP_FULL_INFO_WHEN_DESTROY));
} catch (Exception e) {}
try {
keepMobileWhenDestroyUser = "true".equals(server.getConfig().getProperty(USER_KEEP_MOBILE_WHEN_DESTROY));
} catch (Exception e) {}
try {
keepMessagesWhenDestroyUser = "true".equals(server.getConfig().getProperty(USER_KEEP_MESSAGES_WHEN_DESTROY));
} catch (Exception e) {}
try {
@@ -2758,8 +2792,9 @@ public class MemoryMessagesStore implements IMessagesStore {
} finally {
mWriteLock.unlock();
}
databaseStore.clearUserMessage(userId);
if(!keepMessagesWhenDestroyUser) {
databaseStore.clearUserMessage(userId);
}
}
@Override
@@ -3137,37 +3172,29 @@ public class MemoryMessagesStore implements IMessagesStore {
IMap<String, WFCMessage.User> mUserMap = hzInstance.getMap(USERS);
WFCMessage.User us = mUserMap.get(userId);
if (us != null) {
if (keepDisplayNameWhenDestroyUser) {
us = WFCMessage.User.newBuilder()
.setUid(userId)
.setUpdateDt(System.currentTimeMillis())
.setName(userId)
.setDeleted(1)
.clearAddress()
.clearCompany()
.clearEmail()
.clearExtra()
.clearMobile()
.clearPortrait()
.clearSocial()
.build();
WFCMessage.User.Builder builder = WFCMessage.User.newBuilder().setUpdateDt(System.currentTimeMillis()).setDeleted(1);
if(keepFullInfoWhenDestroyUser) {
if(!keepMobileWhenDestroyUser) {
builder.clearMobile();
}
} else {
us = WFCMessage.User.newBuilder()
.setUid(userId)
.setUpdateDt(System.currentTimeMillis())
builder.setUid(userId)
.setName(userId)
.setDeleted(1)
.clearDisplayName()
.clearAddress()
.clearCompany()
.clearEmail()
.clearExtra()
.clearMobile()
.clearPortrait()
.clearSocial()
.build();
.clearGender()
.clearSocial();
if (!keepDisplayNameWhenDestroyUser) {
builder.clearDisplayName();
}
}
us = builder.build();
try {
databaseStore.updateUser(us);
} catch (Exception e) {
@@ -3176,8 +3203,8 @@ public class MemoryMessagesStore implements IMessagesStore {
}
mUserMap.put(userId, us);
}
}
@Override
public void updateUserInfo(WFCMessage.User user) throws Exception {
HazelcastInstance hzInstance = m_Server.getHazelcastInstance();
@@ -3222,10 +3249,42 @@ public class MemoryMessagesStore implements IMessagesStore {
return databaseStore.getAllUsers(count, offset);
}
// 电话号码校验正则表达式(支持中国大陆手机号和固话)
private static final String PHONE_REGEX = "^\\s*" + // 允许开头空白
"(?:" +
"(1[0-9])\\d{9}" +
"|" +
"((0\\d{2,3})|(\\(0\\d{2,3}\\)))" +
"[-\\s.]?" +
"\\d{7,8}" +
"|" +
"\\d{7,8}" +
")\\s*$";
private static final Pattern PHONE_PATTERN = Pattern.compile(PHONE_REGEX);
private static final Pattern PHONE_PART_PATTERN = Pattern.compile("^1\\d{0,10}$");
public static boolean isPhoneNumber(String phone) {
if (phone == null || phone.trim().isEmpty()) {
return false;
}
Matcher matcher = PHONE_PATTERN.matcher(phone);
return matcher.matches();
}
public static boolean isPhoneNumberPart(String str) {
if (str == null || str.trim().isEmpty()) {
return false;
}
Matcher matcher = PHONE_PART_PATTERN.matcher(str);
return matcher.matches();
}
@Override
public List<WFCMessage.User> searchUser(String keyword, int searchType, int userType, int page) {
public ErrorCode searchUser(String userId, String keyword, int searchType, int userType, int page, List<WFCMessage.User> users) {
if (mDisableSearch) {
return new ArrayList<>();
return ErrorCode.ERROR_CODE_NOT_IMPLEMENT;
}
if (mDisableNicknameSearch && searchType == ProtoConstants.SearchUserType.SearchUserType_General) {
@@ -3241,10 +3300,29 @@ public class MemoryMessagesStore implements IMessagesStore {
}
if(mDisableUserIdSearch && searchType == ProtoConstants.SearchUserType.SearchUserType_UserId) {
return new ArrayList<>();
return ErrorCode.ERROR_CODE_NOT_IMPLEMENT;
}
return databaseStore.searchUserFromDB(keyword, searchType, userType, page);
if(mFriendSearchRateLimiter != null && !isPhoneNumberPart(keyword)) {
//非电话号码,允许多少次搜索。
if(!mFriendSearchRateLimiter.isGranted(userId)) {
LOG.error("User {} search user mobile over frequency, keyword {}, searchType {}", userId, keyword, searchType);
return ErrorCode.ERROR_CODE_OVER_FREQUENCY;
}
}
List<WFCMessage.User> matchedUsers = databaseStore.searchUserFromDB(keyword, searchType, userType, page);
if(mFriendSearchEmpthMobileRateLimiter != null && matchedUsers.isEmpty() && isPhoneNumber(keyword)) {
//查电话号码为空
if(!mFriendSearchEmpthMobileRateLimiter.isGranted(userId)) {
LOG.error("User {} search user over frequency, keyword {}, searchType {}", userId, keyword, searchType);
return ErrorCode.ERROR_CODE_OVER_FREQUENCY;
}
}
users.addAll(matchedUsers);
return ErrorCode.ERROR_CODE_SUCCESS;
}
@Override
@@ -61,6 +61,7 @@ public class MemorySessionStore implements ISessionsStore {
private int deleted;
private boolean pullHistoryMsg;
private String ip;
public int getDeleted() {
return deleted;
@@ -159,6 +160,14 @@ public class MemorySessionStore implements ISessionsStore {
}
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
private int pushType;
private int platform;
@@ -544,6 +553,15 @@ public class MemorySessionStore implements ISessionsStore {
return session.clientSession;
}
@Override
public void updateSessionIp(String username, String clientID, String ip) {
Session session = getSession(clientID);
if(session != null && session.getDeleted() == 0) {
session.setIp(ip);
databaseStore.updateSessionIp(username, clientID, ip);
}
}
@Override
public Session sessionForClientAndUser(String username, String clientID) {
Session session = sessions.get(clientID);
@@ -331,6 +331,14 @@ public class Server {
MediaServerConfig.QINIU_BUCKET_FAVORITE_NAME = config.getProperty(BrokerConstants.QINIU_BUCKET_FAVORITE_NAME);
MediaServerConfig.QINIU_BUCKET_FAVORITE_DOMAIN = config.getProperty(BrokerConstants.QINIU_BUCKET_FAVORITE_DOMAIN);
MediaServerConfig.QINIU_BUCKET_CUSTOM1_NAME = config.getProperty(BrokerConstants.QINIU_BUCKET_CUSTOM1_NAME);
MediaServerConfig.QINIU_BUCKET_CUSTOM1_DOMAIN = config.getProperty(BrokerConstants.QINIU_BUCKET_CUSTOM1_DOMAIN);
MediaServerConfig.QINIU_BUCKET_CUSTOM2_NAME = config.getProperty(BrokerConstants.QINIU_BUCKET_CUSTOM2_NAME);
MediaServerConfig.QINIU_BUCKET_CUSTOM2_DOMAIN = config.getProperty(BrokerConstants.QINIU_BUCKET_CUSTOM2_DOMAIN);
MediaServerConfig.QINIU_BUCKET_CUSTOM3_NAME = config.getProperty(BrokerConstants.QINIU_BUCKET_CUSTOM3_NAME);
MediaServerConfig.QINIU_BUCKET_CUSTOM3_DOMAIN = config.getProperty(BrokerConstants.QINIU_BUCKET_CUSTOM3_DOMAIN);
MediaServerConfig.SERVER_IP = getServerIp(config);
@@ -23,7 +23,14 @@ public class MediaServerConfig {
public static String QINIU_BUCKET_PORTRAIT_DOMAIN;
public static String QINIU_BUCKET_FAVORITE_NAME;
public static String QINIU_BUCKET_FAVORITE_DOMAIN;
public static String QINIU_BUCKET_CUSTOM1_NAME;
public static String QINIU_BUCKET_CUSTOM1_DOMAIN;
public static String QINIU_BUCKET_CUSTOM2_NAME;
public static String QINIU_BUCKET_CUSTOM2_DOMAIN;
public static String QINIU_BUCKET_CUSTOM3_NAME;
public static String QINIU_BUCKET_CUSTOM3_DOMAIN;
public static String SERVER_IP = "localhost";
public static int HTTP_SERVER_PORT = 8080;
public static String FILE_STROAGE_ROOT = "fs";
@@ -154,7 +154,7 @@ public interface IMessagesStore {
WFCMessage.User getUserInfoByName(String name);
WFCMessage.User getUserInfoByMobile(String mobile);
List<WFCMessage.User> getUserInfosByEmail(String email);
List<WFCMessage.User> searchUser(String keyword, int searchType, int userType, int page);
ErrorCode searchUser(String userId, String keyword, int searchType, int userType, int page, List<WFCMessage.User> users);
List<WFCMessage.User> getUserInfoList(int count, int offset);
@@ -43,7 +43,7 @@ public interface ISessionsStore {
ErrorCode loadActiveSession(String username, String clientID);
ClientSession updateExistSession(String username, String clientID, WFCMessage.RouteRequest endpoint, boolean cleanSession);
void updateSessionIp(String username, String clientID, String ip);
Session getSession(String clientID);
void cleanDuplatedToken(String cid, int pushType, String token, boolean isVoip, String packageName);
@@ -230,6 +230,7 @@ public class MessagesPublisher {
}
}
boolean unreadCountIncreased = false;
for (Session targetSession : sessions) {
//超过7天不活跃的用户忽略
if(System.currentTimeMillis() - targetSession.getLastActiveTime() > m_messagesStore.getPushExpiredTimes()) {
@@ -314,8 +315,9 @@ public class MessagesPublisher {
}
if (!StringUtil.isNullOrEmpty(pushContent) || messageContentType == 400) {
if (!isConvSilent && (persistFlag & 0x02) > 0) {
if (!isConvSilent && (persistFlag & 0x02) > 0 && !unreadCountIncreased) {
m_messagesStore.increaseUnreceivedMsgCount(user);
unreadCountIncreased = true;
}
}
}
@@ -284,7 +284,7 @@ public class ProtocolProcessor {
sessionstatus = 0;
}
userOnlineStatus.sessions.add(new OutputCheckUserOnline.Session(userId, session.getClientID(), session.getPlatform(), sessionstatus, session.getLastActiveTime(), session.getAppName()));
userOnlineStatus.sessions.add(new OutputCheckUserOnline.Session(userId, session.getClientID(), session.getPlatform(), sessionstatus, session.getLastActiveTime(), session.getAppName(), session.getIp()));
}
HttpUtils.httpJsonPost(mUserOnlineStatusCallback, GsonUtil.gson.toJson(userOnlineStatus), HttpUtils.HttpPostType.POST_TYPE_User_Online_Event_Callback);
@@ -141,7 +141,7 @@ public class Qos1PublishHandler extends QosPublishHandler {
status = 0;
}
out.addSession(userId, session.getClientID(), session.getPlatform(), status, session.getLastActiveTime(), session.getAppName());
out.addSession(userId, session.getClientID(), session.getPlatform(), status, session.getLastActiveTime(), session.getAppName(), session.getIp());
}
callback.onRouteHandled(GsonUtil.gson.toJson(out).getBytes());
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>wildfirechat-parent</artifactId>
<groupId>cn.wildfirechat</groupId>
<version>1.3.9</version>
<version>1.4.3</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -114,6 +114,9 @@ public interface APIPath {
String Put_System_Setting = "/admin/system/put_setting";
String GET_CUSTOMER = "/admin/customer";
String Health = "/admin/health";
String Get_Conversation_Files = "/admin/file/conversation_files";
String Get_User_Files = "/admin/file/user_files";
String Get_Message_File = "/admin/file/message_file";
String Conference_List = "/admin/conference/list";
String Conference_Exist = "/admin/conference/exist";
+30
View File
@@ -0,0 +1,30 @@
/*
* 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 java.util.ArrayList;
import java.util.List;
public class FilesPojo {
public int total;
public List<FilePojo> files;
public static class FilePojo {
public long messageId;
public String sender;
public int conversationType;
public String target;
public int line;
public String name;
public String url;
public int size;
public int downloadCount;
public long timestamp;
}
}
@@ -0,0 +1,11 @@
package cn.wildfirechat.pojos;
public class GetConversationFilesPojo {
public int conversationType;
public String target;
public int line;
public String userId;
public int offset;
public boolean desc;
public int count;
}
@@ -7,6 +7,7 @@ public class GetOnlineUserResult {
public String userId;
public String clientId;
public int platform;
public String ip;
}
public ArrayList<GetOnlineUserResult.UserClient> userClients;
@@ -0,0 +1,8 @@
package cn.wildfirechat.pojos;
public class GetUserFilesPojo {
public String userId;
public int offset;
public boolean desc;
public int count;
}
@@ -0,0 +1,6 @@
package cn.wildfirechat.pojos;
public class InputCountOffset {
public int count;
public int offset;
}
@@ -25,6 +25,7 @@ public class InputOutputUserInfo {
private String social;
private String extra;
private int type;
private int deleted;
private long updateDt;
public static InputOutputUserInfo fromPbUser(WFCMessage.User pbUser) {
@@ -42,6 +43,7 @@ public class InputOutputUserInfo {
inputCreateUser.extra = pbUser.getExtra();
inputCreateUser.type = pbUser.getType();
inputCreateUser.updateDt = pbUser.getUpdateDt();
inputCreateUser.deleted = pbUser.getDeleted();
return inputCreateUser;
}
@@ -77,6 +79,7 @@ public class InputOutputUserInfo {
newUserBuilder.setExtra(getExtra());
newUserBuilder.setGender(gender);
newUserBuilder.setType(type);
newUserBuilder.setDeleted(deleted);
newUserBuilder.setUpdateDt(System.currentTimeMillis());
return newUserBuilder.build();
@@ -185,4 +188,24 @@ public class InputOutputUserInfo {
public void setType(int type) {
this.type = type;
}
public int getDeleted() {
return deleted;
}
public void setDeleted(int deleted) {
this.deleted = deleted;
}
@Override
public String toString() {
return "{" +
"userId='" + userId + '\'' +
", name='" + name + '\'' +
", displayName='" + displayName + '\'' +
", portrait='" + portrait + '\'' +
", mobile='" + mobile + '\'' +
", updateDt=" + updateDt +
'}';
}
}
@@ -0,0 +1,5 @@
package cn.wildfirechat.pojos;
public class LongPojo {
public long value;
}
@@ -20,22 +20,24 @@ public class OutputCheckUserOnline {
public int status; //0 online, 1 have session offline
public long lastSeen;
public String packageName;
public String ip;
public Session() {
}
public Session(String clientId, String userId, int platform, int status, long lastSeen, String packageName) {
public Session(String clientId, String userId, int platform, int status, long lastSeen, String packageName, String ip) {
this.clientId = clientId;
this.userId = userId;
this.platform = platform;
this.status = status;
this.lastSeen = lastSeen;
this.packageName = packageName;
this.ip = ip;
}
}
public void addSession(String userId, String clientId, int platform, int status, long lastSeen, String packageName) {
Session session = new Session(clientId, userId, platform, status, lastSeen, packageName);
public void addSession(String userId, String clientId, int platform, int status, long lastSeen, String packageName, String ip) {
Session session = new Session(clientId, userId, platform, status, lastSeen, packageName, ip);
sessions.add(session);
}
@@ -2,11 +2,8 @@ package cn.wildfirechat.pojos;
public class PojoConferenceInfo {
public String roomId;
public String serverId;
public String description;
public int max_publishers;
public int num_publishers;
public int bitrate;
public boolean advance;
public boolean recording;
}
+1 -1
View File
@@ -6,7 +6,7 @@
<!--<relativePath>../pom.xml</relativePath>-->
<artifactId>wildfirechat-parent</artifactId>
<groupId>cn.wildfirechat</groupId>
<version>1.3.9</version>
<version>1.4.3</version>
</parent>
<artifactId>distribution</artifactId>
@@ -190,8 +190,8 @@ friend.disable_search false
##禁止按照昵称搜索用户。
friend.disable_nick_name_search false
##禁止按照用户id搜索用户,默认为true。
friend.disable_user_id_search true
##禁止按照用户id搜索用户,默认为false。
friend.disable_user_id_search false
##禁止发送好友邀请,通过server api添加好友不受此限制(force参数需要为true)
friend.disable_friend_request false
@@ -206,7 +206,13 @@ friend.reject_request_duration 2592000000
friend.request_expiration_duration 604800000
##好友请求限制频率,一个用户24小时之内允许请求好友的次数,默认不限频。
#friend.request_rate_limit 30
friend.request_rate_limit 30
##如果搜索电话号码,24小时内搜索错误号码几次就不再允许电话号码搜素。防止有人遍历搜索电话号码
friend.search_mobile_empty_rate_limit 5
##如果搜索用户,24小时内搜索次数。防止有人遍历用户名或者用户ID乱加好友。另外可以禁止ID搜索friend.disable_user_id_search
friend.search_rate_limit 100
##请求添加机器人为好友时,机器人是否自动接受,默认为true
friend.robot_auto_accept true
@@ -262,6 +268,19 @@ group.enable_mark_deletion true
## 注意,修改本配置不会对已经同步的信息产生影响。
#user.hide_properties 3,4
## 销毁用户时,用户信息会被清空,deleted字段设置为1,这个开关控制是否保留用户昵称,默认为true。
user.keep_display_name_when_destroy true
## 销毁用户时deleted字段设置为1,这个开关控制是否保留其他信息,默认是false。
user.keep_full_info_when_destroy false
## 销毁用户时,如果user.keep_full_info_when_destroy为true,会保留所有信息,这个开关控制是否保留这个用户信息的电话号码,默认为false。
## 当保留所有信息且保留电话号码时,用户如果再注册会用到原来的UID,能够看到原来用户的消息,需要考虑一下是否让已删除用户再次注册登录看到之前的消息。
user.keep_mobile_when_destroy false
## 销毁用户时是否保留归属于这个用户的所有消息记录,默认为false。
user.keep_messages_when_destroy false
# 好友/好友请求/用户设置 这三类数据同步的最大条目数。之前是客户第一次登录时,会把所有的对应数据一次下载到客户端,但如果有特别多的信息,会导致无法同步到客户端,
# 因此需要分段多次同步,此开关定义了每次同步的数据的条数。此需要客户端支持,客户端SDK在2021.5.25日后支持此功能。如果确认所有客户端都在这个日志之后才可以打开此设置。
#sync.data_part_size 1000
@@ -315,6 +334,13 @@ qiniu.bucket_portrait_name storage
qiniu.bucket_portrait_domain http://cdn2.wildfirechat.cn
qiniu.bucket_favorite_name storage
qiniu.bucket_favorite_domain http://cdn2.wildfirechat.cn
## custom的桶是给客户预留的,客户可以上传自己的文件到这3个桶中,野火不会用到这几个桶。如果不需要,可以忽略这几个配置
qiniu.bucket_custom1_name temp1
qiniu.bucket_custom1_domain http://temp1.wildfirechat.cn
qiniu.bucket_custom2_name temp2
qiniu.bucket_custom2_domain http://temp2.wildfirechat.cn
qiniu.bucket_custom3_name temp3
qiniu.bucket_custom3_domain http://temp3.wildfirechat.cn
##媒体类型分类
#Media_Type_GENERAL = 0,
+1 -1
View File
@@ -12,7 +12,7 @@
<artifactId>wildfirechat-parent</artifactId>
<packaging>pom</packaging>
<version>1.3.9</version>
<version>1.4.3</version>
<name>Wildfire Chat</name>
<description>Wildfire Chat Server</description>
<inceptionYear>2019</inceptionYear>
+26
View File
@@ -12,6 +12,32 @@
11. *** 1.3.8版本添加了server api发送消息的限制,限制消息体最大内容不能超过64KB,如果升级请注意业务系统发送消息大小。***
# 更新记录
--------------
Release note 1.4.3:
1. 添加内置存储上传文件文件名有效性检查。
2. 接受好友请求通知的发送者改成接受者发送。
3. 对象存储添加预留类型供扩展使用。
4. 同步专业版数据库表格式。
5. 解决server sdk有轻微内存泄漏的问题。
--------------
Release note 1.4.2:
1. 解决部分情况下Server SDK没有解析出文本消息的问题。
--------------
Release note 1.4.1:
1. 解决移动端和PAD同时存在时推送计数错误问题。
2. 添加配置,当销毁用户时是否销毁用户信息和用户的消息。
3. 添加配置,现在搜索用户的次数。
--------------
Release note 1.4.0:
1. 添加对用户IP来源的记录。
2. 移除无用的plugin,可以在java8环境下编译通过。
3. Server SDK解决某些Java版本下消息没有注册的问题。
4. Server SDK解决解析图片缩略图不存在的错误问题。
5. Server SDK解决发送带引用的消息客户端无法解析的问题。
--------------
Release note 1.3.9:
1. 解决server sdk反复初始化内存泄漏的问题。
+1 -1
View File
@@ -3,7 +3,7 @@
<parent>
<artifactId>wildfirechat-parent</artifactId>
<groupId>cn.wildfirechat</groupId>
<version>1.3.9</version>
<version>1.4.3</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -6,9 +6,12 @@ import cn.wildfirechat.sdk.model.IMResult;
import cn.wildfirechat.sdk.utilities.AdminHttpUtils;
public class ConferenceAdmin {
public static IMResult<PojoConferenceInfoList> listConferences() throws Exception {
public static IMResult<PojoConferenceInfoList> listConferences(int count, int offset) throws Exception {
String path = APIPath.Conference_List;
return AdminHttpUtils.httpJsonPost(path, null, PojoConferenceInfoList.class);
InputCountOffset inputCountOffset = new InputCountOffset();
inputCountOffset.count = count;
inputCountOffset.offset = offset;
return AdminHttpUtils.httpJsonPost(path, inputCountOffset, PojoConferenceInfoList.class);
}
public static IMResult<Boolean> existsConferences(String conferenceId) throws Exception {
@@ -82,6 +82,37 @@ public class GeneralAdmin {
}
//以下仅专业版支持
//如果是单聊会话,target和userId代表会话的2个用户。如果是其他会话userId无意义
public static IMResult<FilesPojo> getConversationFiles(int conversationType, String target, int line, String userId, int offset, boolean desc, int count) throws Exception {
String path = APIPath.Get_Conversation_Files;
GetConversationFilesPojo input = new GetConversationFilesPojo();
input.conversationType = conversationType;
input.target = target;
input.line = line;
input.userId = userId;
input.offset = offset;
input.desc = desc;
input.count = count;
return AdminHttpUtils.httpJsonPost(path, input, FilesPojo.class);
}
public static IMResult<FilesPojo> getUserFiles(String userId, int offset, boolean desc, int count) throws Exception {
String path = APIPath.Get_User_Files;
GetUserFilesPojo input = new GetUserFilesPojo();
input.userId = userId;
input.offset = offset;
input.desc = desc;
input.count = count;
return AdminHttpUtils.httpJsonPost(path, input, FilesPojo.class);
}
public static IMResult<FilesPojo.FilePojo> getFile(long messageId) throws Exception {
String path = APIPath.Get_Message_File;
LongPojo input = new LongPojo();
input.value = messageId;
return AdminHttpUtils.httpJsonPost(path, input, FilesPojo.FilePojo.class);
}
public static IMResult<Void> setConversationTop(String userId, int conversationType, String target, int line, boolean isTop) throws Exception {
String key = conversationType + "-" + line + "-" + target;
String value = isTop?"1":"0";
@@ -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 = true;
private static boolean commercialServer = false;
private static boolean advanceVoip = false;
private static boolean robotMomentsEnabled = false;
private static boolean momentsEnabled = false;
@@ -2146,7 +2146,7 @@ public class Main {
会议相关接口,仅音视频高级版服务支持
*/
public static void testConference() throws Exception {
IMResult<PojoConferenceInfoList> listResult = ConferenceAdmin.listConferences();
IMResult<PojoConferenceInfoList> listResult = ConferenceAdmin.listConferences(100, 0);
if(listResult == null || listResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("get conference list failure");
System.exit(-1);
@@ -2164,7 +2164,7 @@ public class Main {
}
}
listResult = ConferenceAdmin.listConferences();
listResult = ConferenceAdmin.listConferences(100, 0);
if(listResult == null || listResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("get conference list failure");
System.exit(-1);
@@ -2204,7 +2204,7 @@ public class Main {
System.out.println("recording conference success");
}
listResult = ConferenceAdmin.listConferences();
listResult = ConferenceAdmin.listConferences(100, 0);
if(listResult == null || listResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("get conference list failure");
System.exit(-1);
@@ -36,7 +36,9 @@ public class ImageMessageContent extends MediaMessageContent {
public MessagePayload encode() {
MessagePayload payload = super.encode();
payload.setSearchableContent("[图片]");
payload.setBase64edData(Base64.getEncoder().encodeToString(thumbnailBytes));
if(thumbnailBytes != null) {
payload.setBase64edData(Base64.getEncoder().encodeToString(thumbnailBytes));
}
return payload;
}
@@ -45,7 +47,9 @@ public class ImageMessageContent extends MediaMessageContent {
@Override
public void decode(MessagePayload payload) {
super.decode(payload);
thumbnailBytes = Base64.getDecoder().decode(payload.getBase64edData());
if(payload.getBase64edData() != null) {
thumbnailBytes = Base64.getDecoder().decode(payload.getBase64edData());
}
}
@Override
@@ -8,12 +8,39 @@ import cn.wildfirechat.sdk.utilities.ClassUtil;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class MessageContentFactory {
private static final Map<Integer, Class<? extends MessageContent>> contentClassMap = new ConcurrentHashMap<>();
private static List<Class> buildinMessageContents = Arrays.asList(
ArticlesMessageContent.class,
StreamTextGeneratedMessageContent.class,
CallStartMessageContent.class,
StreamTextGeneratingMessageContent.class,
CardMessageContent.class,
MultiCallOngoingMessageContent.class,
TextMessageContent.class,
DeleteMessageContent.class,
NotDeliveredMessageContent.class,
TipNotificationMessageContent.class,
FileMessageContent.class,
PTTSoundMessageContent.class,
TypingMessageContent.class,
ImageMessageContent.class,
RecallMessageContent.class,
UnknownMessageContent.class,
LinkMessageContent.class,
RichNotificationMessageContent.class,
VideoMessageContent.class,
LocationMessageContent.class,
SoundMessageContent.class,
StickerMessageContent.class
);
static {
registerAllMessageContent();
}
@@ -59,6 +86,15 @@ public class MessageContentFactory {
}
private static void registerAllMessageContent() {
try {
for (Class buildinMessageContent : buildinMessageContents) {
MessageContent content = (MessageContent)buildinMessageContent.newInstance();
contentClassMap.put(content.getContentType(), buildinMessageContent);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
for (Class cls : ClassUtil.getAllAssignedClass(MessageContent.class)) {
if(!Modifier.isAbstract(cls.getModifiers())) {
@@ -12,7 +12,7 @@ public class UnknownMessageContent extends MessageContent {
@Override
public int getContentType() {
return ProtoConstants.ContentType.Text;
return ProtoConstants.ContentType.Unknown;
}
@Override
@@ -50,13 +50,18 @@ public class QuoteInfo {
object.put("i", userId);
object.put("n", userDisplayName);
object.put("d", messageDigest);
return object;
JSONObject quote = new JSONObject();
quote.put("quote", object);
return quote;
}
public void decode(JSONObject object) {
messageUid = (long) object.get("u");
userId = (String) object.get("i");
userDisplayName = (String) object.get("n");
messageDigest = (String) object.get("d");
JSONObject quote = (JSONObject)object.get("quote");
if(quote != null) {
messageUid = (long) quote.get("u");
userId = (String) quote.get("i");
userDisplayName = (String) quote.get("n");
messageDigest = (String) quote.get("d");
}
}
}
@@ -1,195 +1,135 @@
package cn.wildfirechat.sdk.utilities;
import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.sdk.model.IMResult;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import ikidou.reflect.TypeBuilder;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.ConnectionConfig;
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.InputStreamReader;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;
public class AdminHttpUtils extends JsonUtils {
public class AdminHttpUtils extends HttpUtils {
// ======================== 常量定义(消除硬编码)========================
private static final Logger LOG = LoggerFactory.getLogger(AdminHttpUtils.class);
public static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
private static String adminUrl;
private static String adminSecret;
private static CloseableHttpClient httpClient;
// 连接池配置常量
private static final int DEFAULT_CONNECT_TIMEOUT = 15000;
private static final int DEFAULT_CONNECTION_REQUEST_TIMEOUT = 3000;
private static final int DEFAULT_SOCKET_TIMEOUT = 15000;
private static final int MAX_CONN_TOTAL = 100;
private static final int MAX_CONN_PER_ROUTE = 50;
private static final long IDLE_CONNECTION_EVICT_TIME = 60L;
private static final int VALIDATE_AFTER_INACTIVITY = 1000;
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
private static final int NONCE_MAX_RANGE = 1000000;
// ======================== 线程安全的全局变量 ========================
private static volatile String adminUrl;
private static volatile String adminSecret;
private static volatile CloseableHttpClient httpClient;
// ======================== 初始化方法 ========================
public static void init(String url, String secret) {
init(url, secret, 15000);
init(url, secret, DEFAULT_SOCKET_TIMEOUT);
}
/**
* 初始化HTTP客户端和配置
* @param url IM服务管理地址
* @param secret 管理密钥
* @param timeout 套接字超时时间(毫秒)
*/
public static synchronized void init(String url, String secret, int timeout) {
// 参数校验
if (isNullOrEmpty(url) || isNullOrEmpty(secret)) {
throw new IllegalArgumentException("IM服务地址或密钥不能为空");
}
adminUrl = url.trim();
adminSecret = secret.trim();
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,先关闭再重新初始化(支持配置更新)
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
LOG.error("关闭旧HttpClient连接池失败", e);
}
}
// 初始化连接池
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setValidateAfterInactivity(VALIDATE_AFTER_INACTIVITY);
// 构建请求配置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT)
.setSocketTimeout(timeout)
.setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT)
.build();
// 构建HttpClient
httpClient = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(cm)
.evictExpiredConnections()
.evictIdleConnections(IDLE_CONNECTION_EVICT_TIME, TimeUnit.SECONDS)
.setRetryHandler(new DefaultHttpRequestRetryHandler(3, false)) // 重试3次,不重试IO异常
.setMaxConnTotal(MAX_CONN_TOTAL)
.setMaxConnPerRoute(MAX_CONN_PER_ROUTE)
.build();
LOG.info("AdminHttpUtils初始化完成,IM服务地址:{}", adminUrl);
}
// ======================== HTTP GET请求 ========================
public static <T> IMResult<T> httpGet(String path, Class<T> clazz) throws Exception {
if (isNullOrEmpty(adminUrl) || isNullOrEmpty(adminSecret)) {
LOG.error("野火IM Server SDK必须先初始化才能使用,是不是忘记初始化了!请调用AdminConfig.initAdmin(AdminUrl, AdminSecret);进行初始化");
throw new Exception("SDK没有初始化,请调用AdminConfig.initAdmin(AdminUrl, AdminSecret);进行初始化");
}
// 前置校验
validateInitStatus(adminUrl, adminSecret, httpClient);
if (isNullOrEmpty(path)) {
throw new Exception("路径缺失");
throw new IllegalArgumentException("请求路径不能为空");
}
HttpGet get = null;
HttpGet httpGet = new HttpGet(adminUrl + path);
try {
get = new HttpGet(adminUrl + path);
HttpResponse response = httpClient.execute(get);
int statusCode = response.getStatusLine().getStatusCode();
String content = null;
if (response.getEntity().getContentLength() > 0) {
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
StringBuilder sb = new StringBuilder();
String line;
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line).append(NL);
}
in.close();
content = sb.toString();
LOG.info("http request response content: {}", content);
}
if(statusCode != HttpStatus.SC_OK){
LOG.info("Request error: " + statusCode + " error msg:" + content);
throw new Exception("Http request error with code:" + statusCode);
} else {
return fromJsonObject(content, clazz);
}
HttpResponse response = httpClient.execute(httpGet);
return handleResponse(response, clazz, adminUrl, adminSecret);
} catch (Exception e) {
e.printStackTrace();
throw e;
LOG.error("HTTP GET请求失败,路径:{}", path, e);
throw new Exception("HTTP GET请求异常:" + e.getMessage(), e);
} finally {
if(get != null) {
get.releaseConnection();
}
httpGet.releaseConnection();
}
}
// ======================== HTTP JSON POST请求 ========================
public static <T> IMResult<T> httpJsonPost(String path, Object object, Class<T> clazz) throws Exception {
if (isNullOrEmpty(adminUrl) || isNullOrEmpty(adminSecret)) {
LOG.error("野火IM Server SDK必须先初始化才能使用,是不是忘记初始化了!请调用AdminConfig.initAdmin(AdminUrl, AdminSecret);进行初始化");
throw new Exception("SDK没有初始化,请调用AdminConfig.initAdmin(AdminUrl, AdminSecret);进行初始化");
}
if (isNullOrEmpty(path)) {
throw new Exception("路径缺失");
}
String url = adminUrl + path;
HttpPost post = null;
try {
int nonce = (int)(Math.random() * 100000 + 3);
return httpJsonPost(adminUrl, adminSecret, httpClient, path, object, clazz, httpPost -> {
// 构建签名头
int nonce = SECURE_RANDOM.nextInt(NONCE_MAX_RANGE) + 1; // 安全随机数
long timestamp = System.currentTimeMillis();
String str = nonce + "|" + adminSecret + "|" + timestamp;
String sign = DigestUtils.sha1Hex(str);
String signStr = nonce + "|" + adminSecret + "|" + timestamp;
String sign = DigestUtils.sha1Hex(signStr);
post = new HttpPost(url);
post.setHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Connection", "Keep-Alive");
post.setHeader("nonce", nonce + "");
post.setHeader("timestamp", "" + timestamp);
post.setHeader("sign", sign);
String jsonStr = "";
if (object != null) {
jsonStr = gson.toJson(object);
}
LOG.info("http request:{} content: {}", url, jsonStr);
StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
String content = null;
if (response.getEntity().getContentLength() > 0) {
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
StringBuilder sb = new StringBuilder();
String line;
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line).append(NL);
}
in.close();
content = sb.toString();
LOG.info("http request response content: {}", content);
}
if(statusCode != HttpStatus.SC_OK){
LOG.info("Request error: " + statusCode + " error msg:" + content);
throw new Exception("Http request error with code:" + statusCode);
} else {
IMResult<T> result = fromJsonObject(content, clazz);
if(result != null){
if(result.getErrorCode() == ErrorCode.ERROR_CODE_AUTH_FAILURE) {
LOG.error("鉴权失败,IM服务地址或者密钥配置错误,请检查IM服务{}的配置文件中的http.admin.secret_key是否是{}", adminUrl, adminSecret);
} else if(result.getErrorCode() == ErrorCode.ERROR_CODE_SIGN_EXPIRED) {
LOG.error("时间验证失败,请确保当前服务和IM服务{}的时间是一致的", adminUrl);
}
}
return result;
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if(post != null) {
post.releaseConnection();
}
}
// 设置请求头
httpPost.setHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("Connection", "Keep-Alive");
httpPost.setHeader("nonce", String.valueOf(nonce));
httpPost.setHeader("timestamp", String.valueOf(timestamp));
httpPost.setHeader("sign", sign);
});
}
}
@@ -30,9 +30,8 @@ import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
public class ChannelHttpUtils extends JsonUtils implements Closeable {
public class ChannelHttpUtils extends HttpUtils implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(ChannelHttpUtils.class);
public static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
private String imurl;
private String channelId;
@@ -88,71 +87,19 @@ public class ChannelHttpUtils extends JsonUtils implements Closeable {
}
public <T> IMResult<T> httpJsonPost(String path, Object object, Class<T> clazz) throws Exception{
if (isNullOrEmpty(imurl) || isNullOrEmpty(path)) {
LOG.error("Not init IM SDK correctly. Do you forget init it?");
throw new Exception("SDK url or secret lack!");
}
String url = imurl + path;
HttpPost post = null;
try {
return httpJsonPost(imurl, channelId, httpClient, path, object, clazz, post -> {
int nonce = (int)(Math.random() * 100000 + 3);
long timestamp = System.currentTimeMillis();
String str = nonce + "|" + channelSecret + "|" + timestamp;
String sign = DigestUtils.sha1Hex(str);
post = new HttpPost(url);
post.setHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Connection", "Keep-Alive");
post.setHeader("nonce", nonce + "");
post.setHeader("timestamp", "" + timestamp);
post.setHeader("cid", channelId);
post.setHeader("sign", sign);
String jsonStr = "";
if (object != null) {
jsonStr = gson.toJson(object);
}
LOG.info("http request:{} content: {}", url, jsonStr);
StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK){
LOG.info("Request error: "+statusCode);
throw new Exception("Http request error with code:" + statusCode);
}else{
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent(),"utf-8"));
StringBuffer sb = new StringBuffer();
String line;
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String content = sb.toString();
LOG.info("http request response content: {}", content);
return fromJsonObject(content, clazz);
}
} catch (Exception e) {
checkPort();
e.printStackTrace();
throw e;
}finally{
if(post != null){
post.releaseConnection();
}
}
});
}
public String getChannelId() {
@@ -0,0 +1,161 @@
package cn.wildfirechat.sdk.utilities;
import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.sdk.model.IMResult;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
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.HttpGet;
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.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;
public class HttpUtils extends JsonUtils {
// ======================== 常量定义(消除硬编码)========================
private static final Logger LOG = LoggerFactory.getLogger(HttpUtils.class);
public static final Gson GSON = new GsonBuilder().disableHtmlEscaping().create();
public static interface HeaderCallback {
public void addHeaders(HttpPost httpPost);
}
// ======================== HTTP JSON POST请求 ========================
public static <T> IMResult<T> httpJsonPost(String adminUrl, String adminSecret, HttpClient httpClient, String path, Object object, Class<T> clazz, HeaderCallback headerCallback) throws Exception {
// 前置校验
validateInitStatus(adminUrl, adminSecret, httpClient);
if (isNullOrEmpty(path)) {
throw new IllegalArgumentException("请求路径不能为空");
}
String url = adminUrl + path;
HttpPost httpPost = new HttpPost(url);
try {
headerCallback.addHeaders(httpPost);
// 设置请求体
String jsonStr = object == null ? "" : GSON.toJson(object);
LOG.info("HTTP POST请求:{},请求体:{}", url, truncateLogContent(jsonStr));
StringEntity entity = new StringEntity(jsonStr, StandardCharsets.UTF_8);
entity.setContentEncoding(StandardCharsets.UTF_8.name());
entity.setContentType("application/json");
httpPost.setEntity(entity);
// 执行请求并处理响应
HttpResponse response = httpClient.execute(httpPost);
return handleResponse(response, clazz, adminUrl, adminSecret);
} catch (Exception e) {
LOG.error("HTTP POST请求失败,路径:{}", path, e);
throw new Exception("HTTP POST请求异常:" + e.getMessage(), e);
} finally {
httpPost.releaseConnection();
}
}
// ======================== 私有工具方法 ========================
/**
* 校验初始化状态
*/
protected static void validateInitStatus(String adminUrl, String adminSecret, HttpClient httpClient) {
if (isNullOrEmpty(adminUrl) || isNullOrEmpty(adminSecret) || httpClient == null) {
String errorMsg = "野火IM Server SDK未初始化,请调用AdminConfig.initAdmin(AdminUrl, AdminSecret)完成初始化";
LOG.error(errorMsg);
throw new IllegalStateException(errorMsg);
}
}
/**
* 处理HTTP响应,统一解析逻辑
*/
protected static <T> IMResult<T> handleResponse(HttpResponse response, Class<T> clazz, String adminUrl, String adminSecret) throws Exception {
int statusCode = response.getStatusLine().getStatusCode();
String content = readResponseContent(response);
// 非200状态码处理
if (statusCode != HttpStatus.SC_OK) {
String errorMsg = String.format("HTTP请求失败,状态码:%d,响应内容:%s", statusCode, truncateLogContent(content));
LOG.error(errorMsg);
throw new Exception(errorMsg);
}
// 解析响应体
IMResult<T> result = fromJsonObject(content, clazz);
if (result != null) {
if (result.getErrorCode() == ErrorCode.ERROR_CODE_AUTH_FAILURE) {
LOG.error("鉴权失败,请检查IM服务地址({})或密钥({})配置", adminUrl, maskSecret(adminSecret));
} else if (result.getErrorCode() == ErrorCode.ERROR_CODE_SIGN_EXPIRED) {
LOG.error("签名过期,请确保当前服务与IM服务({})时间同步", adminUrl);
}
}
return result;
}
/**
* 读取响应体(兼容分块传输,修复getContentLength=-1问题)
*/
protected static String readResponseContent(HttpResponse response) throws IOException {
if (response.getEntity() == null) {
return "";
}
// 使用try-with-resources自动关闭所有流,避免资源泄漏
try (InputStream is = response.getEntity().getContent();
InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr)) {
StringBuilder sb = new StringBuilder();
String line;
String nl = System.getProperty("line.separator");
while ((line = br.readLine()) != null) {
sb.append(line).append(nl);
}
String content = sb.toString().trim();
LOG.info("HTTP响应内容:{}", truncateLogContent(content));
return content;
}
}
/**
* 截断超长日志内容(避免日志爆炸)
*/
protected static String truncateLogContent(String content) {
if (content == null) {
return "";
}
int maxLength = 1024;
return content.length() > maxLength ? content.substring(0, maxLength) + "..." : content;
}
/**
* 掩码处理密钥(避免日志泄露敏感信息)
*/
protected static String maskSecret(String secret) {
if (isNullOrEmpty(secret) || secret.length() <= 4) {
return "******";
}
return secret.substring(0, 2) + "******" + secret.substring(secret.length() - 2);
}
/**
* 空值判断(补充实现,避免依赖外部未定义方法)
*/
public static boolean isNullOrEmpty(String str) {
return str == null || str.trim().isEmpty();
}
}
@@ -31,7 +31,7 @@ import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
public class RobotHttpUtils extends JsonUtils implements Closeable {
public class RobotHttpUtils extends HttpUtils implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(RobotHttpUtils.class);
public static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
@@ -90,72 +90,19 @@ public class RobotHttpUtils extends JsonUtils implements Closeable {
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?");
throw new Exception("SDK url or secret lack!");
}
String url = this.url + path;
HttpPost post = null;
try {
return httpJsonPost(url, robotId, httpClient, path, object, clazz, post -> {
int nonce = (int)(Math.random() * 100000 + 3);
long timestamp = System.currentTimeMillis();
String str = nonce + "|" + robotSecret + "|" + timestamp;
String sign = DigestUtils.sha1Hex(str);
post = new HttpPost(url);
post.setHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Connection", "Keep-Alive");
post.setHeader("nonce", nonce + "");
post.setHeader("timestamp", "" + timestamp);
post.setHeader("rid", robotId);
post.setHeader("sign", sign);
String jsonStr = null;
if (object != null) {
jsonStr = gson.toJson(object);
}
LOG.info("http request:{} content: {}", url, jsonStr);
if(!StringUtil.isNullOrEmpty(jsonStr)) {
StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
}
HttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK){
LOG.info("Request error: "+statusCode);
throw new Exception("Http request error with code:" + statusCode);
}else{
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent(),"utf-8"));
StringBuffer sb = new StringBuffer();
String line;
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String content = sb.toString();
LOG.info("http request response content: {}", content);
return fromJsonObject(content, clazz);
}
} catch (Exception e) {
checkPort();
e.printStackTrace();
throw e;
}finally{
if(post != null){
post.releaseConnection();
}
}
});
}
public String getRobotId() {