Compare commits

...
11 Commits
Author SHA1 Message Date
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
32 changed files with 2099 additions and 40 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
+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);
@@ -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,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;
}
}
@@ -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);
}
@@ -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
@@ -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";
+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>
@@ -127,6 +127,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";
@@ -188,4 +190,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,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,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>
@@ -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 块中处理
}
}
+561 -7
View File
@@ -1,6 +1,9 @@
package cn.wildfirechat.sdk;
import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.mesh.PojoDomainPingResponse;
import cn.wildfirechat.pojos.mesh.PojoSearchUserRes;
import cn.wildfirechat.pojos.mesh.PojoUserConferenceResponse;
import cn.wildfirechat.pojos.moments.CommentPojo;
import cn.wildfirechat.pojos.moments.FeedPojo;
import cn.wildfirechat.pojos.moments.FeedsPojo;
@@ -94,6 +97,9 @@ public class Main {
testRobot();
// 测试频道功能
testChannel();
//测试Mesh相关API,用于分布式IM。Mesh相关测试依赖环境,不具备测绘条件,注释掉。
//testMesh();
}
@@ -423,6 +429,15 @@ public class Main {
System.exit(-1);
}
//测试踢下线用户客户端
IMResult<Void> kickoffResult = UserAdmin.kickoffUserClient(userInfo.getUserId(), null);
if (kickoffResult != null && kickoffResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("kickoff user client success");
} else {
System.out.println("kickoff user client failure");
System.exit(-1);
}
//慎用,这个方法可能功能不完全,如果用户不在需要,建议使用block功能屏蔽用户
// 销毁用户(物理删除,不可恢复)
IMResult<Void> voidIMResult = UserAdmin.destroyUser("user11");
@@ -634,6 +649,15 @@ public class Main {
System.out.println("set friend extra failure");
System.exit(-1);
}
//测试获取用户的机器人列表
IMResult<OutputStringList> userRobotsResult = UserAdmin.getUserRobots("ff1");
if (userRobotsResult != null && userRobotsResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("get user robots success");
} else {
System.out.println("get user robots failure");
System.exit(-1);
}
}
//***********************************************
//**** 群组相关功能
@@ -868,6 +892,60 @@ public class Main {
System.exit(-1);
}
//测试批量获取群组信息
IMResult<PojoGroupInfoList> batchGroupInfoResult = GroupAdmin.batchGroupInfos(Arrays.asList(groupInfo.getTarget_id()));
if (batchGroupInfoResult != null && batchGroupInfoResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("batch get group info success");
} else {
System.out.println("batch get group info failure");
System.exit(-1);
}
//测试群备注功能
String groupRemark = "test group remark";
IMResult<Void> setGroupRemarkResult = GroupAdmin.setGroupRemark("user1", groupInfo.getTarget_id(), groupRemark);
if (setGroupRemarkResult != null && setGroupRemarkResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("set group remark success");
} else {
System.out.println("set group remark failure");
System.exit(-1);
}
IMResult<String> getGroupRemarkResult = GroupAdmin.getGroupRemark("user1", groupInfo.getTarget_id());
if (getGroupRemarkResult != null && getGroupRemarkResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS && groupRemark.equals(getGroupRemarkResult.getResult())) {
System.out.println("get group remark success");
} else {
System.out.println("get group remark failure");
System.exit(-1);
}
//测试收藏群功能
IMResult<Void> setFavGroupResult = GroupAdmin.setFavGroup("user1", groupInfo.getTarget_id(), true);
if (setFavGroupResult != null && setFavGroupResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("set fav group success");
} else {
System.out.println("set fav group failure");
System.exit(-1);
}
Thread.sleep(1000);
IMResult<Boolean> isFavGroupResult = GroupAdmin.isFavGroup("user1", groupInfo.getTarget_id());
if (isFavGroupResult != null && isFavGroupResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS && isFavGroupResult.getResult()) {
System.out.println("is fav group success");
} else {
System.out.println("is fav group failure");
System.exit(-1);
}
//取消收藏
setFavGroupResult = GroupAdmin.setFavGroup("user1", groupInfo.getTarget_id(), false);
if (setFavGroupResult != null && setFavGroupResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("cancel fav group success");
} else {
System.out.println("cancel fav group failure");
System.exit(-1);
}
//仅专业版支持
if (commercialServer) {
//开启群成员禁言
@@ -905,6 +983,24 @@ public class Main {
System.exit(-1);
}
}
//测试解散群组
IMResult<Void> dismissGroupResult = GroupAdmin.dismissGroup("user2", groupInfo.getTarget_id(), null, null);
if (dismissGroupResult != null && dismissGroupResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("dismiss group success");
} else {
System.out.println("dismiss group failure");
System.exit(-1);
}
//验证群组已被解散
resultGetGroupInfo = GroupAdmin.getGroupInfo(groupInfo.getTarget_id());
if (resultGetGroupInfo != null && resultGetGroupInfo.getErrorCode() == ErrorCode.ERROR_CODE_NOT_EXIST) {
System.out.println("group dismissed verified");
} else {
System.out.println("group dismiss verify failure");
System.exit(-1);
}
}
//***********************************************
@@ -1006,6 +1102,14 @@ public class Main {
System.out.println("failure");
}
//测试删除广播消息
IMResult<Void> deleteBroadCastResult = MessageAdmin.deleteBroadCastMessage("user1", resultBroadcastMessage.result.getMessageUid());
if (deleteBroadCastResult != null && deleteBroadCastResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("delete broadcast message success");
} else {
System.out.println("delete broadcast message failure");
}
IMResult<OutputTimestamp> timestampResult = MessageAdmin.getConversationReadTimestamp("57gqmws2k", new Conversation(0, "admin", 0));
if(timestampResult != null && timestampResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("Get conversation read time success");
@@ -1030,6 +1134,14 @@ public class Main {
} else {
System.out.println("clear conversation failure");
}
//测试清空用户消息
IMResult<Void> clearUserMessagesResult = MessageAdmin.clearUserMessages("user1", conversation, 0, System.currentTimeMillis());
if (clearUserMessagesResult != null && clearUserMessagesResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("clear user messages success");
} else {
System.out.println("clear user messages failure");
}
}
List<String> multicastReceivers = Arrays.asList("user2", "user3", "user4");
@@ -1048,6 +1160,14 @@ public class Main {
System.out.println("failure");
}
//测试删除多播消息
IMResult<Void> deleteMultiCastResult = MessageAdmin.deleteMultiCastMessage("user1", resultMulticastMessage.result.getMessageUid(), multicastReceivers);
if (deleteMultiCastResult != null && deleteMultiCastResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("delete multicast message success");
} else {
System.out.println("delete multicast message failure");
}
}
//***********************************************
@@ -1509,6 +1629,80 @@ public class Main {
System.out.println("health check failure");
System.exit(-1);
}
//测试用户设置功能
IMResult<Void> setUserSettingResult = GeneralAdmin.setUserSetting("user1", 1, "test_key", "test_value");
if (setUserSettingResult != null && setUserSettingResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("set user setting success");
} else {
System.out.println("set user setting failure");
System.exit(-1);
}
IMResult<UserSettingPojo> getUserSettingResult = GeneralAdmin.getUserSetting("user1", 1, "test_key");
if (getUserSettingResult != null && getUserSettingResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS && "test_value".equals(getUserSettingResult.getResult().getValue())) {
System.out.println("get user setting success");
} else {
System.out.println("get user setting failure");
System.exit(-1);
}
if (commercialServer) {
//测试会话置顶功能
IMResult<Void> setTopResult = GeneralAdmin.setConversationTop("user1", ProtoConstants.ConversationType.ConversationType_Private, "user2", 0, true);
if (setTopResult != null && setTopResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("set conversation top success");
} else {
System.out.println("set conversation top failure");
System.exit(-1);
}
Thread.sleep(1000);
IMResult<Boolean> getTopResult = GeneralAdmin.getConversationTop("user1", ProtoConstants.ConversationType.ConversationType_Private, "user2", 0);
if (getTopResult != null && getTopResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS && getTopResult.getResult()) {
System.out.println("get conversation top success");
} else {
System.out.println("get conversation top failure");
System.exit(-1);
}
//取消置顶
setTopResult = GeneralAdmin.setConversationTop("user1", ProtoConstants.ConversationType.ConversationType_Private, "user2", 0, false);
if (setTopResult != null && setTopResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("cancel conversation top success");
} else {
System.out.println("cancel conversation top failure");
System.exit(-1);
}
//测试获取会话文件
IMResult<FilesPojo> getConversationFilesResult = GeneralAdmin.getConversationFiles(ProtoConstants.ConversationType.ConversationType_Private, "user2", 0, "user1", 0, true, 10);
if (getConversationFilesResult != null && getConversationFilesResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("get conversation files success");
} else {
System.out.println("get conversation files failure");
}
//测试获取用户文件
IMResult<FilesPojo> getUserFilesResult = GeneralAdmin.getUserFiles("user1", 0, true, 10);
if (getUserFilesResult != null && getUserFilesResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("get user files success");
} else {
System.out.println("get user files failure");
}
//测试获取单个文件信息
if (getUserFilesResult.getResult() != null && getUserFilesResult.getResult().files != null && !getUserFilesResult.getResult().files.isEmpty()) {
long messageId = getUserFilesResult.getResult().files.get(0).messageId;
IMResult<FilesPojo.FilePojo> getFileResult = GeneralAdmin.getFile(messageId);
if (getFileResult != null && getFileResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("get file success");
} else {
System.out.println("get file failure");
}
}
}
}
/**
@@ -1592,6 +1786,24 @@ public class Main {
System.exit(-1);
}
//测试设置聊天室全局禁言
IMResult<Void> setChatroomMuteResult = ChatroomAdmin.setChatroomMute(chatroomId, true);
if (setChatroomMuteResult != null && setChatroomMuteResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("set chatroom mute success");
} else {
System.out.println("set chatroom mute failure");
System.exit(-1);
}
//取消聊天室全局禁言
setChatroomMuteResult = ChatroomAdmin.setChatroomMute(chatroomId, false);
if (setChatroomMuteResult != null && setChatroomMuteResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("cancel chatroom mute success");
} else {
System.out.println("cancel chatroom mute failure");
System.exit(-1);
}
//下面仅专业版支持
if(commercialServer) {
//设置用户聊天室黑名单。0正常;1禁言;2禁止加入。
@@ -1787,6 +1999,7 @@ public class Main {
System.exit(-1);
}
//测试删除机器人回调地址
voidIMResult1 = robotService.deleteCallback();
if(voidIMResult1 != null && voidIMResult1.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("delete callback success");
@@ -1795,6 +2008,7 @@ public class Main {
System.exit(-1);
}
//验证回调地址已删除
callbackPojoIMResult = robotService.getCallback();
if(callbackPojoIMResult != null && callbackPojoIMResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS && StringUtil.isNullOrEmpty(callbackPojoIMResult.getResult().getUrl())) {
System.out.println("get callback success");
@@ -1803,13 +2017,17 @@ public class Main {
System.exit(-1);
}
//创建会话对象,设置目标用户和会话类型
Conversation conversation = new Conversation();
conversation.setTarget("user2");
conversation.setType(ProtoConstants.ConversationType.ConversationType_Private);
//创建消息payload,设置消息类型和内容
MessagePayload payload = new MessagePayload();
payload.setType(1);
payload.setSearchableContent("hello world");
//测试机器人发送消息
IMResult<SendMessageResult> resultRobotSendMessage = robotService.sendMessage(robotService.getRobotId(), conversation, payload);
if (resultRobotSendMessage != null && resultRobotSendMessage.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("robot send message success");
@@ -1818,6 +2036,14 @@ public class Main {
System.exit(-1);
}
//测试机器人回复消息
IMResult<SendMessageResult> replyMessageResult = robotService.replyMessage(resultRobotSendMessage.getResult().getMessageUid(), payload, false);
if (replyMessageResult != null && replyMessageResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("robot reply message success");
} else {
System.out.println("robot reply message failure");
}
if(commercialServer) {
Thread.sleep(1000);
IMResult<String> recallMessageResult = robotService.recallMessage(resultRobotSendMessage.result.getMessageUid());
@@ -1849,6 +2075,7 @@ public class Main {
}
//测试机器人通过用户ID获取用户信息
IMResult<InputOutputUserInfo> resultRobotGetUserInfo = robotService.getUserInfo("userId1");
if (resultRobotGetUserInfo != null && resultRobotGetUserInfo.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("robot get user info success");
@@ -1857,6 +2084,23 @@ public class Main {
System.exit(-1);
}
//测试机器人通过手机号获取用户信息
IMResult<InputOutputUserInfo> resultRobotGetUserInfoByMobile = robotService.getUserInfoByMobile("13900000000");
if (resultRobotGetUserInfoByMobile != null && resultRobotGetUserInfoByMobile.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("robot get user info by mobile success");
} else {
System.out.println("robot get user info by mobile failure");
}
//测试机器人通过用户名获取用户信息
IMResult<InputOutputUserInfo> resultRobotGetUserInfoByName = robotService.getUserInfoByName("user1");
if (resultRobotGetUserInfoByName != null && resultRobotGetUserInfoByName.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("robot get user info by name success");
} else {
System.out.println("robot get user info by name failure");
}
//创建群组信息,用于测试机器人群组管理功能
String groupId = "robot_group" + System.currentTimeMillis();
PojoGroupInfo groupInfo = new PojoGroupInfo();
groupInfo.setTarget_id(groupId);
@@ -1878,6 +2122,7 @@ public class Main {
member3.setMember_id("user3");
members.add(member3);
//测试机器人创建群组
IMResult<OutputCreateGroupResult> resultCreateGroup = robotService.createGroup(groupInfo, members, null, null, null);
if (resultCreateGroup != null && resultCreateGroup.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("create group success");
@@ -1954,6 +2199,15 @@ public class Main {
System.exit(-1);
}
//测试设置群成员extra
voidIMResult = robotService.setGroupMemberExtra(groupInfo.getTarget_id(), "user2", "robot member extra", null, null);
if (voidIMResult != null && voidIMResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("set group member extra success");
} else {
System.out.println("set group member extra failure");
System.exit(-1);
}
if(commercialServer) {
PojoGroupMember m4 = new PojoGroupMember();
m4.setMember_id("user4");
@@ -1987,6 +2241,23 @@ public class Main {
System.exit(-1);
}
//测试机器人应用获取用户信息。authCode应该是从客户端SDK里获取到的,这里不具备条件,跳过测试
// IMResult<OutputApplicationUserInfo> appGetUserInfoResult = robotService.applicationGetUserInfo("test_auth_code");
// if (appGetUserInfoResult != null && (appGetUserInfoResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS || appGetUserInfoResult.getErrorCode() == ErrorCode.ERROR_CODE_INVALID_DATA)) {
// System.out.println("robot application get user info success");
// } else {
// System.out.println("robot application get user info failure");
// }
//测试机器人发送会议请求。不具备测试条件,注释掉。
// IMResult<String> sendConferenceRequestResult = robotService.sendConferenceRequest(robotId, "client1", "test_request", 1, "room1", "test_data", false);
// if (sendConferenceRequestResult != null && (sendConferenceRequestResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS || sendConferenceRequestResult.getErrorCode() == ErrorCode.ERROR_CODE_INVALID_DATA)) {
// System.out.println("robot send conference request success");
// } else {
// System.out.println("robot send conference request failure");
// }
OutputApplicationConfigData config = robotService.getApplicationSignature();
System.out.println(config);
}
@@ -2028,6 +2299,7 @@ public class Main {
System.exit(-1);
}
}
//测试机器人转让群组给user2
voidIMResult = robotService.transferGroup(groupInfo.getTarget_id(), "user2", null, null);
if (voidIMResult != null && voidIMResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("transfer success");
@@ -2036,6 +2308,7 @@ public class Main {
System.exit(-1);
}
//验证群组转让成功,检查新群主是否为user2
resultGetGroupInfo = robotService.getGroupInfo(groupInfo.getTarget_id());
if (resultGetGroupInfo != null && resultGetGroupInfo.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
if ("user2".equals(resultGetGroupInfo.getResult().getOwner())) {
@@ -2049,6 +2322,7 @@ public class Main {
System.exit(-1);
}
//测试机器人退出群组
voidIMResult = robotService.quitGroup(groupInfo.getTarget_id(), null, null);
if (voidIMResult != null && voidIMResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("quit group success");
@@ -2138,9 +2412,45 @@ public class Main {
System.out.println("get user moments profile failure:" + profileResult.getErrorCode().code);
System.exit(-1);
}
//测试更新朋友圈设置
IMResult<Void> updateBgResult = robotService.updateMomentsBackgroundUrl("https://example.com/bg.jpg");
if (updateBgResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("update moments background success");
} else {
System.out.println("update moments background failure:" + updateBgResult.getErrorCode().code);
}
IMResult<Void> updateVisibleCountResult = robotService.updateMomentsStrangerVisibleCount(10);
if (updateVisibleCountResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("update moments visible count success");
} else {
System.out.println("update moments visible count failure:" + updateVisibleCountResult.getErrorCode().code);
}
IMResult<Void> updateVisibleScopeResult = robotService.updateMomentsVisibleScope(0);
if (updateVisibleScopeResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("update moments visible scope success");
} else {
System.out.println("update moments visible scope failure:" + updateVisibleScopeResult.getErrorCode().code);
}
IMResult<Void> updateBlackListResult = robotService.updateMomentsBlackList(Arrays.asList("user1"), null);
if (updateBlackListResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("update moments blacklist success");
} else {
System.out.println("update moments blacklist failure:" + updateBlackListResult.getErrorCode().code);
}
IMResult<Void> updateBlockListResult = robotService.updateMomentsBlockList(Arrays.asList("user2"), null);
if (updateBlockListResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("update moments blocklist success");
} else {
System.out.println("update moments blocklist failure:" + updateBlockListResult.getErrorCode().code);
}
}
//使用完需要释放
//释放机器人服务资源
robotService.close();
}
@@ -2238,6 +2548,8 @@ public class Main {
//3. 测试channel api功能
//测试用户关注频道
IMResult<Void> resultVoid = channelServiceApi.subscribe("userId2");
if (resultVoid != null && resultVoid.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("subscribe success");
@@ -2246,6 +2558,7 @@ public class Main {
System.exit(-1);
}
//测试另一个用户关注频道
resultVoid = channelServiceApi.subscribe("userId3");
if (resultVoid != null && resultVoid.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("subscribe done");
@@ -2254,6 +2567,7 @@ public class Main {
System.exit(-1);
}
//使用Admin API让userId4关注频道
resultVoid = ChannelAdmin.subscribeChannel(channelId, "userId4");
if (resultVoid != null && resultVoid.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("subscribe done");
@@ -2262,6 +2576,7 @@ public class Main {
System.exit(-1);
}
//获取频道订阅者列表
IMResult<OutputStringList> resultStringList = channelServiceApi.getSubscriberList();
if (resultStringList != null && resultStringList.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS && resultStringList.getResult().getList().contains("userId2") && resultStringList.getResult().getList().contains("userId3") && resultStringList.getResult().getList().contains("userId4")) {
System.out.println("get subscriber done");
@@ -2270,6 +2585,7 @@ public class Main {
System.exit(-1);
}
//检查用户是否订阅了频道
IMResult<Boolean> booleanIMResult = channelServiceApi.isSubscriber("userId2");
if(booleanIMResult != null && booleanIMResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS && booleanIMResult.getResult()) {
System.out.println("is subscriber success");
@@ -2278,6 +2594,7 @@ public class Main {
System.exit(-1);
}
//测试用户取消关注频道
resultVoid = channelServiceApi.unsubscribe("userId2");
if (resultVoid != null && resultVoid.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("unsubscriber done");
@@ -2286,6 +2603,7 @@ public class Main {
System.exit(-1);
}
//验证userId2已不在订阅者列表中
resultStringList = channelServiceApi.getSubscriberList();
if (resultStringList != null && resultStringList.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS && resultStringList.getResult().getList().contains("userId3") && !resultStringList.getResult().getList().contains("userId2")) {
System.out.println("get subscriber done");
@@ -2294,6 +2612,7 @@ public class Main {
System.exit(-1);
}
//测试频道获取用户信息
IMResult<InputOutputUserInfo> resultGetUserInfo1 = channelServiceApi.getUserInfo("userId3");
if (resultGetUserInfo1 != null && resultGetUserInfo1.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("get user info success");
@@ -2302,6 +2621,7 @@ public class Main {
System.exit(-1);
}
//创建消息payload
MessagePayload payload = new MessagePayload();
payload.setType(1);
payload.setSearchableContent("hello world");
@@ -2314,6 +2634,15 @@ public class Main {
System.exit(-1);
}
//测试重新发布消息
IMResult<Void> republishResult = channelServiceApi.republishMessage(resultSendMessage.getResult().getMessageUid(), Arrays.asList("userId2", "userId3"));
if (republishResult != null && republishResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("republish message success");
} else {
System.out.println("republish message failure");
System.exit(-1);
}
ArticleContent articleContent = new ArticleContent("article1", "https://media.wfcoss.cn/channel-assets/20220816/2dd76540daa9444dae44e942aa1c2bbc.png", "这是一个测试文章", "测试一下文章的功能", "https://mp.weixin.qq.com/s/W6tanLbALd3qqZM8r3MTgA", true);
articleContent.addSubArticle("article2", "https://media.wfcoss.cn/channel-assets/20220816/2dd76540daa9444dae44e942aa1c2bbc.png", "这是第二个测试文章", "测试一下文章的功能", "https://mp.weixin.qq.com/s/W6tanLbALd3qqZM8r3MTgA", false);
articleContent.addSubArticle("article3", "https://media.wfcoss.cn/channel-assets/20220816/2dd76540daa9444dae44e942aa1c2bbc.png", "这是第三个测试文章", "测试一下文章的功能", "https://mp.weixin.qq.com/s/W6tanLbALd3qqZM8r3MTgA", false);
@@ -2327,6 +2656,7 @@ public class Main {
System.exit(-1);
}
//发送定向消息给指定用户
payload.setSearchableContent("hello to user2");
resultSendMessage = channelServiceApi.sendMessage(0, Arrays.asList("userId2"),payload);
@@ -2337,6 +2667,7 @@ public class Main {
System.exit(-1);
}
//测试修改频道描述信息
IMResult<Void> voidIMResult = channelServiceApi.modifyChannelInfo(ProtoConstants.ModifyChannelInfoType.Modify_Channel_Desc, "this is a test channel, update at:" + new Date().toString());
if (voidIMResult != null && voidIMResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("modify channel profile success");
@@ -2387,6 +2718,22 @@ public class Main {
System.out.println("get channel info failure");
System.exit(-1);
}
//测试修改频道菜单
List<PojoChannelMenu> testMenus = new ArrayList<>();
PojoChannelMenu testMenu = new PojoChannelMenu();
testMenu.menuId = UUID.randomUUID().toString();
testMenu.type = "view";
testMenu.name = "测试菜单";
testMenu.key = "test_key";
testMenu.url = "http://www.test.com";
testMenus.add(testMenu);
IMResult<Void> modifyMenuResult = channelServiceApi.modifyChannelMenu(testMenus);
if (modifyMenuResult != null && modifyMenuResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("modify channel menu success");
} else {
System.out.println("modify channel menu failure");
}
OutputApplicationConfigData config = channelServiceApi.getApplicationSignature();
System.out.println(config);
@@ -2489,9 +2836,12 @@ public class Main {
* @throws Exception 当测试过程中发生错误时抛出异常
*/
static void testDevice() throws Exception {
//创建设备信息,设置设备ID和所有者列表
InputCreateDevice createDevice = new InputCreateDevice();
createDevice.setDeviceId("deviceId1");
createDevice.setOwners(Arrays.asList("opoGoG__", "userId1"));
//测试创建设备(如果不存在则创建,存在则更新)
IMResult<OutputCreateDevice> resultCreateDevice = UserAdmin.createOrUpdateDevice(createDevice);
if (resultCreateDevice != null && resultCreateDevice.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("Create device " + resultCreateDevice.getResult().getDeviceId() + " success");
@@ -2500,6 +2850,7 @@ public class Main {
System.exit(-1);
}
//测试获取设备信息
IMResult<OutputDevice> getDevice = UserAdmin.getDevice("deviceId1");
if (getDevice != null && getDevice.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS && getDevice.getResult().getDeviceId().equals("deviceId1") && getDevice.getResult().getOwners().contains("opoGoG__")) {
System.out.println("Get device " + resultCreateDevice.getResult().getDeviceId() + " success");
@@ -2508,6 +2859,7 @@ public class Main {
System.exit(-1);
}
//测试获取用户绑定的所有设备
IMResult<OutputDeviceList> getUserDevices = UserAdmin.getUserDevices("userId1");
if (getUserDevices != null && getUserDevices.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
boolean success = false;
@@ -2529,10 +2881,25 @@ public class Main {
}
}
/*
会议相关接口,仅音视频高级版服务支持
/**
* 会议功能测试(仅音视频高级版服务支持)
* <p>
* 测试以下会议功能:
* <ul>
* <li>获取会议列表</li>
* <li>销毁会议</li>
* <li>创建普通会议</li>
* <li>创建高级会议</li>
* <li>检查会议是否存在</li>
* <li>开启会议录制</li>
* <li>获取参会者列表</li>
* <li>RTP转发相关操作</li>
* </ul>
* </p>
* @throws Exception 当测试过程中发生错误时抛出异常
*/
public static void testConference() throws Exception {
//获取当前会议列表
IMResult<PojoConferenceInfoList> listResult = ConferenceAdmin.listConferences(100, 0);
if(listResult == null || listResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("get conference list failure");
@@ -2541,6 +2908,7 @@ public class Main {
System.out.println("conference list " + listResult.getResult().conferenceInfoList);
}
//清理现有会议,避免影响测试
for (PojoConferenceInfo conferenceInfo:listResult.getResult().conferenceInfoList) {
IMResult<Void> destroyResult = ConferenceAdmin.destroy(conferenceInfo.roomId, conferenceInfo.advance);
if(destroyResult == null || destroyResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
@@ -2551,6 +2919,7 @@ public class Main {
}
}
//再次获取会议列表,确认已清空
listResult = ConferenceAdmin.listConferences(100, 0);
if(listResult == null || listResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("get conference list failure");
@@ -2559,7 +2928,11 @@ public class Main {
System.out.println("conference list " + listResult.getResult().conferenceInfoList);
}
IMResult<Void> voidIMResult = ConferenceAdmin.createRoom("helloroomid", "hello room description", "123456", 9, false, 0, false, true);
//生成两个会议房间ID
String roomId1 = UUID.randomUUID().toString();
String roomId2 = UUID.randomUUID().toString();
//创建普通会议房间(非高级版,最多9人)
IMResult<Void> voidIMResult = ConferenceAdmin.createRoom(roomId1, "hello room description", "123456", 9, false, 0, false, true);
if(voidIMResult == null || voidIMResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("create conference failure");
System.exit(-1);
@@ -2567,7 +2940,8 @@ public class Main {
System.out.println("create conference");
}
voidIMResult = ConferenceAdmin.createRoom("helloroomid2", "hello room description advanced", "123456", 20, true, 0, false, true);
//创建高级会议房间(支持更多功能,最多20人)
voidIMResult = ConferenceAdmin.createRoom(roomId2, "hello room description advanced", "123456", 20, true, 0, false, true);
if(voidIMResult == null || voidIMResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("create conference failure");
System.exit(-1);
@@ -2575,7 +2949,8 @@ public class Main {
System.out.println("create conference");
}
IMResult<Boolean> booleanIMResult = ConferenceAdmin.existsConferences("helloroomid2");
//检查会议房间是否存在
IMResult<Boolean> booleanIMResult = ConferenceAdmin.existsConferences(roomId1);
if(booleanIMResult == null || booleanIMResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("exist conference failure");
System.exit(-1);
@@ -2583,7 +2958,8 @@ public class Main {
System.out.println("exit conference success");
}
voidIMResult = ConferenceAdmin.enableRecording("helloroomid2", true, true);
//开启会议录制功能(视频和音频都录制)
voidIMResult = ConferenceAdmin.enableRecording(roomId2, true, true);
if(voidIMResult == null || voidIMResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("recording conference failure");
System.exit(-1);
@@ -2599,6 +2975,7 @@ public class Main {
System.out.println("conference list " + listResult.getResult().conferenceInfoList);
}
//获取每个会议的参会者列表
for (PojoConferenceInfo conferenceInfo:listResult.getResult().conferenceInfoList) {
IMResult<PojoConferenceParticipantList> listParticipantsResult = ConferenceAdmin.listParticipants(conferenceInfo.roomId, conferenceInfo.advance);
if(listParticipantsResult == null || listParticipantsResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
@@ -2609,6 +2986,7 @@ public class Main {
}
}
//获取RTP转发器列表,并停止所有转发
IMResult<PojoConferenceRtpForwarders> listForwarderResult = ConferenceAdmin.listRtpForwarders("6366963312");
if(listForwarderResult == null || listForwarderResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("list rtp forward failure");
@@ -2628,6 +3006,7 @@ public class Main {
}));
}
//测试RTP转发功能,将媒体流转发到指定地址
IMResult<Void> rtpForwardResult = ConferenceAdmin.rtpForward("6366963312", "cygqmws2k", "192.168.1.81", 10000, 111, 0, 10005, 98, 0);
if(rtpForwardResult == null || rtpForwardResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("rtp forward failure");
@@ -2635,4 +3014,179 @@ public class Main {
System.out.println("rtp forward success");
}
}
//***********************************************
//**** Mesh相关API,用于分布式IM
//***********************************************
/**
* Mesh(分布式IM)API测试
* <p>
* 测试以下分布式IM功能:
* <ul>
* <li>搜索用户 - 跨域搜索用户</li>
* <li>批量获取用户信息 - 获取多个用户的详细信息</li>
* <li>发送好友请求 - 向其他域用户发送好友请求</li>
* <li>处理好友请求 - 接受或拒绝好友请求</li>
* <li>创建域 - 创建新的Mesh域</li>
* <li>获取域信息 - 获取指定域的详细信息</li>
* <li>获取所有域 - 获取Mesh网络中的所有域列表</li>
* <li>Ping域 - 测试域的连通性</li>
* <li>删除域 - 从Mesh网络中移除域</li>
* <li>同步群组 - 跨域同步群组信息</li>
* <li>发送消息 - 向其他域用户发送消息</li>
* <li>发布消息 - 向多个域用户广播消息</li>
* <li>添加加入群组请求 - 跨域申请加入群组</li>
* <li>会议用户请求 - 跨域会议相关请求</li>
* <li>会议用户事件 - 跨域会议事件处理</li>
* </ul>
* </p>
* @throws Exception 当测试过程中发生错误时抛出异常
*/
static void testMesh() throws Exception {
//测试搜索用户
IMResult<PojoSearchUserRes> searchUserResult = MeshAdmin.searchUser("test", 0, 0, 1);
if (searchUserResult != null && searchUserResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("mesh search user success");
} else {
System.out.println("mesh search user failure");
}
//测试批量获取用户信息
IMResult<OutputUserInfoList> batchUserInfosResult = MeshAdmin.getBatchUserInfos(Arrays.asList("user1", "user2"));
if (batchUserInfosResult != null && batchUserInfosResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("mesh batch get user info success");
} else {
System.out.println("mesh batch get user info failure");
}
//测试发送好友请求
IMResult<Void> sendFriendRequestResult = MeshAdmin.sendFriendRequest("user1", "user2", "hello");
if (sendFriendRequestResult != null && (sendFriendRequestResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS || sendFriendRequestResult.getErrorCode() == ErrorCode.ERROR_CODE_ALREADY_FRIENDS)) {
System.out.println("mesh send friend request success");
} else {
System.out.println("mesh send friend request failure");
}
//测试处理好友请求
IMResult<Void> handleFriendRequestResult = MeshAdmin.handleFriendRequest("user2", "user1", 1);
if (handleFriendRequestResult != null && handleFriendRequestResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("mesh handle friend request success");
} else {
System.out.println("mesh handle friend request failure");
}
//测试创建域
String domainId = "test_domain_" + System.currentTimeMillis();
InputOutputDomainInfo domainInfo = new InputOutputDomainInfo();
domainInfo.setDomainId(domainId);
domainInfo.setName("Test Domain");
IMResult<Void> createDomainResult = MeshAdmin.createDomain(domainInfo);
if (createDomainResult != null && createDomainResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("mesh create domain success");
} else {
System.out.println("mesh create domain failure");
}
//测试获取域
IMResult<InputOutputDomainInfo> getDomainResult = MeshAdmin.getDomain(domainId);
if (getDomainResult != null && getDomainResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("mesh get domain success");
} else {
System.out.println("mesh get domain failure");
}
//测试获取所有域
IMResult<InputOutputDomainInfoList> getAllDomainResult = MeshAdmin.getAllDomain();
if (getAllDomainResult != null && getAllDomainResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("mesh get all domain success");
} else {
System.out.println("mesh get all domain failure");
}
//测试ping域
IMResult<PojoDomainPingResponse> pingDomainResult = MeshAdmin.pingDomain(domainId);
if (pingDomainResult != null && pingDomainResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("mesh ping domain success");
} else {
System.out.println("mesh ping domain failure");
}
//测试删除域
IMResult<Void> deleteDomainResult = MeshAdmin.deleteDomain(domainId);
if (deleteDomainResult != null && deleteDomainResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("mesh delete domain success");
} else {
System.out.println("mesh delete domain failure");
}
//测试同步群组
PojoGroupInfo meshGroupInfo = new PojoGroupInfo();
meshGroupInfo.setTarget_id("mesh_group_" + System.currentTimeMillis());
meshGroupInfo.setName("Mesh Test Group");
meshGroupInfo.setOwner("user1");
meshGroupInfo.setType(2);
List<PojoGroupMember> meshMembers = new ArrayList<>();
PojoGroupMember meshMember = new PojoGroupMember();
meshMember.setMember_id("user1");
meshMembers.add(meshMember);
IMResult<Void> syncGroupResult = MeshAdmin.syncGroup(meshGroupInfo, meshMembers);
if (syncGroupResult != null && syncGroupResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("mesh sync group success");
} else {
System.out.println("mesh sync group failure");
}
//测试发送消息
Conversation meshConversation = new Conversation();
meshConversation.setTarget("user2");
meshConversation.setType(ProtoConstants.ConversationType.ConversationType_Private);
MessagePayload meshPayload = new MessagePayload();
meshPayload.setType(1);
meshPayload.setSearchableContent("mesh test message");
IMResult<SendMessageResult> meshSendMessageResult = MeshAdmin.sendMessage("user1", meshConversation, meshPayload, null);
if (meshSendMessageResult != null && meshSendMessageResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("mesh send message success");
} else {
System.out.println("mesh send message failure");
}
//测试发布消息
if (meshSendMessageResult != null && meshSendMessageResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
SendMessageData publishMessageData = new SendMessageData();
publishMessageData.setSender("user1");
publishMessageData.setConv(meshConversation);
publishMessageData.setPayload(meshPayload);
IMResult<SendMessageResult> publishMessageResult = MeshAdmin.publishMessage(publishMessageData, Arrays.asList("user2"), meshSendMessageResult.getResult().getMessageUid());
if (publishMessageResult != null && publishMessageResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("mesh publish message success");
} else {
System.out.println("mesh publish message failure");
}
}
//测试添加加入群组请求
IMResult<Void> addJoinGroupRequestResult = MeshAdmin.addJoinGroupRequest("user2", meshGroupInfo.getTarget_id(), Arrays.asList("user3"), "please add me", null);
if (addJoinGroupRequestResult != null && addJoinGroupRequestResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("mesh add join group request success");
} else {
System.out.println("mesh add join group request failure");
}
//测试会议用户请求
IMResult<PojoUserConferenceResponse> userConferenceRequestResult = MeshAdmin.userConferenceRequest("client1", "user1", "test_request", 1, "room1", "test_data", false);
if (userConferenceRequestResult != null && userConferenceRequestResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("mesh user conference request success");
} else {
System.out.println("mesh user conference request failure");
}
//测试会议用户事件
IMResult<Void> userConferenceEventResult = MeshAdmin.userConferenceEvent("test_event_data", "user1", "client1", false);
if (userConferenceEventResult != null && userConferenceEventResult.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("mesh user conference event success");
} else {
System.out.println("mesh user conference event failure");
}
}
}
@@ -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;
@@ -476,6 +493,333 @@ public class RobotService implements Closeable {
return robotHttpUtils.httpJsonPost(path, requestPojo, Void.class);
}
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 块中处理
}
@Override
public void close() throws IOException {
robotHttpUtils.close();
@@ -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();