Compare commits

..
19 Commits
Author SHA1 Message Date
heavyrian2012 776c9e26c6 机器人API添加根据邮箱获取用户信息和批量获取用户信息的接口 2026-04-29 15:31:59 +08:00
heavyrian2012 c7f7ce949e 机器人和频道api,请求错误时,result应该为空 2026-04-26 09:42:22 +08:00
heavyrian2012 07b1de4ae3 添加注释 2026-04-20 08:19:38 +08:00
heavyrian2012 7e87f9d6ab 机器人更新消息内容添加distribute接口 2026-04-19 20:06:53 +08:00
heavyrian2012 da781180a7 解决业务系统不限制手机号码重复时,根据手机号码获取用户列表的问题 2026-04-10 21:53:24 +08:00
heavyrian2012 f1b62ad64a 同步专业版数据库 2026-04-10 21:41:49 +08:00
heavyrian2012 576fcf3e77 添加获取所有机器人的接口 2026-04-05 11:28:46 +08:00
heavyrian2012 33f2124352 同步专业版IM服务SDK 2026-03-31 15:57:29 +08:00
heavyrian2012 15701e9943 version and release note 2026-03-25 10:04:24 +08:00
heavyrian2012 dc5687319a 转移群组时判断是否已经是群主 2026-03-25 10:01:15 +08:00
heavyrian2012 3eef24bdb9 添加server sdk readme 2026-03-15 10:30:00 +08:00
heavyrian2012 be5a24a6fd update readme 2026-03-13 13:02:17 +08:00
heavyrian2012 6537b7e009 getPresignedUploadUrl公开 2026-03-11 16:15:47 +08:00
heavyrian2012 92471db413 添加SDK上传功能 2026-03-11 16:11:13 +08:00
heavyrian2012 6626237c80 支持可穿戴设备和TV端 2026-03-06 19:15:22 +08:00
heavyrian2012 c98507d9a0 sdk测试方法中添加更多的测试例 2026-03-04 19:16:35 +08:00
heavyrian2012 d8adaf7e88 启动脚本里添加utf8参数 2026-02-28 21:33:38 +08:00
imndx 45d40e2389 update readme 2026-02-27 10:03:30 +08:00
heavyrian2012 33de0f3e43 添加网盘对象存储 2026-02-26 14:20:02 +08:00
45 changed files with 3261 additions and 46 deletions
+23 -22
View File
@@ -30,28 +30,29 @@
## 野火开源项目
主要包括以下项目:
| [GitHub仓库](https://github.com/wildfirechat) | [码云仓库](https://gitee.com/wfchat) | 说明
| ------------------------------------------------------------ | ----------------------------------------------------- | --------------------------------------------------------------------------
| [im-server](https://github.com/wildfirechat/im-server) | [im-server](https://gitee.com/wfchat/im-server) | 野火社区版IM服务,野火IM的核心服务,处理所有IM相关业务。 |
| [app-server](https://github.com/wildfirechat/app-server) | [app-server](https://gitee.com/wfchat/app-server) | Demo应用服务,模拟客户的应用服登陆处理逻辑及部分二次开发示例。 |
| [robot_server](https://github.com/wildfirechat/robot_server) | [robot_server](https://gitee.com/wfchat/robot_server) | 机器人服务,演示野火机器人对接其它系统的方法。 |
| [push_server](https://github.com/wildfirechat/push_server) | [push_server](https://gitee.com/wfchat/push_server) | 推送服务器,可以对接所有的系统厂商推送服务或者第三方推送服务。 |
| [wf-minio](https://github.com/wildfirechat/WF-minio) | [wf-minio](https://gitee.com/wfchat/WF-minio) | 私有对象存储服务,用来支持野火IM专业版的文件存储。 |
| [wf-janus](https://github.com/wildfirechat/wf-janus ) | [wf-janus](https://gitee.com/wfchat/wf-janus ) | 高级音视频媒体服务。 |
| [open-platform](https://github.com/wildfirechat/open-platform) | [open-platform](https://gitee.com/wfchat/open-platform) | 野火开放平台服务。 |
| [daily-report](https://github.com/wildfirechat/daily-report) | [daily-report](https://github.com/wildfirechat/daily-report) | 野火开放平台日报 demo服务。 |
| [channel-platform](https://github.com/wildfirechat/channel-platform) | [channel-platform](https://gitee.com/wfchat/channel-platform) | 野火频道(公众号)平台服务。 |
| [organization-platform](https://github.com/wildfirechat/organization-platform) | [organization-platform](https://gitee.com/wfchat/organization-platform) | 野火组织通讯录服务。 |
| [android-chat](https://github.com/wildfirechat/android-chat) | [android-chat](https://gitee.com/wfchat/android-chat) | 野火IM Android SDK源码和App源码。 |
| [ios-chat](https://github.com/wildfirechat/ios-chat) | [ios-chat](https://gitee.com/wfchat/ios-chat) | 野火IM iOS SDK源码和App源码。|
| [pc-chat(electron)](https://github.com/wildfirechat/vue-pc-chat) | [pc-chat(electron)](https://gitee.com/wfchat/vue-pc-chat) | 基于[Electron](https://electronjs.org/)开发的PC 端 | |
| [pc-chat(Qt)](https://github.com/wildfirechat/qt-pc-chat) | [pc-chat(Qt)](https://gitee.com/wfchat/qt-pc-chat) | 基于Qt开发的PC 端 | |
| [web-chat](https://github.com/wildfirechat/vue-chat) | [web-chat](https://gitee.com/wfchat/vue-chat) | 野火IM Web 端, [体验地址](https://web.wildfirechat.cn)。 |
| [wx-chat](https://github.com/wildfirechat/wx-chat) | [wx-chat](https://gitee.com/wfchat/wx-chat) | 小程序平台的Demo(支持微信、百度、阿里、字节、QQ 等小程序平台)。 |
| [uni-chat](https://github.com/wildfirechat/uni-chat) | [uni-chat](https://gitee.com/wfchat/uni-chat) | UniApp平台移动端应用(使用原生插件)。 |
| [uni-wfc-client](https://github.com/wildfirechat/uni-wfc-client) | [uni-wfc-client](https://gitee.com/wfchat/uni-wfc-client) | UniApp平台原生插件。已[商店](https://ext.dcloud.net.cn/plugin?id=7895)上架 |
| [wfc_flutter_plugins](https://github.com/wildfirechat/wfc_flutter_plugins) | [flutter_imclient](https://gitee.com/wfchat/wfc_flutter_plugins) | Flutter平台原生插件,支持IM和音视频通话。 |
| [docs](https://github.com/wildfirechat/docs) | [docs](https://gitee.com/wfchat/docs) | 野火IM相关文档,包含设计、概念、开发、使用说明,[在线查看](https://docs.wildfirechat.cn/)。 |
| [GitHub仓库](https://github.com/wildfirechat) | [码云仓库](https://gitee.com/wfchat) | 说明
|--------------------------------------------------------------------------------|-------------------------------------------------------------------------| --------------------------------------------------------------------------
| [im-server](https://github.com/wildfirechat/im-server) | [im-server](https://gitee.com/wfchat/im-server) | 野火社区版IM服务,野火IM的核心服务,处理所有IM相关业务。 |
| [app-server](https://github.com/wildfirechat/app-server) | [app-server](https://gitee.com/wfchat/app-server) | Demo应用服务,模拟客户的应用服登陆处理逻辑及部分二次开发示例。 |
| [robot_server](https://github.com/wildfirechat/robot_server) | [robot_server](https://gitee.com/wfchat/robot_server) | 机器人服务,演示野火机器人对接其它系统的方法。 |
| [push_server](https://github.com/wildfirechat/push_server) | [push_server](https://gitee.com/wfchat/push_server) | 推送服务器,可以对接所有的系统厂商推送服务或者第三方推送服务。 |
| [wf-minio](https://github.com/wildfirechat/WF-minio) | [wf-minio](https://gitee.com/wfchat/WF-minio) | 私有对象存储服务,用来支持野火IM专业版的文件存储。 |
| [wf-janus](https://github.com/wildfirechat/wf-janus ) | [wf-janus](https://gitee.com/wfchat/wf-janus ) | 高级音视频媒体服务。 |
| [open-platform](https://github.com/wildfirechat/open-platform) | [open-platform](https://gitee.com/wfchat/open-platform) | 野火开放平台服务。 |
| [daily-report](https://github.com/wildfirechat/daily-report) | [daily-report](https://github.com/wildfirechat/daily-report) | 野火开放平台日报 demo服务。 |
| [channel-platform](https://github.com/wildfirechat/channel-platform) | [channel-platform](https://gitee.com/wfchat/channel-platform) | 野火频道(公众号)平台服务。 |
| [organization-platform](https://github.com/wildfirechat/organization-platform) | [organization-platform](https://gitee.com/wfchat/organization-platform) | 野火组织通讯录服务。 |
| [archive-server](https://github.com/wildfirechat/archive-server) | [archive-server](https://gitee.com/wfchat/archive-server) | 野火组织通讯录服务。 |
| [android-chat](https://github.com/wildfirechat/android-chat) | [android-chat](https://gitee.com/wfchat/android-chat) | 野火IM Android SDK源码和App源码。 |
| [ios-chat](https://github.com/wildfirechat/ios-chat) | [ios-chat](https://gitee.com/wfchat/ios-chat) | 野火IM iOS SDK源码和App源码。|
| [pc-chat(electron)](https://github.com/wildfirechat/vue-pc-chat) | [pc-chat(electron)](https://gitee.com/wfchat/vue-pc-chat) | 基于[Electron](https://electronjs.org/)开发的PC 端 | |
| [pc-chat(Qt)](https://github.com/wildfirechat/qt-pc-chat) | [pc-chat(Qt)](https://gitee.com/wfchat/qt-pc-chat) | 基于Qt开发的PC 端 | |
| [web-chat](https://github.com/wildfirechat/vue-chat) | [web-chat](https://gitee.com/wfchat/vue-chat) | 野火IM Web 端, [体验地址](https://web.wildfirechat.cn)。 |
| [wx-chat](https://github.com/wildfirechat/wx-chat) | [wx-chat](https://gitee.com/wfchat/wx-chat) | 小程序平台的Demo(支持微信、百度、阿里、字节、QQ 等小程序平台)。 |
| [uni-chat](https://github.com/wildfirechat/uni-chat) | [uni-chat](https://gitee.com/wfchat/uni-chat) | UniApp平台移动端应用(使用原生插件)。 |
| [uni-wfc-client](https://github.com/wildfirechat/uni-wfc-client) | [uni-wfc-client](https://gitee.com/wfchat/uni-wfc-client) | UniApp平台原生插件。已[商店](https://ext.dcloud.net.cn/plugin?id=7895)上架 |
| [flutter-chat](https://github.com/wildfirechat/flutter-chat) | [flutter-chat](https://gitee.com/wfchat/flutter-chat) | Flutter平台原生插件,支持IM和音视频通话。 |
| [docs](https://github.com/wildfirechat/docs) | [docs](https://gitee.com/wfchat/docs) | 野火IM相关文档,包含设计、概念、开发、使用说明,[在线查看](https://docs.wildfirechat.cn/)。 |
## 野火开发文档
[在线文档](https://docs.wildfirechat.cn/)
+8
View File
@@ -347,6 +347,8 @@ 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
qiniu.bucket_pan_name pan
qiniu.bucket_pan_domain http://pan.wildfirechat.cn
##媒体类型分类
#Media_Type_GENERAL = 0,
@@ -379,6 +381,12 @@ server.multi_pc_endpoint false
## 是否支持PAD多端登陆,当server.multi_endpoint为true时,此开关无意义,当为false时,可以单独打开PAD端多端登录。
server.multi_pad_endpoint false
## 是否支持可穿戴设备多端登陆,当server.multi_endpoint为true时,此开关无意义,当为false时,可以单独打开可穿戴设备多端登录。
server.multi_wearable_endpoint false
## 是否支持TV设备多端登陆,当server.multi_endpoint为true时,此开关无意义,当为false时,可以单独打开TV多端登录。
server.multi_tv_endpoint false
# 多平台连接状态通知(仅当multi_endpoint为false时有效),true时移动端可以收到pc或pad或web端登录的通知。
server.multi_platform_notification true
+3
View File
@@ -0,0 +1,3 @@
ALTER TABLE `t_conference` ADD COLUMN `_delete_by` varchar(64) DEFAULT '';
ALTER TABLE `t_conference` ADD COLUMN `_deleted` tinyint DEFAULT 0;
ALTER TABLE `t_conference` ADD COLUMN `_delete_dt` bigint(20) DEFAULT 0;
+3
View File
@@ -0,0 +1,3 @@
ALTER TABLE `t_conference` ADD COLUMN `_delete_by` varchar(64) DEFAULT '';
ALTER TABLE `t_conference` ADD COLUMN `_deleted` tinyint DEFAULT 0;
ALTER TABLE `t_conference` ADD COLUMN `_delete_dt` bigint(20) DEFAULT 0;
+1 -1
View File
@@ -5,7 +5,7 @@
<relativePath>../</relativePath>
<artifactId>wildfirechat-parent</artifactId>
<groupId>cn.wildfirechat</groupId>
<version>1.4.5</version>
<version>1.4.6</version>
</parent>
<artifactId>moquette-broker</artifactId>
@@ -96,13 +96,18 @@ public class PushServer {
session.getPlatform() == ProtoConstants.Platform.Platform_Android ||
session.getPlatform() == ProtoConstants.Platform.Platform_APad ||
session.getPlatform() == ProtoConstants.Platform.Platform_Harmony ||
session.getPlatform() == ProtoConstants.Platform.Platform_HarmonyPad
session.getPlatform() == ProtoConstants.Platform.Platform_HarmonyPad ||
session.getPlatform() == ProtoConstants.Platform.Platform_AppleTV ||
session.getPlatform() == ProtoConstants.Platform.Platform_AndroidTV ||
session.getPlatform() == ProtoConstants.Platform.Platform_HarmonyTV ||
session.getPlatform() == ProtoConstants.Platform.Platform_HarmonyWearable ||
session.getPlatform() == ProtoConstants.Platform.Platform_AndroidWearable
) {
String url = androidPushServerUrl;
if (session.getPlatform() == ProtoConstants.Platform.Platform_iOS || session.getPlatform() == ProtoConstants.Platform.Platform_iPad) {
if (session.getPlatform() == ProtoConstants.Platform.Platform_iOS || session.getPlatform() == ProtoConstants.Platform.Platform_iPad || session.getPlatform() == ProtoConstants.Platform.Platform_AppleTV) {
url = iOSPushServerUrl;
pushMessage.voipDeviceToken = session.getVoipDeviceToken();
} else if (session.getPlatform() == ProtoConstants.Platform.Platform_Harmony || session.getPlatform() == ProtoConstants.Platform.Platform_HarmonyPad) {
} else if (session.getPlatform() == ProtoConstants.Platform.Platform_Harmony || session.getPlatform() == ProtoConstants.Platform.Platform_HarmonyPad || session.getPlatform() == ProtoConstants.Platform.Platform_HarmonyWearable || session.getPlatform() == ProtoConstants.Platform.Platform_HarmonyTV) {
url = harmonyPushServerUrl;
}
HttpUtils.httpJsonPost(url, gson.toJson(pushMessage, pushMessage.getClass()), POST_TYPE_Push);
@@ -144,7 +144,7 @@ abstract public class Action {
errorCode = ErrorCode.ERROR_CODE_SUCCESS;
}
RestResult result = RestResult.resultOf(errorCode, errorCode.getMsg(), RestResult.resultOf(errorCode));
RestResult result = RestResult.resultOf(errorCode, errorCode.getMsg(), null);
response.setContent(gson.toJson(result));
response.send();
}
@@ -0,0 +1,62 @@
/*
* This file is part of the Wildfire Chat package.
* (c) Heavyrain2012 <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package com.xiaoleilu.loServer.action.admin;
import cn.wildfirechat.common.APIPath;
import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.*;
import cn.wildfirechat.proto.WFCMessage;
import com.xiaoleilu.loServer.RestResult;
import com.xiaoleilu.loServer.annotation.HttpMethod;
import com.xiaoleilu.loServer.annotation.Route;
import com.xiaoleilu.loServer.handler.Request;
import com.xiaoleilu.loServer.handler.Response;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.internal.StringUtil;
import java.util.*;
@Route(APIPath.User_Get_All_Robots)
@HttpMethod("POST")
public class GetAllRobotAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputGetUserList input = getRequestBody(request.getNettyRequest(), InputGetUserList.class);
if (input != null && input.count > 0 && input.offset >= 0) {
List<WFCMessage.Robot> robots = messagesStore.getRobotInfoList(input.count, input.offset);
OutputGetRobotList outputGetUserList = new OutputGetRobotList();
outputGetUserList.robotInfoList = new ArrayList<>();
robots.forEach(robotData -> {
WFCMessage.User userInfoData = messagesStore.getUserInfo(robotData.getUid());
if (userInfoData != null && !StringUtil.isNullOrEmpty(userInfoData.getName()) && userInfoData.getDeleted() ==0) {
OutputRobot outputRobot = new OutputRobot();
outputRobot.fromUser(userInfoData);
outputRobot.fromRobot(robotData, true);
outputGetUserList.robotInfoList.add(outputRobot);
}
});
RestResult result = RestResult.ok(outputGetUserList);
setResponseContent(result, response);
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
}
}
@@ -0,0 +1,126 @@
/*
* This file is part of the Wildfire Chat package.
* (c) Heavyrain2012 <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package com.xiaoleilu.loServer.action.admin;
import cn.wildfirechat.common.APIPath;
import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.InputGetPresignedUploadUrl;
import cn.wildfirechat.pojos.OutputPresignedUploadUrl;
import com.qiniu.util.Auth;
import com.xiaoleilu.loServer.RestResult;
import com.xiaoleilu.loServer.action.robot.RobotAction;
import com.xiaoleilu.loServer.annotation.HttpMethod;
import com.xiaoleilu.loServer.annotation.Route;
import com.xiaoleilu.loServer.handler.Request;
import com.xiaoleilu.loServer.handler.Response;
import io.moquette.server.config.MediaServerConfig;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.internal.StringUtil;
import java.util.UUID;
@Route(APIPath.Get_Presigned_Upload_Url)
@HttpMethod("POST")
public class GetUploadUrlAction extends AdminAction {
@Override
public boolean action(Request request, Response response) {
if (request.getNettyRequest() instanceof FullHttpRequest) {
if(!MediaServerConfig.USER_QINIU) {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
return true;
}
InputGetPresignedUploadUrl inputUserId = getRequestBody(request.getNettyRequest(), InputGetPresignedUploadUrl.class);
if (StringUtil.isNullOrEmpty(inputUserId.contentType)) {
inputUserId.contentType = "application/octet-stream";
}
String uuid = UUID.randomUUID().toString().replace("-", "");
inputUserId.fileName = uuid + inputUserId.fileName;
int type = inputUserId.mediaType;
String bucketName;
String bucketDomain;
switch (type) {
case 0:
default:
bucketName = MediaServerConfig.QINIU_BUCKET_GENERAL_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_GENERAL_DOMAIN;
break;
case 1:
bucketName = MediaServerConfig.QINIU_BUCKET_IMAGE_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_IMAGE_DOMAIN;
break;
case 2:
bucketName = MediaServerConfig.QINIU_BUCKET_VOICE_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_VOICE_DOMAIN;
break;
case 3:
bucketName = MediaServerConfig.QINIU_BUCKET_VIDEO_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_VIDEO_DOMAIN;
break;
case 4:
bucketName = MediaServerConfig.QINIU_BUCKET_FILE_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_FILE_DOMAIN;
break;
case 5:
bucketName = MediaServerConfig.QINIU_BUCKET_PORTRAIT_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_PORTRAIT_DOMAIN;
break;
case 6:
bucketName = MediaServerConfig.QINIU_BUCKET_FAVORITE_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_FAVORITE_DOMAIN;
break;
case 7:
bucketName = MediaServerConfig.QINIU_BUCKET_STICKER_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_STICKER_DOMAIN;
break;
case 8:
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;
case 12:
bucketName = MediaServerConfig.QINIU_BUCKET_PAN_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_PAN_DOMAIN;
break;
}
if(StringUtil.isNullOrEmpty(bucketName)) {
bucketName = MediaServerConfig.QINIU_BUCKET_GENERAL_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_GENERAL_DOMAIN;
}
String key = inputUserId.fileName;
Auth auth = Auth.create(MediaServerConfig.QINIU_ACCESS_KEY, MediaServerConfig.QINIU_SECRET_KEY);
String token = auth.uploadToken(bucketName, key);
String downloadUrl = bucketDomain + "/" + key;
String uploadUrl = "https://" + MediaServerConfig.QINIU_SERVER_URL + "?" + token + "?" + key;
OutputPresignedUploadUrl outputPresignedUploadUrl = new OutputPresignedUploadUrl();
outputPresignedUploadUrl.uploadUrl = uploadUrl;
outputPresignedUploadUrl.downloadUrl = downloadUrl;
outputPresignedUploadUrl.type = 1;
setResponseContent(RestResult.ok(outputPresignedUploadUrl), response);
}
return true;
}
}
@@ -0,0 +1,65 @@
/*
* This file is part of the Wildfire Chat package.
* (c) Heavyrain2012 <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package com.xiaoleilu.loServer.action.admin;
import cn.wildfirechat.common.APIPath;
import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.InputGetUserInfo;
import cn.wildfirechat.pojos.InputOutputUserInfo;
import cn.wildfirechat.pojos.OutputUserInfoList;
import cn.wildfirechat.proto.WFCMessage;
import com.xiaoleilu.loServer.RestResult;
import com.xiaoleilu.loServer.annotation.HttpMethod;
import com.xiaoleilu.loServer.annotation.Route;
import com.xiaoleilu.loServer.handler.Request;
import com.xiaoleilu.loServer.handler.Response;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.internal.StringUtil;
import java.util.ArrayList;
import java.util.List;
@Route(APIPath.User_Get_By_Mobile)
@HttpMethod("POST")
public class GetUsersByMobileAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputGetUserInfo email = getRequestBody(request.getNettyRequest(), InputGetUserInfo.class);
if (!StringUtil.isNullOrEmpty(email.getMobile())) {
List<WFCMessage.User> users = messagesStore.getUserInfosByMobile(email.getMobile(), email.isIncludeDeleted());
List<InputOutputUserInfo> list = new ArrayList<>();
for (WFCMessage.User user : users) {
list.add(InputOutputUserInfo.fromPbUser(user));
}
RestResult result;
if (list.isEmpty()) {
result = RestResult.resultOf(ErrorCode.ERROR_CODE_NOT_EXIST);
} else {
OutputUserInfoList outputUserInfoList = new OutputUserInfoList();
outputUserInfoList.userInfos = list;
result = RestResult.ok(outputUserInfoList);
}
setResponseContent(result, response);
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
}
}
@@ -0,0 +1,87 @@
/*
* This file is part of the Wildfire Chat package.
* (c) Heavyrain2012 <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package com.xiaoleilu.loServer.action.robot;
import cn.wildfirechat.common.APIPath;
import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.InputOutputUserInfo;
import cn.wildfirechat.pojos.InputStringList;
import cn.wildfirechat.pojos.OutputUserInfoList;
import cn.wildfirechat.proto.WFCMessage;
import com.xiaoleilu.loServer.RestResult;
import com.xiaoleilu.loServer.annotation.HttpMethod;
import com.xiaoleilu.loServer.annotation.Route;
import com.xiaoleilu.loServer.handler.Request;
import com.xiaoleilu.loServer.handler.Response;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.internal.StringUtil;
import java.util.ArrayList;
import java.util.List;
@Route(APIPath.Robot_User_Batch_Get_Infos)
@HttpMethod("POST")
public class GetBatchUserAction extends RobotAction {
@Override
public boolean action(Request request, Response response) {
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputStringList inputUserId = getRequestBody(request.getNettyRequest(), InputStringList.class);
if (inputUserId != null && inputUserId.getList() != null && !inputUserId.getList().isEmpty()) {
OutputUserInfoList res = new OutputUserInfoList();
res.userInfos = new ArrayList<>();
int mask = messagesStore.getRobotGetUserInfoMask();
for (String userId : inputUserId.getList()) {
WFCMessage.User user = messagesStore.getUserInfo(userId);
if(user == null || StringUtil.isNullOrEmpty(user.getName())) {
continue;
}
InputOutputUserInfo inputOutputUserInfo = InputOutputUserInfo.fromPbUser(user);
if((mask & 1) == 0) {
inputOutputUserInfo.setName(null);
}
if((mask & 2) == 0) {
inputOutputUserInfo.setMobile(null);
}
if((mask & 4) == 0) {
inputOutputUserInfo.setEmail(null);
}
if((mask & 8) == 0) {
inputOutputUserInfo.setAddress(null);
}
if((mask & 16) == 0) {
inputOutputUserInfo.setCompany(null);
}
if((mask & 32) == 0) {
inputOutputUserInfo.setExtra(null);
}
if((mask & 64) == 0) {
inputOutputUserInfo.setUpdateDt(0);
}
if((mask & 128) == 0) {
inputOutputUserInfo.setGender(0);
}
if((mask & 256) == 0) {
inputOutputUserInfo.setSocial(null);
}
if((mask & 512) == 0) {
inputOutputUserInfo.setType(0);
}
res.userInfos.add(inputOutputUserInfo);
}
RestResult result = RestResult.ok(res);
setResponseContent(result, response);
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
}
}
@@ -0,0 +1,139 @@
/*
* This file is part of the Wildfire Chat package.
* (c) Heavyrain2012 <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package com.xiaoleilu.loServer.action.robot;
import cn.wildfirechat.common.APIPath;
import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.InputGetPresignedUploadUrl;
import cn.wildfirechat.pojos.InputGetUserInfo;
import cn.wildfirechat.pojos.InputOutputUserInfo;
import cn.wildfirechat.pojos.OutputPresignedUploadUrl;
import cn.wildfirechat.proto.ProtoConstants;
import cn.wildfirechat.proto.WFCMessage;
import com.qiniu.util.Auth;
import com.xiaoleilu.loServer.RestResult;
import com.xiaoleilu.loServer.annotation.HttpMethod;
import com.xiaoleilu.loServer.annotation.Route;
import com.xiaoleilu.loServer.handler.Request;
import com.xiaoleilu.loServer.handler.Response;
import io.moquette.persistence.MemorySessionStore;
import io.moquette.server.config.MediaServerConfig;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.internal.StringUtil;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.ZonedDateTime;
import java.util.*;
@Route(APIPath.Robot_Get_Presigned_Upload_Url)
@HttpMethod("POST")
public class GetUploadUrlAction extends RobotAction {
@Override
public boolean action(Request request, Response response) {
if (request.getNettyRequest() instanceof FullHttpRequest) {
if(!MediaServerConfig.USER_QINIU) {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
return true;
}
InputGetPresignedUploadUrl inputUserId = getRequestBody(request.getNettyRequest(), InputGetPresignedUploadUrl.class);
if (StringUtil.isNullOrEmpty(inputUserId.contentType)) {
inputUserId.contentType = "application/octet-stream";
}
String uuid = UUID.randomUUID().toString().replace("-", "");
inputUserId.fileName = uuid + inputUserId.fileName;
int type = inputUserId.mediaType;
String bucketName;
String bucketDomain;
switch (type) {
case 0:
default:
bucketName = MediaServerConfig.QINIU_BUCKET_GENERAL_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_GENERAL_DOMAIN;
break;
case 1:
bucketName = MediaServerConfig.QINIU_BUCKET_IMAGE_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_IMAGE_DOMAIN;
break;
case 2:
bucketName = MediaServerConfig.QINIU_BUCKET_VOICE_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_VOICE_DOMAIN;
break;
case 3:
bucketName = MediaServerConfig.QINIU_BUCKET_VIDEO_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_VIDEO_DOMAIN;
break;
case 4:
bucketName = MediaServerConfig.QINIU_BUCKET_FILE_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_FILE_DOMAIN;
break;
case 5:
bucketName = MediaServerConfig.QINIU_BUCKET_PORTRAIT_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_PORTRAIT_DOMAIN;
break;
case 6:
bucketName = MediaServerConfig.QINIU_BUCKET_FAVORITE_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_FAVORITE_DOMAIN;
break;
case 7:
bucketName = MediaServerConfig.QINIU_BUCKET_STICKER_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_STICKER_DOMAIN;
break;
case 8:
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;
case 12:
bucketName = MediaServerConfig.QINIU_BUCKET_PAN_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_PAN_DOMAIN;
break;
}
if(StringUtil.isNullOrEmpty(bucketName)) {
bucketName = MediaServerConfig.QINIU_BUCKET_GENERAL_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_GENERAL_DOMAIN;
}
String key = inputUserId.fileName;
Auth auth = Auth.create(MediaServerConfig.QINIU_ACCESS_KEY, MediaServerConfig.QINIU_SECRET_KEY);
String token = auth.uploadToken(bucketName, key);
String downloadUrl = bucketDomain + "/" + key;
String uploadUrl = "https://" + MediaServerConfig.QINIU_SERVER_URL + "?" + token + "?" + key;
OutputPresignedUploadUrl outputPresignedUploadUrl = new OutputPresignedUploadUrl();
outputPresignedUploadUrl.uploadUrl = uploadUrl;
outputPresignedUploadUrl.downloadUrl = downloadUrl;
outputPresignedUploadUrl.type = 1;
setResponseContent(RestResult.ok(outputPresignedUploadUrl), response);
}
return true;
}
}
@@ -0,0 +1,92 @@
/*
* This file is part of the Wildfire Chat package.
* (c) Heavyrain2012 <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package com.xiaoleilu.loServer.action.robot;
import cn.wildfirechat.common.APIPath;
import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.InputOutputUserInfo;
import cn.wildfirechat.pojos.OutputUserInfoList;
import cn.wildfirechat.proto.WFCMessage;
import com.xiaoleilu.loServer.RestResult;
import com.xiaoleilu.loServer.annotation.HttpMethod;
import com.xiaoleilu.loServer.annotation.Route;
import com.xiaoleilu.loServer.handler.Request;
import com.xiaoleilu.loServer.handler.Response;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.internal.StringUtil;
import java.util.ArrayList;
import java.util.List;
@Route(APIPath.Robot_User_Get_Email_Info)
@HttpMethod("POST")
public class GetUsersByEmailAction extends RobotAction {
@Override
public boolean action(Request request, Response response) {
if (request.getNettyRequest() instanceof FullHttpRequest) {
String email = getRequestBody(request.getNettyRequest(), String.class);
if (!StringUtil.isNullOrEmpty(email)) {
List<WFCMessage.User> users = messagesStore.getUserInfosByEmail(email);
List<InputOutputUserInfo> list = new ArrayList<>();
int mask = messagesStore.getRobotGetUserInfoMask();
for (WFCMessage.User user : users) {
InputOutputUserInfo outputUserInfo = InputOutputUserInfo.fromPbUser(user);
if((mask & 1) == 0) {
outputUserInfo.setName(null);
}
if((mask & 2) == 0) {
outputUserInfo.setMobile(null);
}
if((mask & 4) == 0) {
outputUserInfo.setEmail(null);
}
if((mask & 8) == 0) {
outputUserInfo.setAddress(null);
}
if((mask & 16) == 0) {
outputUserInfo.setCompany(null);
}
if((mask & 32) == 0) {
outputUserInfo.setExtra(null);
}
if((mask & 64) == 0) {
outputUserInfo.setUpdateDt(0);
}
if((mask & 128) == 0) {
outputUserInfo.setGender(0);
}
if((mask & 256) == 0) {
outputUserInfo.setSocial(null);
}
if((mask & 512) == 0) {
outputUserInfo.setType(0);
}
list.add(outputUserInfo);
}
RestResult result;
if (list.isEmpty()) {
result = RestResult.resultOf(ErrorCode.ERROR_CODE_NOT_EXIST);
} else {
OutputUserInfoList outputUserInfoList = new OutputUserInfoList();
outputUserInfoList.userInfos = list;
result = RestResult.ok(outputUserInfoList);
}
setResponseContent(result, response);
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
}
}
@@ -88,6 +88,8 @@ public final class BrokerConstants {
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 QINIU_BUCKET_PAN_NAME= "qiniu.bucket_pan_name";
public static final String QINIU_BUCKET_PAN_DOMAIN = "qiniu.bucket_pan_domain";
public static final String FILE_STORAGE_ROOT = "local.media.storage.root";
@@ -146,6 +148,8 @@ public final class BrokerConstants {
public static final String SERVER_MULTI_ENDPOINT = "server.multi_endpoint";
public static final String SERVER_MULTI_PC_ENDPOINT = "server.multi_pc_endpoint";
public static final String SERVER_MULTI_PAD_ENDPOINT = "server.multi_pad_endpoint";
public static final String SERVER_MULTI_WEARABLE_ENDPOINT = "server.multi_wearable_endpoint";
public static final String SERVER_MULTI_TV_ENDPOINT = "server.multi_tv_endpoint";
public static final String SERVER_MULTI_PLATFROM_NOTIFICATION = "server.multi_platform_notification";
public static final String SERVER_MOBILE_DEFAULT_SILENT_WHEN_PC_ONLINE = "server.mobile_default_silent_when_pc_online";
public static final String SERVER_CLIENT_SUPPORT_KICKOFF_EVENT = "server.client_support_kickoff_event";
@@ -83,6 +83,10 @@ public class GetMediaUploadTokenHandler extends IMHandler<WFCMessage.GetUploadTo
bucketName = MediaServerConfig.QINIU_BUCKET_CUSTOM3_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_CUSTOM3_DOMAIN;
break;
case 12:
bucketName = MediaServerConfig.QINIU_BUCKET_PAN_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_PAN_DOMAIN;
break;
default:
bucketName = MediaServerConfig.QINIU_BUCKET_GENERAL_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_GENERAL_DOMAIN;
@@ -89,6 +89,10 @@ public class GetQiniuUploadTokenHandler extends IMHandler<Byte> {
bucketName = MediaServerConfig.QINIU_BUCKET_CUSTOM3_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_CUSTOM3_DOMAIN;
break;
case 12:
bucketName = MediaServerConfig.QINIU_BUCKET_PAN_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_PAN_DOMAIN;
break;
default:
bucketName = MediaServerConfig.QINIU_BUCKET_GENERAL_NAME;
bucketDomain = MediaServerConfig.QINIU_BUCKET_GENERAL_DOMAIN;
@@ -27,7 +27,7 @@ public class GetTokenHandler extends IMHandler<WFCMessage.GetTokenRequest> {
if(userInfo != null && userInfo.getType() == 1) {
return ErrorCode.ERROR_CODE_ROBOT_NO_TOKEN;
}
if((session.isPcClient() || session.isPadClient())) {
if(session.isPcClient() || session.isPadClient() || session.isTVClient()) {
if(m_messagesStore.isLocked(session.getUsername(), session.getClientID())) {
m_messagesStore.updateUserSettings(session.getUsername(), WFCMessage.ModifyUserSettingReq.newBuilder().setScope(UserSettingScope.UserSettingScopeLockPC).setKey(session.getClientID()).setValue("0").build(), null);
}
@@ -1870,6 +1870,10 @@ public class DatabaseStore {
sql = "update t_user_session set `_deleted` = ?, `_token` = ?, `_voip_token` = ?, `_dt` = ? where `_uid`=? and (`_platform` = ? or `_platform` = ? or `_platform` = ?) and `_cid` <> ? and `_deleted` = 0";
} else if(platform == ProtoConstants.Platform.Platform_iPad || platform == ProtoConstants.Platform.Platform_APad || platform == ProtoConstants.Platform.Platform_HarmonyPad) {
sql = "update t_user_session set `_deleted` = ?, `_token` = ?, `_voip_token` = ?, `_dt` = ? where `_uid`=? and (`_platform` = ? or `_platform` = ? or `_platform` = ?) and `_cid` <> ? and `_deleted` = 0";
} else if(platform == ProtoConstants.Platform.Platform_AndroidWearable || platform == ProtoConstants.Platform.Platform_HarmonyWearable) {
sql = "update t_user_session set `_deleted` = ?, `_token` = ?, `_voip_token` = ?, `_dt` = ? where `_uid`=? and (`_platform` = ? or `_platform` = ?) and `_cid` <> ? and `_deleted` = 0";
} else if(platform == ProtoConstants.Platform.Platform_AndroidTV || platform == ProtoConstants.Platform.Platform_AppleTV || platform == ProtoConstants.Platform.Platform_HarmonyTV) {
sql = "update t_user_session set `_deleted` = ?, `_token` = ?, `_voip_token` = ?, `_dt` = ? where `_uid`=? and (`_platform` = ? or `_platform` = ? or `_platform` = ?) and `_cid` <> ? and `_deleted` = 0";
} else {
sql = "update t_user_session set `_deleted` = ?, `_token` = ?, `_voip_token` = ?, `_dt` = ? where `_uid`=? and `_platform` = ? and `_cid` <> ? and `_deleted` = 0";
}
@@ -1897,6 +1901,13 @@ public class DatabaseStore {
statement.setInt(index++, ProtoConstants.Platform.Platform_iPad);
statement.setInt(index++, ProtoConstants.Platform.Platform_APad);
statement.setInt(index++, ProtoConstants.Platform.Platform_HarmonyPad);
} else if(platform == ProtoConstants.Platform.Platform_AndroidWearable || platform == ProtoConstants.Platform.Platform_HarmonyWearable) {
statement.setInt(index++, ProtoConstants.Platform.Platform_AndroidWearable);
statement.setInt(index++, ProtoConstants.Platform.Platform_HarmonyWearable);
} else if(platform == ProtoConstants.Platform.Platform_AndroidTV || platform == ProtoConstants.Platform.Platform_AppleTV || platform == ProtoConstants.Platform.Platform_HarmonyTV) {
statement.setInt(index++, ProtoConstants.Platform.Platform_AndroidTV);
statement.setInt(index++, ProtoConstants.Platform.Platform_AppleTV);
statement.setInt(index++, ProtoConstants.Platform.Platform_HarmonyTV);
} else {
statement.setInt(index++, platform);
}
@@ -3080,6 +3091,102 @@ public class DatabaseStore {
return outList;
}
List<WFCMessage.User> getUserInfosByMobile(String mobile, boolean includeDeleted) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet rs = null;
List<WFCMessage.User> outList = new ArrayList<>();
try {
connection = DBUtil.getConnection();
String sql = "select `_uid`, `_name`" +
", `_display_name`" +
", `_portrait`" +
", `_mobile`" +
", `_gender`" +
", `_email`" +
", `_address`" +
", `_company`" +
", `_social`" +
", `_extra`" +
", `_type`" +
", `_deleted`" +
", `_dt` from t_user where `_mobile` = ?";
if(!includeDeleted) {
sql += " and `_deleted` = 0";
}
statement = connection.prepareStatement(sql);
statement.setString(1, mobile);
rs = statement.executeQuery();
while (rs.next()) {
WFCMessage.User.Builder builder = WFCMessage.User.newBuilder();
int index = 1;
String value = rs.getString(index++);
value = (value == null ? "" : value);
builder.setUid(value);
value = rs.getString(index++);
value = (value == null ? "" : value);
builder.setName(value);
value = rs.getString(index++);
value = (value == null ? "" : value);
builder.setDisplayName(value);
value = rs.getString(index++);
value = (value == null ? "" : value);
builder.setPortrait(value);
value = rs.getString(index++);
value = (value == null ? "" : value);
builder.setMobile(value);
int gender = rs.getInt(index++);
builder.setGender(gender);
value = rs.getString(index++);
value = (value == null ? "" : value);
builder.setEmail(value);
value = rs.getString(index++);
value = (value == null ? "" : value);
builder.setAddress(value);
value = rs.getString(index++);
value = (value == null ? "" : value);
builder.setCompany(value);
value = rs.getString(index++);
value = (value == null ? "" : value);
builder.setSocial(value);
value = rs.getString(index++);
value = (value == null ? "" : value);
builder.setExtra(value);
int type = rs.getInt(index++);
builder.setType(type);
int deleted = rs.getInt(index++);
builder.setDeleted(deleted);
long longValue = rs.getLong(index++);
if(longValue <= 0)
longValue = 1;
builder.setUpdateDt(longValue);
outList.add(builder.build());
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Utility.printExecption(LOG, e, RDBS_Exception);
} finally {
DBUtil.closeDB(connection, statement, rs);
}
return outList;
}
List<WFCMessage.User> getAllUsers(int count, int offset) {
Connection connection = null;
PreparedStatement statement = null;
@@ -3177,6 +3284,69 @@ public class DatabaseStore {
return outList;
}
List<WFCMessage.Robot> getAllRobots(int count, int offset) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet rs = null;
List<WFCMessage.Robot> outList = new ArrayList<>();
try {
connection = DBUtil.getConnection();
String sql = "select `_uid`, `_owner`" +
", `_secret`" +
", `_callback`" +
", `_state`" +
", `_extra`" +
", `_dt` from t_robot limit ? offset ?";
statement = connection.prepareStatement(sql);
int index = 1;
statement.setInt(1, count);
statement.setInt(2, offset);
rs = statement.executeQuery();
while (rs.next()) {
WFCMessage.Robot.Builder builder = WFCMessage.Robot.newBuilder();
index = 1;
String value = rs.getString(index++);
value = (value == null ? "" : value);
builder.setUid(value);
value = rs.getString(index++);
value = (value == null ? "" : value);
builder.setOwner(value);
value = rs.getString(index++);
value = (value == null ? "" : value);
builder.setSecret(value);
value = rs.getString(index++);
value = (value == null ? "" : value);
builder.setCallback(value);
int state = rs.getInt(index++);
builder.setState(state);
value = rs.getString(index++);
value = (value == null ? "" : value);
builder.setExtra(value);
long longValue = rs.getLong(index++);
outList.add(builder.build());
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Utility.printExecption(LOG, e, RDBS_Exception);
} finally {
DBUtil.closeDB(connection, statement, rs);
}
return outList;
}
List<String> getUserRobotIds(String userId) {
Connection connection = null;
PreparedStatement statement = null;
@@ -2437,6 +2437,10 @@ public class MemoryMessagesStore implements IMessagesStore {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(newOwner.equals(groupInfo.getOwner())) {
return ErrorCode.ERROR_CODE_SUCCESS;
}
//check the new owner is in member list? is that necessary?
MultiMap<String, WFCMessage.GroupMember> groupMembers = hzInstance.getMultiMap(GROUP_MEMBERS);
Collection<WFCMessage.GroupMember> members = groupMembers.get(groupId);
@@ -3026,6 +3030,8 @@ public class MemoryMessagesStore implements IMessagesStore {
String pcValue = null;
String padValue = null;
String wearableValue = null;
String tvValue = null;
for (MemorySessionStore.Session s : m_Server.getStore().sessionsStore().sessionForUser(session.username)) {
if (s.getDeleted() != 0 || !m_Server.getConnectionsManager().isConnected(s.getClientID())) {
continue;
@@ -3043,6 +3049,15 @@ public class MemoryMessagesStore implements IMessagesStore {
case Platform_HarmonyPad:
padValue = System.currentTimeMillis() + "|" + s.getPlatform() + "|" + s.getClientID() + "|" + s.getPhoneName();
break;
case Platform_AndroidWearable:
case Platform_HarmonyWearable:
wearableValue = System.currentTimeMillis() + "|" + s.getPlatform() + "|" + s.getClientID() + "|" + s.getPhoneName();
break;
case Platform_AndroidTV:
case Platform_AppleTV:
case Platform_HarmonyTV:
tvValue = System.currentTimeMillis() + "|" + s.getPlatform() + "|" + s.getClientID() + "|" + s.getPhoneName();
break;
default:
break;
}
@@ -3057,6 +3072,16 @@ public class MemoryMessagesStore implements IMessagesStore {
if (!isOnlineValueEqual(padentry, padValue)) {
updateUserSettings(session.username, WFCMessage.ModifyUserSettingReq.newBuilder().setScope(kUserSettingPCOnline).setKey("Pad").setValue(padValue==null?"":padValue).build(), session.clientID);
}
WFCMessage.UserSettingEntry wearableEntry = getUserSetting(session.getUsername(), kUserSettingPCOnline, "Wearable");
if (!isOnlineValueEqual(wearableEntry, wearableValue)) {
updateUserSettings(session.username, WFCMessage.ModifyUserSettingReq.newBuilder().setScope(kUserSettingPCOnline).setKey("Wearable").setValue(wearableValue==null?"":wearableValue).build(), session.clientID);
}
WFCMessage.UserSettingEntry tvEntry = getUserSetting(session.getUsername(), kUserSettingPCOnline, "TV");
if (!isOnlineValueEqual(tvEntry, tvValue)) {
updateUserSettings(session.username, WFCMessage.ModifyUserSettingReq.newBuilder().setScope(kUserSettingPCOnline).setKey("TV").setValue(tvValue==null?"":tvValue).build(), session.clientID);
}
}
@Override
@@ -3247,11 +3272,21 @@ public class MemoryMessagesStore implements IMessagesStore {
return databaseStore.getUserInfosByEmail(email);
}
@Override
public List<WFCMessage.User> getUserInfosByMobile(String mobile, boolean includeDeleted) {
return databaseStore.getUserInfosByMobile(mobile, includeDeleted);
}
@Override
public List<WFCMessage.User> getUserInfoList(int count, int offset) {
return databaseStore.getAllUsers(count, offset);
}
@Override
public List<WFCMessage.Robot> getRobotInfoList(int count, int offset) {
return databaseStore.getAllRobots(count, offset);
}
@Override
public List<String> getUserRobotIds(String userId) {
return databaseStore.getUserRobotIds(userId);
@@ -41,6 +41,8 @@ public class MemorySessionStore implements ISessionsStore {
private boolean supportMultiEndpoint = false;
private boolean supportMultiPCEndpoint = false;
private boolean supportMultiPadEndpoint = false;
private boolean supportMultiWearableEndpoint = false;
private boolean supportMultiTVEndpoint = false;
private boolean clientSupportKickoff = false;
public static class Session implements Comparable<Session>{
@@ -101,6 +103,9 @@ public class MemorySessionStore implements ISessionsStore {
return platform == ProtoConstants.Platform.Platform_iPad || platform == ProtoConstants.Platform.Platform_APad || platform == ProtoConstants.Platform.Platform_HarmonyPad;
}
public boolean isTVClient() {
return platform == ProtoConstants.Platform.Platform_AppleTV || platform == ProtoConstants.Platform.Platform_AndroidTV || platform == ProtoConstants.Platform.Platform_HarmonyTV;
}
public int getPushType() {
return pushType;
@@ -312,6 +317,16 @@ public class MemorySessionStore implements ISessionsStore {
} catch (Exception e) {
}
try {
supportMultiWearableEndpoint = Boolean.parseBoolean(server.getConfig().getProperty(BrokerConstants.SERVER_MULTI_WEARABLE_ENDPOINT, "false"));
} catch (Exception e) {
}
try {
supportMultiTVEndpoint = Boolean.parseBoolean(server.getConfig().getProperty(BrokerConstants.SERVER_MULTI_TV_ENDPOINT, "false"));
} catch (Exception e) {
}
try {
clientSupportKickoff = Boolean.parseBoolean(server.getConfig().getProperty(BrokerConstants.SERVER_CLIENT_SUPPORT_KICKOFF_EVENT, "false"));
} catch (Exception e) {
@@ -419,6 +434,11 @@ public class MemorySessionStore implements ISessionsStore {
&& !(platform == ProtoConstants.Platform.Platform_iPad && supportMultiPadEndpoint)
&& !(platform == ProtoConstants.Platform.Platform_APad && supportMultiPadEndpoint)
&& !(platform == ProtoConstants.Platform.Platform_HarmonyPad && supportMultiPadEndpoint)
&& !(platform == ProtoConstants.Platform.Platform_AndroidWearable && supportMultiWearableEndpoint)
&& !(platform == ProtoConstants.Platform.Platform_HarmonyWearable && supportMultiWearableEndpoint)
&& !(platform == ProtoConstants.Platform.Platform_AndroidTV && supportMultiTVEndpoint)
&& !(platform == ProtoConstants.Platform.Platform_AppleTV && supportMultiTVEndpoint)
&& !(platform == ProtoConstants.Platform.Platform_HarmonyTV && supportMultiTVEndpoint)
) {
databaseStore.clearMultiEndpoint(username, clientID, platform);
if (userSessions.get(username) != null) {
@@ -445,6 +465,14 @@ public class MemorySessionStore implements ISessionsStore {
if (s.getPlatform() == ProtoConstants.Platform.Platform_OSX || s.getPlatform() == ProtoConstants.Platform.Platform_Windows || s.getPlatform() == ProtoConstants.Platform.Platform_LINUX || s.getPlatform() == ProtoConstants.Platform.Platform_HarmonyPC) {
remove = true;
}
} else if(platform == ProtoConstants.Platform.Platform_AndroidWearable || platform == ProtoConstants.Platform.Platform_HarmonyWearable) {
if (s.getPlatform() == ProtoConstants.Platform.Platform_AndroidWearable || s.getPlatform() == ProtoConstants.Platform.Platform_HarmonyWearable) {
remove = true;
}
} else if(platform == ProtoConstants.Platform.Platform_AndroidTV || platform == ProtoConstants.Platform.Platform_AppleTV || platform == ProtoConstants.Platform.Platform_HarmonyTV) {
if (s.getPlatform() == ProtoConstants.Platform.Platform_AndroidTV || s.getPlatform() == ProtoConstants.Platform.Platform_AppleTV || s.getPlatform() == ProtoConstants.Platform.Platform_HarmonyTV) {
remove = true;
}
} else { //web, microapp
if (s.getPlatform() ==platform) {
remove = true;
@@ -340,6 +340,9 @@ public class Server {
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.QINIU_BUCKET_PAN_NAME = config.getProperty(BrokerConstants.QINIU_BUCKET_PAN_NAME);
MediaServerConfig.QINIU_BUCKET_PAN_DOMAIN = config.getProperty(BrokerConstants.QINIU_BUCKET_PAN_DOMAIN);
MediaServerConfig.SERVER_IP = getServerIp(config);
MediaServerConfig.HTTP_SERVER_PORT = Integer.parseInt(config.getProperty(BrokerConstants.HTTP_SERVER_PORT));
@@ -29,6 +29,8 @@ public class MediaServerConfig {
public static String QINIU_BUCKET_CUSTOM2_DOMAIN;
public static String QINIU_BUCKET_CUSTOM3_NAME;
public static String QINIU_BUCKET_CUSTOM3_DOMAIN;
public static String QINIU_BUCKET_PAN_NAME;
public static String QINIU_BUCKET_PAN_DOMAIN;
public static String SERVER_IP = "localhost";
@@ -154,9 +154,11 @@ public interface IMessagesStore {
WFCMessage.User getUserInfoByName(String name);
WFCMessage.User getUserInfoByMobile(String mobile);
List<WFCMessage.User> getUserInfosByEmail(String email);
List<WFCMessage.User> getUserInfosByMobile(String mobile, boolean includeDeleted);
ErrorCode searchUser(String userId, String keyword, int searchType, int userType, int page, List<WFCMessage.User> users);
List<WFCMessage.User> getUserInfoList(int count, int offset);
List<WFCMessage.Robot> getRobotInfoList(int count, int offset);
List<String> getUserRobotIds(String userId);
boolean updateSystemSetting(int id, String value, String desc);
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>wildfirechat-parent</artifactId>
<groupId>cn.wildfirechat</groupId>
<version>1.4.5</version>
<version>1.4.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -43,8 +43,10 @@ public interface APIPath {
String User_Get_Info = "/admin/user/get_info";
String User_Batch_Get_Infos = "/admin/user/batch_get_infos";
String User_Get_Email_Info = "/admin/user/get_info_by_email";
String User_Get_By_Mobile = "/admin/user/get_info_by_mobile";
String User_Get_All = "/admin/user/all";
String User_Get_Robot_Info = "/admin/user/get_robot_info";
String User_Get_All_Robots = "/admin/user/get_all_robots";
String User_Get_User_Robots = "/admin/user/get_user_robots";
String User_Get_Blocked_List = "/admin/user/get_blocked_list";
String User_Check_Block_Status = "/admin/user/check_block_status";
@@ -88,6 +90,7 @@ public interface APIPath {
String Msg_Delivery = "/admin/message/delivery";
String Conversation_Delete = "/admin/conversation/delete";
String Msg_Clear_By_User = "/admin/message/clear_by_user";
String Msg_Import = "/admin/message/import";
String Create_Group = "/admin/group/create";
String Group_Dismiss = "/admin/group/del";
@@ -127,6 +130,8 @@ public interface APIPath {
String Get_User_Files = "/admin/file/user_files";
String Get_Message_File = "/admin/file/message_file";
String Get_Presigned_Upload_Url = "/admin/oss/get_upload_url";
String Conference_List = "/admin/conference/list";
String Conference_Exist = "/admin/conference/exist";
String Conference_List_Participant = "/admin/conference/list_participant";
@@ -149,6 +154,8 @@ public interface APIPath {
String Channel_Application_Get_UserInfo = "/channel/application/get_user_info";
String Robot_User_Info = "/robot/user_info";
String Robot_User_Get_Email_Info = "/robot/user/get_info_by_email";
String Robot_User_Batch_Get_Infos = "/robot/user/batch_get_infos";
String Robot_Get_Profile = "/robot/profile";
String Robot_Message_Send = "/robot/message/send";
String Robot_Message_Reply = "/robot/message/reply";
@@ -188,4 +195,6 @@ public interface APIPath {
String Robot_Moments_Update_Profiles_Value = "/robot/moments/profiles/value/push";
String Robot_Conference_Request = "/robot/conference/request";
String Robot_Get_Presigned_Upload_Url = "/robot/oss/get_upload_url";
}
@@ -0,0 +1,24 @@
/*
* This file is part of the Wildfire Chat package.
* (c) Heavyrain2012 <heavyrain.lee@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package cn.wildfirechat.pojos;
import cn.wildfirechat.proto.WFCMessage;
import java.util.List;
public class ImportMessagesData {
public static class ImportMessage {
public String sender;
public Conversation conversation;
public MessagePayload payload;
public List<String> receivers;
public long timestamp;
}
public List<ImportMessage> messages;
}
@@ -0,0 +1,27 @@
/*
* 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;
/**
* 请求预签名上传地址
* <p>
* 请求封装预签名上传地址,包括:
* <ul>
* <li>文件名</li>
* <li>文件类型</li>
* <li>媒体类型</li>
* </ul>
* </p>
*/
public class InputGetPresignedUploadUrl {
public String fileName;
public String contentType;
public int mediaType;
}
@@ -0,0 +1,7 @@
package cn.wildfirechat.pojos;
import java.util.List;
public class OutputGetRobotList {
public List<OutputRobot> robotInfoList;
}
@@ -0,0 +1,29 @@
/*
* 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;
/**
* 预签名上传地址
* <p>
* 封装预签名上传地址,包括:
* <ul>
* <li>上传地址</li>
* <li>备选上传地址</li>
* <li>下载地址</li>
* <li>类型</li>
* </ul>
* </p>
*/
public class OutputPresignedUploadUrl {
public String uploadUrl;
public String backupUploadUrl;
public String downloadUrl;
public int type;
}
@@ -56,7 +56,14 @@ public class ProtoConstants {
int Platform_Harmony = 10;
int Platform_HarmonyPad = 11;
int Platform_HarmonyPC = 12;
int Platform_MAX = Platform_HarmonyPC;
// 穿戴端 (Wearable)
int Platform_AndroidWearable = 13;
int Platform_HarmonyWearable = 14;
// TV端
int Platform_AndroidTV = 15;
int Platform_AppleTV = 16;
int Platform_HarmonyTV = 17;
int Platform_MAX = Platform_HarmonyTV;
}
//message NotifyMessage & PullMessageRequest -> type
+1 -1
View File
@@ -6,7 +6,7 @@
<!--<relativePath>../pom.xml</relativePath>-->
<artifactId>wildfirechat-parent</artifactId>
<groupId>cn.wildfirechat</groupId>
<version>1.4.5</version>
<version>1.4.6</version>
</parent>
<artifactId>distribution</artifactId>
@@ -347,6 +347,9 @@ 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
## 如果配置网盘服务,需要配置这个
qiniu.bucket_pan_name pan
qiniu.bucket_pan_domain http://pan.wildfirechat.cn
##媒体类型分类
#Media_Type_GENERAL = 0,
@@ -379,6 +382,12 @@ server.multi_pc_endpoint false
## 是否支持PAD多端登陆,当server.multi_endpoint为true时,此开关无意义,当为false时,可以单独打开PAD端多端登录。
server.multi_pad_endpoint false
## 是否支持可穿戴设备多端登陆,当server.multi_endpoint为true时,此开关无意义,当为false时,可以单独打开可穿戴设备多端登录。
server.multi_wearable_endpoint false
## 是否支持TV设备多端登陆,当server.multi_endpoint为true时,此开关无意义,当为false时,可以单独打开TV多端登录。
server.multi_tv_endpoint false
# 多平台连接状态通知(仅当multi_endpoint为false时有效),true时移动端可以收到pc或pad或web端登录的通知。
server.multi_platform_notification true
@@ -97,4 +97,4 @@ echo ""
#JAVA_OPTS="$JAVA_OPTS -Xms2G"
$JAVA -server $JAVA_OPTS $JAVA_OPTS_SCRIPT -Dlog4j.configurationFile="file:$LOG_FILE" -Dlog4j2.formatMsgNoLookups=true -Dcom.mchange.v2.c3p0.cfg.xml="$C3P0_CONF_FILE" -Dhazelcast.configuration=$HZ_CONF_FILE -Dwildfirechat.path="$WILDFIRECHAT_CONFIG_PATH" -cp "$WILDFIRECHAT_HOME/lib/*" cn.wildfirechat.server.Server
$JAVA -server $JAVA_OPTS $JAVA_OPTS_SCRIPT -Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8 -Dlog4j.configurationFile="file:$LOG_FILE" -Dlog4j2.formatMsgNoLookups=true -Dcom.mchange.v2.c3p0.cfg.xml="$C3P0_CONF_FILE" -Dhazelcast.configuration=$HZ_CONF_FILE -Dwildfirechat.path="$WILDFIRECHAT_CONFIG_PATH" -cp "$WILDFIRECHAT_HOME/lib/*" cn.wildfirechat.server.Server
+1 -1
View File
@@ -12,7 +12,7 @@
<artifactId>wildfirechat-parent</artifactId>
<packaging>pom</packaging>
<version>1.4.5</version>
<version>1.4.6</version>
<name>Wildfire Chat</name>
<description>Wildfire Chat Server</description>
<inceptionYear>2019</inceptionYear>
+7
View File
@@ -12,6 +12,13 @@
11. *** 1.3.8版本添加了server api发送消息的限制,限制消息体最大内容不能超过64KB,如果升级请注意业务系统发送消息大小。***
# 更新记录
--------------
Release note 1.4.6:
1. 添加网盘存储类型。
2. 添加可穿戴设备和TV设备类型。
3. Server SDK添加上传接口。
4. 解决转移群主给现有群主错误问题。
--------------
Release note 1.4.5:
1. 解决删除用户时保留信息错误问题。
+359
View File
@@ -0,0 +1,359 @@
# 野火IM Server Java SDK
野火IM Server Java SDK 是野火IM服务器的官方 Java 语言 SDK,提供了完整的 Admin API、Robot API 和 Channel API 接口封装。
## 功能特性
- **用户管理**:创建用户、获取用户信息、更新用户信息、封禁/解封用户等
- **群组管理**:创建群组、添加/移除成员、转让群主、设置管理员等
- **消息管理**:发送消息、广播消息、撤回消息、删除消息等
- **好友关系**:添加好友、删除好友、获取好友列表、设置黑名单等
- **聊天室管理**:创建聊天室、获取聊天室信息、销毁聊天室等
- **频道管理**:创建频道、订阅/取消订阅、发送频道消息等
- **机器人服务**:机器人消息收发、用户信息查询、群组管理等
- **会议管理**:创建会议、查询会议信息、管理参会者等(高级音视频功能)
- **朋友圈功能**:发布动态、评论、点赞等(需启用朋友圈功能)
- **敏感词管理**:添加/删除敏感词、检查敏感词等
## 安装
### Maven 依赖
```xml
<dependencies>
<!-- 必需依赖 -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<!-- SDK JAR (本地路径根据实际情况修改) -->
<dependency>
<groupId>cn.wildfirechat</groupId>
<artifactId>sdk</artifactId>
<version>1.2.2</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/sdk.jar</systemPath>
</dependency>
<dependency>
<groupId>cn.wildfirechat</groupId>
<artifactId>common</artifactId>
<version>1.2.2</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/common.jar</systemPath>
</dependency>
</dependencies>
<!-- Spring Boot 项目需要添加 includeSystemScope -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
</plugins>
</build>
```
### SDK 获取
1. 从源码编译:本项目位于 `server/sdk` 目录
2. 从发布包获取:在 release 包的 `server_sdk` 目录中
## 快速开始
### Admin 管理 API
```java
import cn.wildfirechat.sdk.AdminConfig;
import cn.wildfirechat.sdk.UserAdmin;
import cn.wildfirechat.sdk.MessageAdmin;
import cn.wildfirechat.pojos.InputOutputUserInfo;
import cn.wildfirechat.pojos.Conversation;
import cn.wildfirechat.sdk.messagecontent.TextMessageContent;
import cn.wildfirechat.proto.ProtoConstants;
import cn.wildfirechat.sdk.model.IMResult;
public class QuickStart {
public static void main(String[] args) throws Exception {
// 初始化配置
AdminConfig.initAdmin("http://localhost:18080", "123456");
// 创建用户
InputOutputUserInfo user = new InputOutputUserInfo();
user.setUserId("user1");
user.setName("user1");
user.setDisplayName("Test User");
user.setMobile("13900000000");
IMResult<OutputCreateUser> result = UserAdmin.createUser(user);
if (result.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("创建用户成功: " + result.getResult().getUserId());
}
// 获取用户 Token
IMResult<OutputGetIMTokenData> tokenResult = UserAdmin.getUserToken(
"user1",
"client1",
ProtoConstants.Platform.Platform_Android
);
if (tokenResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("Token: " + tokenResult.getResult().getToken());
}
// 发送消息
Conversation conversation = new Conversation();
conversation.setType(ProtoConstants.ConversationType.ConversationType_Private);
conversation.setTarget("user2");
conversation.setLine(0);
TextMessageContent content = new TextMessageContent("Hello, World!");
MessagePayload payload = content.encode();
IMResult<SendMessageResult> msgResult = MessageAdmin.sendMessage("user1", conversation, payload);
if (msgResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("消息发送成功,ID: " + msgResult.getResult().getMessageUid());
}
}
}
```
### Robot 机器人服务
```java
import cn.wildfirechat.sdk.RobotService;
import cn.wildfirechat.sdk.messagecontent.TextMessageContent;
public class RobotExample {
public static void main(String[] args) throws Exception {
// 初始化机器人服务
RobotService robot = new RobotService("http://localhost", "robot1", "123456");
// 获取机器人信息
IMResult<OutputRobot> profile = robot.getProfile();
if (profile.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("机器人名称: " + profile.getResult().getDisplayName());
}
// 发送消息给用户
TextMessageContent content = new TextMessageContent("Hello from robot!");
IMResult<SendMessageResult> result = robot.sendMessage("user1", content);
if (result.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("机器人消息发送成功");
}
// 获取用户信息
IMResult<OutputUserInfo> userInfo = robot.getUserInfo("user1");
if (userInfo.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("用户显示名: " + userInfo.getResult().getDisplayName());
}
}
}
```
### Channel 频道服务
```java
import cn.wildfirechat.sdk.ChannelServiceApi;
import cn.wildfirechat.sdk.messagecontent.TextMessageContent;
public class ChannelExample {
public static void main(String[] args) throws Exception {
// 初始化频道服务
ChannelServiceApi channel = new ChannelServiceApi("http://localhost", "channel1", "secret");
// 发送广播消息给订阅者
TextMessageContent content = new TextMessageContent("Channel broadcast message");
IMResult<SendMessageResult> result = channel.broadcastMessage(content);
if (result.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("频道广播消息发送成功");
}
// 用户订阅频道
IMResult<Void> subscribeResult = channel.subscribe("user1");
if (subscribeResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("订阅成功");
}
// 获取频道订阅者(商业版功能)
IMResult<OutputStringList> subscribers = channel.getSubscriberList();
if (subscribers.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("订阅者数量: " + subscribers.getResult().getList().size());
}
}
}
```
## 运行测试
SDK 提供了完整的测试示例 `Main.java`:
```bash
# 编译
mvn compile
# 运行测试(使用默认配置)
mvn exec:java -Dexec.mainClass="cn.wildfirechat.sdk.Main"
# 运行测试(自定义配置)
mvn exec:java -Dexec.mainClass="cn.wildfirechat.sdk.Main" \
-Dexec.args="http://your-server:18080 your-secret http://your-server false false"
```
### 命令行参数
```
Usage: java -jar sdk.jar adminUrl adminSecret imUrl commercialServer advanceVoip
参数说明:
adminUrl - 管理API地址,如 http://localhost:18080
adminSecret - 管理员密钥
imUrl - IM服务地址(机器人/频道使用),如 http://localhost
commercialServer - 是否为商业版服务器 (true/false)
advanceVoip - 是否启用高级音视频功能 (true/false)
```
## 项目结构
```
sdk/
├── src/main/java/cn/wildfirechat/
│ ├── sdk/
│ │ ├── AdminConfig.java # 配置类
│ │ ├── UserAdmin.java # 用户管理
│ │ ├── GroupAdmin.java # 群组管理
│ │ ├── MessageAdmin.java # 消息管理
│ │ ├── RelationAdmin.java # 好友关系管理
│ │ ├── ChatroomAdmin.java # 聊天室管理
│ │ ├── ChannelAdmin.java # 频道管理
│ │ ├── GeneralAdmin.java # 通用管理
│ │ ├── SensitiveAdmin.java # 敏感词管理
│ │ ├── ConferenceAdmin.java # 会议管理
│ │ ├── MomentsAdmin.java # 朋友圈管理
│ │ ├── RobotService.java # 机器人服务
│ │ ├── ChannelServiceApi.java # 频道服务API
│ │ ├── MeshAdmin.java # Mesh分布式管理
│ │ └── Main.java # 测试主程序
│ │ └── messagecontent/ # 消息内容类
│ │ ├── MessageContent.java
│ │ ├── TextMessageContent.java
│ │ ├── ImageMessageContent.java
│ │ ├── SoundMessageContent.java
│ │ ├── VideoMessageContent.java
│ │ ├── FileMessageContent.java
│ │ └── ...
│ ├── common/ # 公共模块(依赖)
│ └── proto/ # 协议常量
└── pom.xml # Maven配置
```
## 主要 API 说明
### 用户管理 (UserAdmin)
| 方法 | 说明 |
|------|------|
| `createUser()` | 创建用户 |
| `getUserByName()` | 按用户名获取用户 |
| `getUserByMobile()` | 按手机号获取用户 |
| `getUserByUserId()` | 按用户ID获取用户 |
| `updateUserInfo()` | 更新用户信息 |
| `getUserToken()` | 获取用户IM Token |
| `updateUserBlockStatus()` | 封禁/解封用户 |
| `checkUserOnlineStatus()` | 检查用户在线状态 |
### 群组管理 (GroupAdmin)
| 方法 | 说明 |
|------|------|
| `createGroup()` | 创建群组 |
| `getGroupInfo()` | 获取群组信息 |
| `addGroupMembers()` | 添加群成员 |
| `kickoffGroupMembers()` | 踢出群成员 |
| `transferGroup()` | 转让群主 |
| `dismissGroup()` | 解散群组 |
### 消息管理 (MessageAdmin)
| 方法 | 说明 |
|------|------|
| `sendMessage()` | 发送消息 |
| `broadcastMessage()` | 广播消息 |
| `multicastMessage()` | 群发消息 |
| `recallMessage()` | 撤回消息 |
| `deleteMessage()` | 删除消息 |
### 好友关系 (RelationAdmin)
| 方法 | 说明 |
|------|------|
| `setUserFriend()` | 设置好友关系 |
| `getFriendList()` | 获取好友列表 |
| `setUserBlacklist()` | 设置黑名单 |
| `getUserBlacklist()` | 获取黑名单列表 |
## 接口文档
- [Admin API 文档](https://docs.wildfirechat.cn/server/admin_api/) - 服务端管理接口,包括用户、群组、消息、频道等管理功能
- [Robot API 文档](https://docs.wildfirechat.cn/server/robot_api/) - 机器人服务接口,用于开发机器人应用
- [Channel API 文档](https://docs.wildfirechat.cn/server/channel_api/) - 频道服务接口,用于开发公众号/频道应用
- [IM 开发文档](https://docs.wildfirechat.cn/) - 野火IM完整开发文档
## 其他语言 SDK
| 语言 | GitHub | Gitee(码云) |
|------|------------------------------------------------------------------|-------------|
| Java SDK | [GitHub](https://github.com/wildfirechat/server/tree/master/sdk) | [Gitee](https://gitee.com/wfchat/im-server/tree/wildfirechat/sdk) |
| Python SDK | [GitHub](https://github.com/wildfirechat/server-sdk-python) | [Gitee](https://gitee.com/wfchat/im-server/server-sdk-python) |
| Go SDK | [GitHub](https://github.com/wildfirechat/server-sdk-go) | [Gitee](https://gitee.com/wfchat/server-sdk-go) |
| Node.js SDK | [GitHub](https://github.com/wildfirechat/server-sdk.js) | [Gitee](https://gitee.com/wfchat/server-sdk.js) |
## 相关链接
- [野火IM 官网](https://wildfirechat.cn/)
- [在线文档](https://docs.wildfirechat.cn/)
- [服务端源码 - GitHub](https://github.com/wildfirechat/server) | [Gitee](https://gitee.com/wfchat/im-server)
- [应用服务源码 - GitHub](https://github.com/wildfirechat/app-server) | [Gitee](https://gitee.com/wfchat/app-server)
- [机器人服务源码 - GitHub](https://github.com/wildfirechat/robot-server) | [Gitee](https://gitee.com/wfchat/robot-server)
- [推送服务源码 - GitHub](https://github.com/wildfirechat/push-server) | [Gitee](https://gitee.com/wfchat/push-server)
- [论坛交流](https://bbs.wildfirechat.cn/)
## 注意事项
1. **Admin API** 使用 18080 端口,具有超级管理权限,理论上不应对外开放,也不应让非内部服务知悉密钥。
2. **Robot API** 和 **Channel API** 使用 IM 服务的公开端口(默认 80),第三方可以使用机器人或频道与 IM 系统进行对接。
3. 商业版服务器支持更多高级功能,如在线用户统计、设备管理等。
4. 高级音视频功能需要单独启用,支持会议管理相关 API。
## 许可证
本项目采用与野火IM相同的许可证。
+7 -1
View File
@@ -3,7 +3,7 @@
<parent>
<artifactId>wildfirechat-parent</artifactId>
<groupId>cn.wildfirechat</groupId>
<version>1.4.5</version>
<version>1.4.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -68,6 +68,12 @@
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
@@ -41,24 +41,49 @@ public class ChannelServiceApi implements Closeable {
channelHttpUtils = new ChannelHttpUtils(imurl, channelId, secret);
}
/**
* 根据用户ID获取用户信息
* @param userId 用户ID
* @return 用户信息
* @throws Exception 请求失败时抛出异常
*/
public IMResult<InputOutputUserInfo> getUserInfo(String userId) throws Exception {
String path = APIPath.Channel_User_Info;
InputGetUserInfo getUserInfo = new InputGetUserInfo(userId, null, null);
return channelHttpUtils.httpJsonPost(path, getUserInfo, InputOutputUserInfo.class);
}
/**
* 根据用户名获取用户信息
* @param userName 用户名
* @return 用户信息
* @throws Exception 请求失败时抛出异常
*/
public IMResult<InputOutputUserInfo> getUserInfoByName(String userName) throws Exception {
String path = APIPath.Channel_User_Info;
InputGetUserInfo getUserInfo = new InputGetUserInfo(null, userName, null);
return channelHttpUtils.httpJsonPost(path, getUserInfo, InputOutputUserInfo.class);
}
/**
* 根据手机号获取用户信息
* @param mobile 手机号
* @return 用户信息
* @throws Exception 请求失败时抛出异常
*/
public IMResult<InputOutputUserInfo> getUserInfoByMobile(String mobile) throws Exception {
String path = APIPath.Channel_User_Info;
InputGetUserInfo getUserInfo = new InputGetUserInfo(null, null, mobile);
return channelHttpUtils.httpJsonPost(path, getUserInfo, InputOutputUserInfo.class);
}
/**
* 修改频道信息
* @param type 修改类型,参考{@link cn.wildfirechat.proto.ProtoConstants.ModifyChannelInfoType}
* @param value 修改的值
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> modifyChannelInfo(/*ProtoConstants.ModifyChannelInfoType*/int type, String value) throws Exception {
String path = APIPath.Channel_Update_Profile;
InputModifyChannelInfo modifyChannelInfo = new InputModifyChannelInfo();
@@ -67,16 +92,35 @@ public class ChannelServiceApi implements Closeable {
return channelHttpUtils.httpJsonPost(path, modifyChannelInfo, Void.class);
}
/**
* 获取频道信息
* @return 频道信息
* @throws Exception 请求失败时抛出异常
*/
public IMResult<OutputGetChannelInfo> getChannelInfo() throws Exception {
String path = APIPath.Channel_Get_Profile;
return channelHttpUtils.httpJsonPost(path, null, OutputGetChannelInfo.class);
}
/**
* 修改频道菜单
* @param menus 菜单列表
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> modifyChannelMenu(List<PojoChannelMenu> menus) throws Exception {
String menuStr = new Gson().toJson(menus);
return modifyChannelInfo(ProtoConstants.ModifyChannelInfoType.Modify_Channel_Menu, menuStr);
}
/**
* 发送频道消息
* @param line 线路
* @param targets 目标用户ID列表
* @param payload 消息内容
* @return 发送结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<SendMessageResult> sendMessage(int line, List<String> targets, MessagePayload payload) throws Exception {
String path = APIPath.Channel_Message_Send;
SendChannelMessageData messageData = new SendChannelMessageData();
@@ -86,6 +130,12 @@ public class ChannelServiceApi implements Closeable {
return channelHttpUtils.httpJsonPost(path, messageData, SendMessageResult.class);
}
/**
* 撤回频道消息
* @param messageUid 消息UID
* @return 操作结果,返回被撤回消息的UID
* @throws Exception 请求失败时抛出异常
*/
public IMResult<String> recallMessage(long messageUid) throws Exception {
String path = APIPath.Channel_Msg_Recall;
RecallMessageData messageData = new RecallMessageData();
@@ -93,6 +143,13 @@ public class ChannelServiceApi implements Closeable {
return channelHttpUtils.httpJsonPost(path, messageData, String.class);
}
/**
* 重新发布频道消息
* @param messageUid 消息UID
* @param targets 目标用户ID列表
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> republishMessage(long messageUid, List<String> targets) throws Exception {
String path = APIPath.Channel_Msg_Republish;
RepublishChannelMessageData messageData = new RepublishChannelMessageData();
@@ -101,6 +158,12 @@ public class ChannelServiceApi implements Closeable {
return channelHttpUtils.httpJsonPost(path, messageData, Void.class);
}
/**
* 订阅频道
* @param userId 用户ID
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> subscribe(String userId) throws Exception {
String path = APIPath.Channel_Subscribe;
InputChannelSubscribe input = new InputChannelSubscribe();
@@ -109,6 +172,12 @@ public class ChannelServiceApi implements Closeable {
return channelHttpUtils.httpJsonPost(path, input, Void.class);
}
/**
* 取消订阅频道
* @param userId 用户ID
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> unsubscribe(String userId) throws Exception {
String path = APIPath.Channel_Subscribe;
InputChannelSubscribe input = new InputChannelSubscribe();
@@ -117,17 +186,34 @@ public class ChannelServiceApi implements Closeable {
return channelHttpUtils.httpJsonPost(path, input, Void.class);
}
/**
* 获取频道订阅者列表
* @return 订阅者用户ID列表
* @throws Exception 请求失败时抛出异常
*/
public IMResult<OutputStringList> getSubscriberList() throws Exception {
String path = APIPath.Channel_Subscriber_List;
return channelHttpUtils.httpJsonPost(path, null, OutputStringList.class);
}
/**
* 判断用户是否订阅了频道
* @param userId 用户ID
* @return 是否订阅
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Boolean> isSubscriber(String userId) throws Exception {
String path = APIPath.Channel_Is_Subscriber;
InputUserId input = new InputUserId(userId);
return channelHttpUtils.httpJsonPost(path, input, Boolean.class);
}
/**
* 通过授权码获取应用用户信息
* @param authCode 授权码
* @return 应用用户信息
* @throws Exception 请求失败时抛出异常
*/
public IMResult<OutputApplicationUserInfo> applicationGetUserInfo(String authCode) throws Exception {
String path = APIPath.Channel_Application_Get_UserInfo;
InputApplicationGetUserInfo input = new InputApplicationGetUserInfo();
@@ -135,6 +221,11 @@ public class ChannelServiceApi implements Closeable {
return channelHttpUtils.httpJsonPost(path, input, OutputApplicationUserInfo.class);
}
/**
* 获取应用签名配置
* <p>用于客户端接入时的签名验证</p>
* @return 应用签名配置数据
*/
public OutputApplicationConfigData getApplicationSignature() {
int nonce = (int)(Math.random() * 100000 + 3);
long timestamp = System.currentTimeMillis()/1000;
@@ -149,6 +240,10 @@ public class ChannelServiceApi implements Closeable {
return configData;
}
/**
* 关闭服务,释放资源
* @throws IOException 关闭时发生IO异常
*/
@Override
public void close() throws IOException {
channelHttpUtils.close();
@@ -1,9 +1,26 @@
package cn.wildfirechat.sdk;
import cn.wildfirechat.common.APIPath;
import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.*;
import cn.wildfirechat.proto.ProtoConstants;
import cn.wildfirechat.sdk.model.IMResult;
import cn.wildfirechat.sdk.utilities.AdminHttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.InputStream;
import java.net.URLConnection;
/**
* 通用管理类
@@ -256,4 +273,331 @@ public class GeneralAdmin {
public static IMResult<String> getCustomer() throws Exception {
return AdminHttpUtils.httpJsonPost(APIPath.GET_CUSTOMER, null, String.class);
}
public static IMResult<OutputPresignedUploadUrl> getPresignedUploadUrl(String fileName, int/*ProtoConstants.MessageMediaType*/ mediaType, String contentType) throws Exception {
String path = APIPath.Get_Presigned_Upload_Url;
InputGetPresignedUploadUrl requestPojo = new InputGetPresignedUploadUrl();
requestPojo.fileName = fileName;
requestPojo.mediaType = mediaType;
requestPojo.contentType = contentType;
return AdminHttpUtils.httpJsonPost(path, requestPojo, OutputPresignedUploadUrl.class);
}
/**
* 根据文件名获取Content-Type
*
* @param fileName 文件名
* @return Content-Type,如果无法识别则返回 "application/octet-stream"
*/
private static String getContentTypeByFileName(String fileName) {
if (fileName == null || fileName.isEmpty()) {
return "application/octet-stream";
}
// 首先尝试使用 URLConnection 猜测
String contentType = URLConnection.guessContentTypeFromName(fileName);
// 如果无法识别,使用常见扩展名映射
if (contentType == null) {
String lowerName = fileName.toLowerCase();
if (lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg")) {
contentType = "image/jpeg";
} else if (lowerName.endsWith(".png")) {
contentType = "image/png";
} else if (lowerName.endsWith(".gif")) {
contentType = "image/gif";
} else if (lowerName.endsWith(".bmp")) {
contentType = "image/bmp";
} else if (lowerName.endsWith(".webp")) {
contentType = "image/webp";
} else if (lowerName.endsWith(".mp4")) {
contentType = "video/mp4";
} else if (lowerName.endsWith(".mov")) {
contentType = "video/quicktime";
} else if (lowerName.endsWith(".avi")) {
contentType = "video/x-msvideo";
} else if (lowerName.endsWith(".mp3")) {
contentType = "audio/mpeg";
} else if (lowerName.endsWith(".wav")) {
contentType = "audio/wav";
} else if (lowerName.endsWith(".pdf")) {
contentType = "application/pdf";
} else if (lowerName.endsWith(".doc")) {
contentType = "application/msword";
} else if (lowerName.endsWith(".docx")) {
contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
} else if (lowerName.endsWith(".xls")) {
contentType = "application/vnd.ms-excel";
} else if (lowerName.endsWith(".xlsx")) {
contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
} else if (lowerName.endsWith(".ppt")) {
contentType = "application/vnd.ms-powerpoint";
} else if (lowerName.endsWith(".pptx")) {
contentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
} else if (lowerName.endsWith(".txt")) {
contentType = "text/plain";
} else if (lowerName.endsWith(".html") || lowerName.endsWith(".htm")) {
contentType = "text/html";
} else if (lowerName.endsWith(".json")) {
contentType = "application/json";
} else if (lowerName.endsWith(".xml")) {
contentType = "application/xml";
} else if (lowerName.endsWith(".zip")) {
contentType = "application/zip";
} else if (lowerName.endsWith(".rar")) {
contentType = "application/x-rar-compressed";
} else if (lowerName.endsWith(".7z")) {
contentType = "application/x-7z-compressed";
} else if (lowerName.endsWith(".tar")) {
contentType = "application/x-tar";
} else if (lowerName.endsWith(".gz")) {
contentType = "application/gzip";
} else {
contentType = "application/octet-stream";
}
}
return contentType;
}
/**
* 上传文件
* <p>
* 流程:先调用getPresignedUploadUrl获取预签名上传地址,然后直接上传文件。
* 上传成功后返回文件的下载地址等信息。
* </p>
*
* @param file 要上传的文件
* @return 上传结果,包含下载地址
* @throws Exception 上传失败时抛出异常
*/
public static IMResult<String> uploadFile(File file) throws Exception {
return uploadFile(file, ProtoConstants.MessageMediaType.FILE, null);
}
/**
* 上传文件
* <p>
* 流程:先调用getPresignedUploadUrl获取预签名上传地址,然后直接上传文件。
* 上传成功后返回文件的下载地址等信息。
* </p>
*
* @param file 要上传的文件
* @param mediaType 媒体类型,参考{@link cn.wildfirechat.proto.ProtoConstants.MessageMediaType}
* @param contentType 文件Content-Type,例如 "image/jpeg", "application/octet-stream" 等;
* 如果为null或空,则根据文件名自动识别
* @return 上传结果,包含下载地址
* @throws Exception 上传失败时抛出异常
*/
public static IMResult<String> uploadFile(File file, int mediaType, String contentType) throws Exception {
if (file == null || !file.exists()) {
throw new IllegalArgumentException("文件不能为空或不存在");
}
// 如果未指定Content-Type,根据文件名自动获取
if (contentType == null || contentType.isEmpty()) {
contentType = getContentTypeByFileName(file.getName());
}
return doUploadFile(file.getName(), mediaType, contentType, file, null);
}
/**
* 执行文件上传的公共方法
* <p>
* 根据服务器类型选择不同的上传方式:
* <ul>
* <li>type = 1(七牛云):使用 POST + multipart/form-data 表单上传</li>
* <li>type = 其他(阿里云、Minio等):使用 PUT + 二进制流上传</li>
* </ul>
* </p>
*
* @param fileName 文件名
* @param mediaType 媒体类型
* @param contentType Content-Type
* @param file 文件对象(用于七牛云上传)
* @param inputStream 输入流(用于其他类型上传,可为null)
* @return 上传结果
* @throws Exception 上传失败时抛出异常
*/
private static IMResult<String> doUploadFile(String fileName, int mediaType,
String contentType,
File file,
InputStream inputStream) throws Exception {
// 1. 获取预签名上传地址
IMResult<OutputPresignedUploadUrl> presignedResult = getPresignedUploadUrl(
fileName, mediaType, contentType);
if (presignedResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
IMResult<String> imResult = new IMResult<>();
imResult.setCode(presignedResult.code);
imResult.setMsg(presignedResult.msg);
return imResult;
}
OutputPresignedUploadUrl presignedUrl = presignedResult.getResult();
if (presignedUrl == null || presignedUrl.uploadUrl == null) {
throw new Exception("预签名上传地址为空");
}
// 2. 根据服务器类型选择上传方式
if (presignedUrl.type == 1) {
// 七牛云:使用 POST + multipart/form-data 表单上传
return uploadToQiniu(presignedUrl, file, inputStream, fileName, contentType);
} else {
// 其他(阿里云、Minio、腾讯云、华为云、AWS S3等):使用 PUT 上传
return uploadToOther(presignedUrl, file, inputStream, contentType);
}
}
/**
* 上传到七牛云(type = 1)
* 使用 POST + multipart/form-data 表单格式
*/
private static IMResult<String> uploadToQiniu(OutputPresignedUploadUrl presignedUrl, File file,
InputStream inputStream, String fileName,
String contentType) throws Exception {
// 解析七牛云上传地址:格式为 "https://host?token?key"
String uploadUrl = presignedUrl.uploadUrl;
String token;
String key;
int tokenStart = uploadUrl.indexOf('?');
int keyStart = uploadUrl.indexOf('?', tokenStart + 1);
if (tokenStart == -1 || keyStart == -1) {
throw new Exception("七牛云上传地址格式错误");
}
String baseUrl = uploadUrl.substring(0, tokenStart);
token = uploadUrl.substring(tokenStart + 1, keyStart);
key = uploadUrl.substring(keyStart + 1);
HttpPost httpPost = new HttpPost(baseUrl);
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// 添加 token 和 key 字段
builder.addTextBody("token", token);
builder.addTextBody("key", key);
// 添加文件字段
if (file != null) {
builder.addPart("file", new FileBody(file, ContentType.create(contentType), fileName));
} else if (inputStream != null) {
builder.addPart("file", new InputStreamBody(inputStream, ContentType.create(contentType), fileName));
}
httpPost.setEntity(builder.build());
HttpResponse response = AdminHttpUtils.getHttpClient().execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
// 消耗响应体
if (response.getEntity() != null) {
EntityUtils.consumeQuietly(response.getEntity());
}
// 七牛云返回 200 表示成功
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) {
throw new Exception("文件上传到七牛云失败,HTTP状态码:" + statusCode);
}
IMResult<String> imResult = new IMResult<>();
imResult.setCode(0);
imResult.setResult(presignedUrl.downloadUrl);
return imResult;
} finally {
httpPost.releaseConnection();
}
}
/**
* 上传到其他对象存储(type != 1)
* 使用 PUT + 二进制流
*/
private static IMResult<String> uploadToOther(OutputPresignedUploadUrl presignedUrl, File file,
InputStream inputStream, String contentType) throws Exception {
HttpPut httpPut = new HttpPut(presignedUrl.uploadUrl);
try {
// 设置请求实体
if (file != null) {
FileEntity fileEntity = new FileEntity(file);
fileEntity.setContentType(contentType);
httpPut.setEntity(fileEntity);
} else if (inputStream != null) {
InputStreamEntity streamEntity = new InputStreamEntity(inputStream);
streamEntity.setContentType(contentType);
httpPut.setEntity(streamEntity);
}
HttpResponse response = AdminHttpUtils.getHttpClient().execute(httpPut);
int statusCode = response.getStatusLine().getStatusCode();
// 消耗响应体,确保连接可以被复用
if (response.getEntity() != null) {
EntityUtils.consumeQuietly(response.getEntity());
}
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) {
throw new Exception("文件上传失败,HTTP状态码:" + statusCode);
}
IMResult<String> imResult = new IMResult<>();
imResult.setCode(0);
imResult.setResult(presignedUrl.downloadUrl);
return imResult;
} finally {
httpPut.releaseConnection();
}
}
/**
* 上传文件(通过输入流)
* <p>
* 流程:先调用getPresignedUploadUrl获取预签名上传地址,然后直接上传文件。
* 上传成功后返回文件的下载地址等信息。
* </p>
*
* @param inputStream 文件输入流
* @param fileName 文件名
* @return 上传结果,包含下载地址
* @throws Exception 上传失败时抛出异常
*/
public static IMResult<String> uploadFile(InputStream inputStream, String fileName) throws Exception {
return uploadFile(inputStream, fileName, ProtoConstants.MessageMediaType.FILE, null);
}
/**
* 上传文件(通过输入流)
* <p>
* 流程:先调用getPresignedUploadUrl获取预签名上传地址,然后直接上传文件。
* 上传成功后返回文件的下载地址等信息。
* </p>
* <p>
* <b>注意:</b>无论上传成功还是失败,此方法都会关闭输入流。
* </p>
*
* @param inputStream 文件输入流(此方法会关闭该流)
* @param fileName 文件名
* @param mediaType 媒体类型,参考{@link cn.wildfirechat.proto.ProtoConstants.MessageMediaType}
* @param contentType 文件Content-Type,例如 "image/jpeg", "application/octet-stream" 等;
* 如果为null或空,则根据文件名自动识别
* @return 上传结果,包含下载地址
* @throws Exception 上传失败时抛出异常
*/
public static IMResult<String> uploadFile(InputStream inputStream, String fileName,
int mediaType, String contentType) throws Exception {
if (inputStream == null) {
throw new IllegalArgumentException("输入流不能为空");
}
// 如果未指定Content-Type,根据文件名自动获取
if (contentType == null || contentType.isEmpty()) {
contentType = getContentTypeByFileName(fileName);
}
return doUploadFile(fileName, mediaType, contentType, null, inputStream);
// 注意:正常流程下的流关闭在 uploadToQiniu 或 uploadToOther 的 finally 块中处理
}
}
File diff suppressed because one or more lines are too long
@@ -5,6 +5,7 @@ import cn.wildfirechat.pojos.*;
import cn.wildfirechat.sdk.model.IMResult;
import cn.wildfirechat.sdk.utilities.AdminHttpUtils;
import java.util.ArrayList;
import java.util.List;
/**
@@ -293,4 +294,20 @@ public class MessageAdmin {
InputUserId input = new InputUserId(userId);
return AdminHttpUtils.httpJsonPost(path, input, OutputTimestamp.class);
}
/**
* 导入消息。只用在服务为正式使用之前,从别的IM服务进行导入历史消息。当导入时,只能部署一个节点,可以多线程导入。当导入结束后,检查有没有异常日志,如果有异常日志需要解决后重新导入。
* 当导入完成后,重启IM服务(不要用kill -9,需要等待缓存写入)。重启之后再用客户端验证是否有历史消息可以从远端加载。另外需要保留之前IM服务的备份记录,以防有消息泄漏。
* 下面所有参数必须有效才行,如果是群组消息,还需要先创建群组。
*
* @param messages 消息列表
* @return 导入结果
* @throws Exception
*/
public static IMResult<Void> importMessage(List<ImportMessagesData.ImportMessage> messages) throws Exception {
String path = APIPath.Msg_Import;
ImportMessagesData messageData = new ImportMessagesData();
messageData.messages = messages;
return AdminHttpUtils.httpJsonPost(path, messageData, Void.class);
}
}
@@ -4,12 +4,29 @@ import cn.wildfirechat.common.APIPath;
import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.*;
import cn.wildfirechat.pojos.moments.*;
import cn.wildfirechat.proto.ProtoConstants;
import cn.wildfirechat.sdk.model.IMResult;
import cn.wildfirechat.sdk.utilities.RobotHttpUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.util.EntityUtils;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static cn.wildfirechat.proto.ProtoConstants.ApplicationType.ApplicationType_Robot;
@@ -80,6 +97,14 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, messageData, SendMessageResult.class);
}
/**
* 回复消息
* @param messageUid 原消息UID
* @param payload 消息内容
* @param only2Sender 是否只回复给原发送者
* @return 发送结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<SendMessageResult> replyMessage(long messageUid, MessagePayload payload, boolean only2Sender) throws Exception {
String path = APIPath.Robot_Message_Reply;
ReplyMessageData messageData = new ReplyMessageData();
@@ -89,6 +114,12 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, messageData, SendMessageResult.class);
}
/**
* 撤回消息
* @param messageUid 消息UID
* @return 操作结果,返回被撤回消息的UID
* @throws Exception 请求失败时抛出异常
*/
public IMResult<String> recallMessage(long messageUid) throws Exception {
String path = APIPath.Robot_Message_Recall;
RecallMessageData messageData = new RecallMessageData();
@@ -96,34 +127,101 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, messageData, String.class);
}
/**
* 更新消息内容
* @param messageUid 消息UID
* @param payload 新的消息内容
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> updateMessage(long messageUid, MessagePayload payload) throws Exception {
return updateMessage(messageUid, payload, true);
}
/**
* 更新消息内容
* @param messageUid 消息UID
* @param payload 新的消息内容
* @param distribute 是否分发给在线用户
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> updateMessage(long messageUid, MessagePayload payload, boolean distribute) throws Exception {
String path = APIPath.Robot_Message_Update;
UpdateMessageContentData updateMessageContentData = new UpdateMessageContentData();
updateMessageContentData.setMessageUid(messageUid);
updateMessageContentData.setPayload(payload);
updateMessageContentData.setUpdateTimestamp(0);
updateMessageContentData.setDistribute(1);
updateMessageContentData.setDistribute(distribute?1:0);
return robotHttpUtils.httpJsonPost(path, updateMessageContentData, Void.class);
}
/**
* 根据用户ID获取用户信息
* @param userId 用户ID
* @return 用户信息
* @throws Exception 请求失败时抛出异常
*/
public IMResult<InputOutputUserInfo> getUserInfo(String userId) throws Exception {
String path = APIPath.Robot_User_Info;
InputGetUserInfo getUserInfo = new InputGetUserInfo(userId, null, null);
return robotHttpUtils.httpJsonPost(path, getUserInfo, InputOutputUserInfo.class);
}
/**
* 根据手机号获取用户信息
* @param phone 手机号
* @return 用户信息
* @throws Exception 请求失败时抛出异常
*/
public IMResult<InputOutputUserInfo> getUserInfoByMobile(String phone) throws Exception {
String path = APIPath.Robot_User_Info;
InputGetUserInfo getUserInfo = new InputGetUserInfo(null, null, phone);
return robotHttpUtils.httpJsonPost(path, getUserInfo, InputOutputUserInfo.class);
}
/**
* 根据用户名获取用户信息
* @param userName 用户名
* @return 用户信息
* @throws Exception 请求失败时抛出异常
*/
public IMResult<InputOutputUserInfo> getUserInfoByName(String userName) throws Exception {
String path = APIPath.Robot_User_Info;
InputGetUserInfo getUserInfo = new InputGetUserInfo(null, userName, null);
return robotHttpUtils.httpJsonPost(path, getUserInfo, InputOutputUserInfo.class);
}
/**
* 根据邮箱获取用户信息列表
* @param email 邮箱地址
* @return 用户信息列表
* @throws Exception 请求失败时抛出异常
*/
public IMResult<OutputUserInfoList> getUserInfoByEmail(String email) throws Exception {
String path = APIPath.Robot_User_Get_Email_Info;
return robotHttpUtils.httpJsonPost(path, email, OutputUserInfoList.class);
}
/**
* 批量获取用户信息
* @param userIds 用户ID列表
* @return 用户信息列表
* @throws Exception 请求失败时抛出异常
*/
public IMResult<OutputUserInfoList> getBatchUsers(List<String> userIds) throws Exception {
String path = APIPath.Robot_User_Batch_Get_Infos;
InputStringList input = new InputStringList();
input.setList(userIds);
return robotHttpUtils.httpJsonPost(path, input, OutputUserInfoList.class);
}
/**
* 设置机器人消息回调地址
* @param url 回调地址
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> setCallback(String url) throws Exception {
String path = APIPath.Robot_Set_Callback;
RobotCallbackPojo pojo = new RobotCallbackPojo();
@@ -131,23 +229,43 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, pojo, Void.class);
}
/**
* 获取机器人消息回调地址
* @return 回调信息
* @throws Exception 请求失败时抛出异常
*/
public IMResult<RobotCallbackPojo> getCallback() throws Exception {
String path = APIPath.Robot_Get_Callback;
return robotHttpUtils.httpJsonPost(path, null, RobotCallbackPojo.class);
}
/**
* 删除机器人消息回调地址
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> deleteCallback() throws Exception {
String path = APIPath.Robot_Delete_Callback;
return robotHttpUtils.httpJsonPost(path, null, Void.class);
}
/**
* 获取机器人资料
* @return 机器人资料
* @throws Exception 请求失败时抛出异常
*/
public IMResult<OutputRobot> getProfile() throws Exception {
String path = APIPath.Robot_Get_Profile;
return robotHttpUtils.httpJsonPost(path, null, OutputRobot.class);
}
/*
type可选范围为MyInfoType,注意不能修改电话号码,如果要修改电话号码请使用adminapi进行修改
/**
* 更新机器人资料
* <p>type可选范围为MyInfoType,注意不能修改电话号码,如果要修改电话号码请使用adminapi进行修改</p>
* @param type 资料类型,参考MyInfoType
* @param value 资料值
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> updateProfile(int/*MyInfoType*/ type, String value) throws Exception {
String path = APIPath.Robot_Update_Profile;
@@ -155,6 +273,16 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, pojo, Void.class);
}
/**
* 创建群组
* @param group_info 群组信息
* @param members 群成员列表
* @param member_extra 成员扩展信息
* @param to_lines 指定线路
* @param notify_message 通知消息
* @return 创建结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<OutputCreateGroupResult> createGroup(PojoGroupInfo group_info, List<PojoGroupMember> members, String member_extra, List<Integer> to_lines, MessagePayload notify_message) throws Exception {
String path = APIPath.Robot_Create_Group;
PojoGroup pojoGroup = new PojoGroup();
@@ -169,6 +297,12 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, createGroup, OutputCreateGroupResult.class);
}
/**
* 获取群组信息
* @param groupId 群组ID
* @return 群组信息
* @throws Exception 请求失败时抛出异常
*/
public IMResult<PojoGroupInfo> getGroupInfo(String groupId) throws Exception {
String path = APIPath.Robot_Group_Get_Info;
InputGetGroup input = new InputGetGroup();
@@ -177,6 +311,14 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, input, PojoGroupInfo.class);
}
/**
* 解散群组
* @param groupId 群组ID
* @param to_lines 指定线路
* @param notify_message 通知消息
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> dismissGroup(String groupId, List<Integer> to_lines, MessagePayload notify_message) throws Exception {
String path = APIPath.Robot_Group_Dismiss;
InputDismissGroup dismissGroup = new InputDismissGroup();
@@ -186,6 +328,15 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, dismissGroup, Void.class);
}
/**
* 转让群组
* @param groupId 群组ID
* @param newOwner 新群主用户ID
* @param to_lines 指定线路
* @param notify_message 通知消息
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> transferGroup(String groupId, String newOwner, List<Integer> to_lines, MessagePayload notify_message) throws Exception {
String path = APIPath.Robot_Group_Transfer;
InputTransferGroup transferGroup = new InputTransferGroup();
@@ -196,6 +347,16 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, transferGroup, Void.class);
}
/**
* 修改群组信息
* @param groupId 群组ID
* @param type 修改类型,参考ModifyGroupInfoType
* @param value 修改的值
* @param to_lines 指定线路
* @param notify_message 通知消息
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> modifyGroupInfo(String groupId, /*ModifyGroupInfoType*/int type, String value, List<Integer> to_lines, MessagePayload notify_message) throws Exception {
String path = APIPath.Robot_Group_Modify_Info;
InputModifyGroupInfo modifyGroupInfo = new InputModifyGroupInfo();
@@ -208,6 +369,12 @@ public class RobotService implements Closeable {
}
/**
* 获取群成员列表
* @param groupId 群组ID
* @return 群成员列表
* @throws Exception 请求失败时抛出异常
*/
public IMResult<OutputGroupMemberList> getGroupMembers(String groupId) throws Exception {
String path = APIPath.Robot_Group_Member_List;
InputGetGroup input = new InputGetGroup();
@@ -215,6 +382,13 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, input, OutputGroupMemberList.class);
}
/**
* 获取指定群成员信息
* @param groupId 群组ID
* @param memberId 成员用户ID
* @return 群成员信息
* @throws Exception 请求失败时抛出异常
*/
public IMResult<PojoGroupMember> getGroupMember(String groupId, String memberId) throws Exception {
String path = APIPath.Robot_Group_Member_Get;
InputGetGroupMember input = new InputGetGroupMember();
@@ -223,6 +397,16 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, input, PojoGroupMember.class);
}
/**
* 添加群成员
* @param groupId 群组ID
* @param groupMembers 要添加的成员列表
* @param member_extra 成员扩展信息
* @param to_lines 指定线路
* @param notify_message 通知消息
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> addGroupMembers(String groupId, List<PojoGroupMember> groupMembers, String member_extra, List<Integer> to_lines, MessagePayload notify_message) throws Exception {
String path = APIPath.Robot_Group_Member_Add;
InputAddGroupMember addGroupMember = new InputAddGroupMember();
@@ -234,6 +418,16 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, addGroupMember, Void.class);
}
/**
* 设置群管理员
* @param groupId 群组ID
* @param groupMemberIds 成员用户ID列表
* @param isManager 是否设为管理员
* @param to_lines 指定线路
* @param notify_message 通知消息
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> setGroupManager(String groupId, List<String> groupMemberIds, boolean isManager, List<Integer> to_lines, MessagePayload notify_message) throws Exception {
String path = APIPath.Robot_Group_Set_Manager;
InputSetGroupManager addGroupMember = new InputSetGroupManager();
@@ -245,6 +439,16 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, addGroupMember, Void.class);
}
/**
* 禁言/取消禁言群成员
* @param groupId 群组ID
* @param groupMemberIds 成员用户ID列表
* @param isMute 是否禁言
* @param to_lines 指定线路
* @param notify_message 通知消息
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> muteGroupMember(String groupId, List<String> groupMemberIds, boolean isMute, List<Integer> to_lines, MessagePayload notify_message) throws Exception {
String path = APIPath.Robot_Group_Mute_Member;
InputMuteGroupMember addGroupMember = new InputMuteGroupMember();
@@ -256,6 +460,16 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, addGroupMember, Void.class);
}
/**
* 允许/禁止群成员
* @param groupId 群组ID
* @param groupMemberIds 成员用户ID列表
* @param isAllow 是否允许
* @param to_lines 指定线路
* @param notify_message 通知消息
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> allowGroupMember(String groupId, List<String> groupMemberIds, boolean isAllow, List<Integer> to_lines, MessagePayload notify_message) throws Exception {
String path = APIPath.Robot_Group_Allow_Member;
InputMuteGroupMember addGroupMember = new InputMuteGroupMember();
@@ -267,6 +481,15 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, addGroupMember, Void.class);
}
/**
* 踢出群成员
* @param groupId 群组ID
* @param groupMemberIds 要踢出的成员用户ID列表
* @param to_lines 指定线路
* @param notify_message 通知消息
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> kickoffGroupMembers(String groupId, List<String> groupMemberIds, List<Integer> to_lines, MessagePayload notify_message) throws Exception {
String path = APIPath.Robot_Group_Member_Kickoff;
InputKickoffGroupMember kickoffGroupMember = new InputKickoffGroupMember();
@@ -277,6 +500,14 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, kickoffGroupMember, Void.class);
}
/**
* 退出群组
* @param groupId 群组ID
* @param to_lines 指定线路
* @param notify_message 通知消息
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> quitGroup(String groupId, List<Integer> to_lines, MessagePayload notify_message) throws Exception {
String path = APIPath.Robot_Group_Member_Quit;
InputQuitGroup quitGroup = new InputQuitGroup();
@@ -286,6 +517,16 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, quitGroup, Void.class);
}
/**
* 设置群成员昵称
* @param groupId 群组ID
* @param memberId 成员用户ID
* @param alias 群昵称
* @param to_lines 指定线路
* @param notify_message 通知消息
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> setGroupMemberAlias(String groupId, String memberId, String alias, List<Integer> to_lines, MessagePayload notify_message) throws Exception {
String path = APIPath.Robot_Group_Set_Member_Alias;
InputSetGroupMemberAlias input = new InputSetGroupMemberAlias();
@@ -297,6 +538,16 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, input, Void.class);
}
/**
* 设置群成员扩展信息
* @param groupId 群组ID
* @param memberId 成员用户ID
* @param extra 扩展信息
* @param to_lines 指定线路
* @param notify_message 通知消息
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> setGroupMemberExtra(String groupId, String memberId, String extra, List<Integer> to_lines, MessagePayload notify_message) throws Exception {
String path = APIPath.Robot_Group_Set_Member_Extra;
InputSetGroupMemberExtra input = new InputSetGroupMemberExtra();
@@ -308,6 +559,12 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, input, Void.class);
}
/**
* 通过授权码获取应用用户信息
* @param authCode 授权码
* @return 应用用户信息
* @throws Exception 请求失败时抛出异常
*/
public IMResult<OutputApplicationUserInfo> applicationGetUserInfo(String authCode) throws Exception {
String path = APIPath.Robot_Application_Get_UserInfo;
InputApplicationGetUserInfo input = new InputApplicationGetUserInfo();
@@ -315,6 +572,11 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, input, OutputApplicationUserInfo.class);
}
/**
* 获取应用签名配置
* <p>用于客户端接入时的签名验证</p>
* @return 应用签名配置数据
*/
public OutputApplicationConfigData getApplicationSignature() {
int nonce = (int)(Math.random() * 100000 + 3);
long timestamp = System.currentTimeMillis()/1000;
@@ -329,12 +591,36 @@ public class RobotService implements Closeable {
return configData;
}
/**
* 发送会议相关请求
* @param robotId 机器人ID
* @param clientId 客户端ID
* @param request 请求类型
* @param sessionId 会话ID
* @param roomId 会议室ID
* @param data 请求数据
* @param advance 是否高级请求
* @return 请求结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<String> sendConferenceRequest(String robotId, String clientId, String request, long sessionId, String roomId, String data, boolean advance) throws Exception {
String path = APIPath.Robot_Conference_Request;
InputConferenceRequest input = new InputConferenceRequest(robotId, clientId, request, sessionId, roomId, data, advance);
return robotHttpUtils.httpJsonPost(path, input, String.class);
}
/**
* 发布朋友圈动态
* @param type 内容类型,参考MomentsContentType
* @param text 文本内容
* @param medias 媒体列表
* @param toUsers 可见用户列表
* @param excludeUsers 不可见用户列表
* @param mentionedUsers 提及用户列表
* @param extra 扩展信息
* @return 发布结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<FeedPojo> postMomentsFeed(int/*MomentsContentType*/ type, String text, List<MediaEntry> medias, List<String> toUsers, List<String> excludeUsers, List<String> mentionedUsers, String extra) throws Exception {
String path = APIPath.Robot_Moments_Post_Feed;
FeedPojo feedPojo = new FeedPojo();
@@ -359,6 +645,19 @@ public class RobotService implements Closeable {
return feedResult;
}
/**
* 更新朋友圈动态
* @param feedId 动态ID
* @param type 内容类型,参考MomentsContentType
* @param text 文本内容
* @param medias 媒体列表
* @param toUsers 可见用户列表
* @param excludeUsers 不可见用户列表
* @param mentionedUsers 提及用户列表
* @param extra 扩展信息
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> updateMomentsFeed(long feedId, int/*MomentsContentType*/ type, String text, List<MediaEntry> medias, List<String> toUsers, List<String> excludeUsers, List<String> mentionedUsers, String extra) throws Exception {
String path = APIPath.Robot_Moments_Update_Feed;
FeedPojo feedPojo = new FeedPojo();
@@ -373,6 +672,14 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, feedPojo, Void.class);
}
/**
* 获取朋友圈动态列表
* @param feedId 起始动态ID
* @param count 获取数量
* @param user 指定用户ID,为空表示获取所有
* @return 动态列表
* @throws Exception 请求失败时抛出异常
*/
public IMResult<FeedsPojo> getMomentsFeeds(long feedId, int count, String user) throws Exception {
String path = APIPath.Robot_Moments_Pull_Feeds;
PullFeedRequestPojo requestPojo = new PullFeedRequestPojo();
@@ -382,6 +689,12 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, requestPojo, FeedsPojo.class);
}
/**
* 获取单条朋友圈动态
* @param feedId 动态ID
* @return 动态详情
* @throws Exception 请求失败时抛出异常
*/
public IMResult<FeedPojo> getMomentsFeed(long feedId) throws Exception {
String path = APIPath.Robot_Moments_Fetch_Feed;
PullOneFeedRequestPojo requestPojo = new PullOneFeedRequestPojo();
@@ -389,6 +702,12 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, requestPojo, FeedPojo.class);
}
/**
* 删除朋友圈动态
* @param feedId 动态ID
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> deleteMomentsFeed(long feedId) throws Exception {
String path = APIPath.Robot_Moments_Recall_Feed;
IdPojo requestPojo = new IdPojo();
@@ -396,6 +715,17 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, requestPojo, Void.class);
}
/**
* 发布朋友圈评论
* @param feedId 动态ID
* @param replyId 回复的评论ID
* @param type 评论类型,参考MomentsCommentType
* @param text 评论内容
* @param replyTo 回复目标用户ID
* @param extra 扩展信息
* @return 评论结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<CommentPojo> postMomentsComment(long feedId, long replyId, int/*MomentsCommentType*/ type, String text, String replyTo, String extra) throws Exception {
String path = APIPath.Robot_Moments_Post_Comment;
CommentPojo commentPojo = new CommentPojo();
@@ -419,6 +749,13 @@ public class RobotService implements Closeable {
return feedResult;
}
/**
* 删除朋友圈评论
* @param feedId 动态ID
* @param commentId 评论ID
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> deleteMomentsComment(long feedId, long commentId) throws Exception {
String path = APIPath.Robot_Moments_Recall_Comment;
IdPojo requestPojo = new IdPojo();
@@ -427,6 +764,12 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, requestPojo, Void.class);
}
/**
* 获取用户朋友圈资料
* @param userId 用户ID
* @return 朋友圈资料
* @throws Exception 请求失败时抛出异常
*/
public IMResult<MomentProfilePojo> getUserMomentsProfile(String userId) throws Exception {
String path = APIPath.Robot_Moments_Fetch_Profiles;
PullProfileRequestPojo requestPojo = new PullProfileRequestPojo();
@@ -434,6 +777,12 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, requestPojo, MomentProfilePojo.class);
}
/**
* 更新朋友圈背景图
* @param url 背景图URL
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> updateMomentsBackgroundUrl(String url) throws Exception {
String path = APIPath.Robot_Moments_Update_Profiles_Value;
PushProfileValueRequestPojo requestPojo = new PushProfileValueRequestPojo();
@@ -442,6 +791,12 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, requestPojo, Void.class);
}
/**
* 更新朋友圈陌生人可见数量
* @param count 可见数量
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> updateMomentsStrangerVisibleCount(int count) throws Exception {
String path = APIPath.Robot_Moments_Update_Profiles_Value;
PushProfileValueRequestPojo requestPojo = new PushProfileValueRequestPojo();
@@ -450,6 +805,12 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, requestPojo, Void.class);
}
/**
* 更新朋友圈可见范围
* @param scope 可见范围,参考MomentsVisibleScope
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> updateMomentsVisibleScope(int/*MomentsVisibleScope*/ scope) throws Exception {
String path = APIPath.Robot_Moments_Update_Profiles_Value;
PushProfileValueRequestPojo requestPojo = new PushProfileValueRequestPojo();
@@ -458,6 +819,13 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, requestPojo, Void.class);
}
/**
* 更新朋友圈黑名单
* @param addList 要添加的用户ID列表
* @param removeList 要移除的用户ID列表
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> updateMomentsBlackList(List<String> addList, List<String> removeList) throws Exception {
String path = APIPath.Robot_Moments_Update_Profiles_List_Value;
PushProfileListRequestPojo requestPojo = new PushProfileListRequestPojo();
@@ -467,6 +835,13 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, requestPojo, Void.class);
}
/**
* 更新朋友圈屏蔽列表
* @param addList 要添加的用户ID列表
* @param removeList 要移除的用户ID列表
* @return 操作结果
* @throws Exception 请求失败时抛出异常
*/
public IMResult<Void> updateMomentsBlockList(List<String> addList, List<String> removeList) throws Exception {
String path = APIPath.Robot_Moments_Update_Profiles_List_Value;
PushProfileListRequestPojo requestPojo = new PushProfileListRequestPojo();
@@ -476,6 +851,345 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, requestPojo, Void.class);
}
/**
* 获取预签名上传地址
* @param fileName 文件名
* @param mediaType 媒体类型,参考{@link cn.wildfirechat.proto.ProtoConstants.MessageMediaType}
* @param contentType 文件Content-Type
* @return 预签名上传地址信息
* @throws Exception 请求失败时抛出异常
*/
public IMResult<OutputPresignedUploadUrl> getPresignedUploadUrl(String fileName, int/*ProtoConstants.MessageMediaType*/ mediaType, String contentType) throws Exception {
String path = APIPath.Robot_Get_Presigned_Upload_Url;
InputGetPresignedUploadUrl requestPojo = new InputGetPresignedUploadUrl();
requestPojo.fileName = fileName;
requestPojo.mediaType = mediaType;
requestPojo.contentType = contentType;
return robotHttpUtils.httpJsonPost(path, requestPojo, OutputPresignedUploadUrl.class);
}
/**
* 根据文件名获取Content-Type
*
* @param fileName 文件名
* @return Content-Type,如果无法识别则返回 "application/octet-stream"
*/
private String getContentTypeByFileName(String fileName) {
if (fileName == null || fileName.isEmpty()) {
return "application/octet-stream";
}
// 首先尝试使用 URLConnection 猜测
String contentType = URLConnection.guessContentTypeFromName(fileName);
// 如果无法识别,使用常见扩展名映射
if (contentType == null) {
String lowerName = fileName.toLowerCase();
if (lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg")) {
contentType = "image/jpeg";
} else if (lowerName.endsWith(".png")) {
contentType = "image/png";
} else if (lowerName.endsWith(".gif")) {
contentType = "image/gif";
} else if (lowerName.endsWith(".bmp")) {
contentType = "image/bmp";
} else if (lowerName.endsWith(".webp")) {
contentType = "image/webp";
} else if (lowerName.endsWith(".mp4")) {
contentType = "video/mp4";
} else if (lowerName.endsWith(".mov")) {
contentType = "video/quicktime";
} else if (lowerName.endsWith(".avi")) {
contentType = "video/x-msvideo";
} else if (lowerName.endsWith(".mp3")) {
contentType = "audio/mpeg";
} else if (lowerName.endsWith(".wav")) {
contentType = "audio/wav";
} else if (lowerName.endsWith(".pdf")) {
contentType = "application/pdf";
} else if (lowerName.endsWith(".doc")) {
contentType = "application/msword";
} else if (lowerName.endsWith(".docx")) {
contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
} else if (lowerName.endsWith(".xls")) {
contentType = "application/vnd.ms-excel";
} else if (lowerName.endsWith(".xlsx")) {
contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
} else if (lowerName.endsWith(".ppt")) {
contentType = "application/vnd.ms-powerpoint";
} else if (lowerName.endsWith(".pptx")) {
contentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
} else if (lowerName.endsWith(".txt")) {
contentType = "text/plain";
} else if (lowerName.endsWith(".html") || lowerName.endsWith(".htm")) {
contentType = "text/html";
} else if (lowerName.endsWith(".json")) {
contentType = "application/json";
} else if (lowerName.endsWith(".xml")) {
contentType = "application/xml";
} else if (lowerName.endsWith(".zip")) {
contentType = "application/zip";
} else if (lowerName.endsWith(".rar")) {
contentType = "application/x-rar-compressed";
} else if (lowerName.endsWith(".7z")) {
contentType = "application/x-7z-compressed";
} else if (lowerName.endsWith(".tar")) {
contentType = "application/x-tar";
} else if (lowerName.endsWith(".gz")) {
contentType = "application/gzip";
} else {
contentType = "application/octet-stream";
}
}
return contentType;
}
/**
* 上传文件
* <p>
* 流程:先调用getPresignedUploadUrl获取预签名上传地址,然后直接上传文件。
* 上传成功后返回文件的下载地址等信息。
* </p>
*
* @param file 要上传的文件
* @return 上传结果,包含下载地址
* @throws Exception 上传失败时抛出异常
*/
public IMResult<String> uploadFile(File file) throws Exception {
return uploadFile(file, ProtoConstants.MessageMediaType.FILE, null);
}
/**
* 上传文件
* <p>
* 流程:先调用getPresignedUploadUrl获取预签名上传地址,然后直接上传文件。
* 上传成功后返回文件的下载地址等信息。
* </p>
*
* @param file 要上传的文件
* @param mediaType 媒体类型,参考{@link cn.wildfirechat.proto.ProtoConstants.MessageMediaType}
* @param contentType 文件Content-Type,例如 "image/jpeg", "application/octet-stream" 等;
* 如果为null或空,则根据文件名自动识别
* @return 上传结果,包含下载地址
* @throws Exception 上传失败时抛出异常
*/
public IMResult<String> uploadFile(File file, int mediaType, String contentType) throws Exception {
if (file == null || !file.exists()) {
throw new IllegalArgumentException("文件不能为空或不存在");
}
// 如果未指定Content-Type,根据文件名自动获取
if (contentType == null || contentType.isEmpty()) {
contentType = getContentTypeByFileName(file.getName());
}
return doUploadFile(file.getName(), mediaType, contentType, file, null);
}
/**
* 执行文件上传的公共方法
* <p>
* 根据服务器类型选择不同的上传方式:
* <ul>
* <li>type = 1(七牛云):使用 POST + multipart/form-data 表单上传</li>
* <li>type = 其他(阿里云、Minio等):使用 PUT + 二进制流上传</li>
* </ul>
* </p>
*
* @param fileName 文件名
* @param mediaType 媒体类型
* @param contentType Content-Type
* @param file 文件对象(用于七牛云上传)
* @param inputStream 输入流(用于其他类型上传,可为null)
* @return 上传结果
* @throws Exception 上传失败时抛出异常
*/
private IMResult<String> doUploadFile(String fileName, int mediaType,
String contentType,
File file,
InputStream inputStream) throws Exception {
// 1. 获取预签名上传地址
IMResult<OutputPresignedUploadUrl> presignedResult = getPresignedUploadUrl(
fileName, mediaType, contentType);
if (presignedResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
IMResult<String> imResult = new IMResult<>();
imResult.setCode(presignedResult.code);
imResult.setMsg(presignedResult.msg);
return imResult;
}
OutputPresignedUploadUrl presignedUrl = presignedResult.getResult();
if (presignedUrl == null || presignedUrl.uploadUrl == null) {
throw new Exception("预签名上传地址为空");
}
// 2. 根据服务器类型选择上传方式
if (presignedUrl.type == 1) {
// 七牛云:使用 POST + multipart/form-data 表单上传
return uploadToQiniu(presignedUrl, file, inputStream, fileName, contentType);
} else {
// 其他(阿里云、Minio、腾讯云、华为云、AWS S3等):使用 PUT 上传
return uploadToOther(presignedUrl, file, inputStream, contentType);
}
}
/**
* 上传到七牛云(type = 1)
* 使用 POST + multipart/form-data 表单格式
*/
private IMResult<String> uploadToQiniu(OutputPresignedUploadUrl presignedUrl, File file,
InputStream inputStream, String fileName,
String contentType) throws Exception {
// 解析七牛云上传地址:格式为 "https://host?token?key"
String uploadUrl = presignedUrl.uploadUrl;
String token;
String key;
int tokenStart = uploadUrl.indexOf('?');
int keyStart = uploadUrl.indexOf('?', tokenStart + 1);
if (tokenStart == -1 || keyStart == -1) {
throw new Exception("七牛云上传地址格式错误");
}
String baseUrl = uploadUrl.substring(0, tokenStart);
token = uploadUrl.substring(tokenStart + 1, keyStart);
key = uploadUrl.substring(keyStart + 1);
HttpPost httpPost = new HttpPost(baseUrl);
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// 添加 token 和 key 字段
builder.addTextBody("token", token);
builder.addTextBody("key", key);
// 添加文件字段
if (file != null) {
builder.addPart("file", new FileBody(file, ContentType.create(contentType), fileName));
} else if (inputStream != null) {
builder.addPart("file", new InputStreamBody(inputStream, ContentType.create(contentType), fileName));
}
httpPost.setEntity(builder.build());
HttpResponse response = robotHttpUtils.getHttpClient().execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
// 消耗响应体
if (response.getEntity() != null) {
EntityUtils.consumeQuietly(response.getEntity());
}
// 七牛云返回 200 表示成功
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) {
throw new Exception("文件上传到七牛云失败,HTTP状态码:" + statusCode);
}
IMResult<String> imResult = new IMResult<>();
imResult.setCode(0);
imResult.setResult(presignedUrl.downloadUrl);
return imResult;
} finally {
httpPost.releaseConnection();
}
}
/**
* 上传到其他对象存储(type != 1)
* 使用 PUT + 二进制流
*/
private IMResult<String> uploadToOther(OutputPresignedUploadUrl presignedUrl, File file,
InputStream inputStream, String contentType) throws Exception {
HttpPut httpPut = new HttpPut(presignedUrl.uploadUrl);
try {
// 设置请求实体
if (file != null) {
FileEntity fileEntity = new FileEntity(file);
fileEntity.setContentType(contentType);
httpPut.setEntity(fileEntity);
} else if (inputStream != null) {
InputStreamEntity streamEntity = new InputStreamEntity(inputStream);
streamEntity.setContentType(contentType);
httpPut.setEntity(streamEntity);
}
HttpResponse response = robotHttpUtils.getHttpClient().execute(httpPut);
int statusCode = response.getStatusLine().getStatusCode();
// 消耗响应体,确保连接可以被复用
if (response.getEntity() != null) {
EntityUtils.consumeQuietly(response.getEntity());
}
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) {
throw new Exception("文件上传失败,HTTP状态码:" + statusCode);
}
IMResult<String> imResult = new IMResult<>();
imResult.setCode(0);
imResult.setResult(presignedUrl.downloadUrl);
return imResult;
} finally {
httpPut.releaseConnection();
}
}
/**
* 上传文件(通过输入流)
* <p>
* 流程:先调用getPresignedUploadUrl获取预签名上传地址,然后直接上传文件。
* 上传成功后返回文件的下载地址等信息。
* </p>
*
* @param inputStream 文件输入流
* @param fileName 文件名
* @return 上传结果,包含下载地址
* @throws Exception 上传失败时抛出异常
*/
public IMResult<String> uploadFile(InputStream inputStream, String fileName) throws Exception {
return uploadFile(inputStream, fileName, ProtoConstants.MessageMediaType.FILE, null);
}
/**
* 上传文件(通过输入流)
* <p>
* 流程:先调用getPresignedUploadUrl获取预签名上传地址,然后直接上传文件。
* 上传成功后返回文件的下载地址等信息。
* </p>
* <p>
* <b>注意:</b>无论上传成功还是失败,此方法都会关闭输入流。
* </p>
*
* @param inputStream 文件输入流(此方法会关闭该流)
* @param fileName 文件名
* @param mediaType 媒体类型,参考{@link cn.wildfirechat.proto.ProtoConstants.MessageMediaType}
* @param contentType 文件Content-Type,例如 "image/jpeg", "application/octet-stream" 等;
* 如果为null或空,则根据文件名自动识别
* @return 上传结果,包含下载地址
* @throws Exception 上传失败时抛出异常
*/
public IMResult<String> uploadFile(InputStream inputStream, String fileName,
int mediaType, String contentType) throws Exception {
if (inputStream == null) {
throw new IllegalArgumentException("输入流不能为空");
}
// 如果未指定Content-Type,根据文件名自动获取
if (contentType == null || contentType.isEmpty()) {
contentType = getContentTypeByFileName(fileName);
}
return doUploadFile(fileName, mediaType, contentType, null, inputStream);
// 注意:正常流程下的流关闭在 uploadToQiniu 或 uploadToOther 的 finally 块中处理
}
/**
* 关闭服务,释放资源
* @throws IOException 关闭时发生IO异常
*/
@Override
public void close() throws IOException {
robotHttpUtils.close();
@@ -70,6 +70,7 @@ public class UserAdmin {
/**
* 根据手机号获取用户信息(不包含已删除用户)
* @deprecated 用户手机号码不要求唯一,正常应该业务系统保证电话号码唯一。如果业务系统不限制电话号码唯一,可能一个号码有多个用户,此方法只能返回一个,此时建议使用 {@link #getUsersByMobile(String mobile, boolean includeDeleted)}
* @param mobile 手机号
* @return 用户信息
* @throws Exception 请求失败时抛出异常
@@ -79,7 +80,8 @@ public class UserAdmin {
}
/**
* 根据手机号获取用户信息
* 根据手机号获取用户信息,
* @deprecated 用户手机号码不要求唯一,正常应该业务系统保证电话号码唯一。如果业务系统不限制电话号码唯一,可能一个号码有多个用户,此方法只能返回一个,此时建议使用 {@link #getUsersByMobile(String mobile, boolean includeDeleted)}
* @param mobile 手机号
* @param includeDeleted 是否包含已删除的用户
* @return 用户信息
@@ -91,6 +93,19 @@ public class UserAdmin {
return AdminHttpUtils.httpJsonPost(path, getUserInfo, InputOutputUserInfo.class);
}
/**
* 根据电话号码获取用户信息列表
* @param mobile 邮箱地址
* @param includeDeleted 是否包含已删除的用户
* @return 用户信息列表
* @throws Exception 请求失败时抛出异常
*/
public static IMResult<OutputUserInfoList> getUsersByMobile(String mobile, boolean includeDeleted) throws Exception {
String path = APIPath.User_Get_By_Mobile;
InputGetUserInfo getUserInfo = new InputGetUserInfo(null, null, mobile, includeDeleted);
return AdminHttpUtils.httpJsonPost(path, getUserInfo, OutputUserInfoList.class);
}
/**
* 根据邮箱获取用户信息列表
* @param email 邮箱地址
@@ -117,6 +132,21 @@ public class UserAdmin {
return AdminHttpUtils.httpJsonPost(path, input, OutputGetUserList.class);
}
/**
* 获取所有机器人列表(分页)
* @param count 每页数量
* @param offset 偏移量
* @return 机器人列表
* @throws Exception 请求失败时抛出异常
*/
public static IMResult<OutputGetRobotList> getAllRobots(int count, int offset) throws Exception {
String path = APIPath.User_Get_All_Robots;
InputGetUserList input = new InputGetUserList();
input.count = count;
input.offset = offset;
return AdminHttpUtils.httpJsonPost(path, input, OutputGetRobotList.class);
}
/**
* 批量获取用户信息
* @param userIds 用户ID列表
@@ -46,6 +46,11 @@ public class AdminHttpUtils extends HttpUtils {
// ======================== 线程安全的全局变量 ========================
private static volatile String adminUrl;
private static volatile String adminSecret;
public static CloseableHttpClient getHttpClient() {
return httpClient;
}
private static volatile CloseableHttpClient httpClient;
@@ -120,6 +120,10 @@ public class RobotHttpUtils extends HttpUtils implements Closeable {
return robotSecret;
}
public CloseableHttpClient getHttpClient() {
return httpClient;
}
@Override
public void close() throws IOException {
httpClient.close();