Compare commits

..
10 Commits
37 changed files with 535 additions and 281 deletions
+3
View File
@@ -163,6 +163,9 @@ mvn clean package
如果是专业版IM服务,普通群性能会有些加强,但也不会提高太多,所以我们就开发了超级群,可以支持上万群成员。关于超级群,请参考[野火超级群组](https://mp.weixin.qq.com/s/ov5ZiaEIUZuvgFBXOrcjbg)。现有客户有接近10W的群组成员能够流畅稳定地运行。
## 网络问题
如果是自建机房或者私有网络,可能会有跨运营商瓶颈,详情请参考[《从野火 IM 的网络踩坑经历,聊聊跨运营商访问的那些坑》](https://mp.weixin.qq.com/s/Pa8b93oMk58fjMgwtwmePQ)。
## 常见问题
请参考文档[常见问题](https://docs.wildfirechat.cn/faq/server.html)
+7
View File
@@ -334,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,
+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)
);
+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 -1
View File
@@ -5,7 +5,7 @@
<relativePath>../</relativePath>
<artifactId>wildfirechat-parent</artifactId>
<groupId>cn.wildfirechat</groupId>
<version>1.4.1</version>
<version>1.4.3</version>
</parent>
<artifactId>moquette-broker</artifactId>
@@ -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";
@@ -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();
}
@@ -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";
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>wildfirechat-parent</artifactId>
<groupId>cn.wildfirechat</groupId>
<version>1.4.1</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 <[email protected]>
*
* 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;
}
@@ -196,4 +196,16 @@ public class InputOutputUserInfo {
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;
}
@@ -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.4.1</version>
<version>1.4.3</version>
</parent>
<artifactId>distribution</artifactId>
@@ -334,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.4.1</version>
<version>1.4.3</version>
<name>Wildfire Chat</name>
<description>Wildfire Chat Server</description>
<inceptionYear>2019</inceptionYear>
+12
View File
@@ -12,6 +12,18 @@
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同时存在时推送计数错误问题。
+1 -1
View File
@@ -3,7 +3,7 @@
<parent>
<artifactId>wildfirechat-parent</artifactId>
<groupId>cn.wildfirechat</groupId>
<version>1.4.1</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";
@@ -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);
@@ -12,7 +12,7 @@ public class UnknownMessageContent extends MessageContent {
@Override
public int getContentType() {
return ProtoConstants.ContentType.Text;
return ProtoConstants.ContentType.Unknown;
}
@Override
@@ -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() {