@asteriskzuo/react-native-easemob
Version:
easemob chat sdk of react-native.
626 lines (505 loc) • 20.7 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ChatClient = void 0;
var _reactNative = require("react-native");
var _ChatEvents = require("./ChatEvents");
var _ChatManager = require("./ChatManager");
var _ChatDeviceInfo = require("./common/ChatDeviceInfo");
var _Consts = require("./_internal/Consts");
var _Native = require("./_internal/Native");
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
const LINKING_ERROR = `The package 'react-native-easemob' doesn't seem to be linked. Make sure: \n\n` + _reactNative.Platform.select({
ios: "- You have run 'pod install'\n",
default: ''
}) + '- You rebuilt the app after installing the package\n' + '- You are not using Expo managed workflow\n';
const ExtSdkApiRN = _reactNative.NativeModules.ExtSdkApiRN ? _reactNative.NativeModules.ExtSdkApiRN : new Proxy({}, {
get() {
throw new Error(LINKING_ERROR);
}
});
const eventEmitter = new _reactNative.NativeEventEmitter(ExtSdkApiRN);
console.log('eventEmitter: ', eventEmitter);
class ChatClient extends _Native.Native {
// 1.remove 2.subscription(suggested)
static getInstance() {
if (ChatClient._instance == null || ChatClient._instance === undefined) {
ChatClient._instance = new ChatClient();
}
return ChatClient._instance;
}
setEventEmitter() {
console.log(`${ChatClient.TAG}: setEventEmitter: `);
this.setNativeListener(this.getEventEmitter());
this._chatManager.setNativeListener(this.getEventEmitter());
console.log('eventEmitter has finished.');
}
getEventEmitter() {
return eventEmitter;
} // private _eventEmitter: NativeEventEmitter;
constructor() {
super();
_defineProperty(this, "_connectionSubscriptions", void 0);
_defineProperty(this, "_chatManager", void 0);
_defineProperty(this, "_connectionListeners", void 0);
_defineProperty(this, "_multiDeviceListeners", void 0);
_defineProperty(this, "_customListeners", void 0);
_defineProperty(this, "_options", void 0);
_defineProperty(this, "_sdkVersion", '1.0.0');
_defineProperty(this, "_isInit", false);
_defineProperty(this, "_currentUsername", '');
this._chatManager = new _ChatManager.ChatManager(); // todo: no implement
// this._contactManager = new ChatContactManager();
// this._chatRoomManager = new ChatChatRoomManager();
// this._groupManager = new ChatGroupManager();
// this._pushManager = new ChatPushManager();
// this._userInfoManager = new ChatUserInfoManager();
// this._conversationManager = new ChatConversationManager();
this._connectionListeners = new Set();
this._connectionSubscriptions = new Map();
this._multiDeviceListeners = new Set();
this._customListeners = new Set();
this.setEventEmitter();
}
setConnectNativeListener(event) {
console.log(`${ChatClient.TAG}: setConnectNativeListener: `);
this._connectionSubscriptions.forEach((value, key, map) => {
console.log(`${ChatClient.TAG}: setConnectNativeListener: ${key}, ${value}, ${map}`);
value.remove();
});
this._connectionSubscriptions.clear(); // let s: EmitterSubscription[] | undefined = eventEmitter?.listeners(
// MethodTypeonConnected
// );
// console.log(`${s?.length}`);
// let s: EmitterSubscription = event.addListener(
// MethodTypeonConnected,
// (params: any[]): any => {
// console.log('etst', params);
// s.remove();
// }
// );
this._connectionSubscriptions.set(_Consts.MethodTypeonConnected, event.addListener(_Consts.MethodTypeonConnected, this.onConnected.bind(this)));
this._connectionSubscriptions.set(_Consts.MethodTypeonDisconnected, event.addListener(_Consts.MethodTypeonDisconnected, this.onDisconnected.bind(this)));
this._connectionSubscriptions.set(_Consts.MethodTypeonTokenDidExpire, event.addListener(_Consts.MethodTypeonTokenDidExpire, this.onTokenDidExpire.bind(this)));
this._connectionSubscriptions.set(_Consts.MethodTypeonTokenWillExpire, event.addListener(_Consts.MethodTypeonTokenWillExpire, this.onTokenWillExpire.bind(this)));
this._connectionSubscriptions.set(_Consts.MethodTypeonMultiDeviceEvent, event.addListener(_Consts.MethodTypeonMultiDeviceEvent, this.onMultiDeviceEvent.bind(this)));
this._connectionSubscriptions.set(_Consts.MethodTypeonSendDataToFlutter, event.addListener(_Consts.MethodTypeonSendDataToFlutter, this.onCustomEvent.bind(this)));
console.log(`${ChatClient.TAG}: setConnectNativeListener: `, event);
}
setNativeListener(event) {
console.log(`${ChatClient.TAG}: setNativeListener: ${ChatClient.eventType}`);
if (ChatClient.eventType === 1) {
event.removeAllListeners(_Consts.MethodTypeonConnected);
event.addListener(_Consts.MethodTypeonConnected, this.onConnected.bind(this));
event.removeAllListeners(_Consts.MethodTypeonDisconnected);
event.addListener(_Consts.MethodTypeonDisconnected, this.onDisconnected.bind(this));
event.removeAllListeners(_Consts.MethodTypeonTokenDidExpire);
event.addListener(_Consts.MethodTypeonTokenDidExpire, this.onTokenDidExpire.bind(this));
event.removeAllListeners(_Consts.MethodTypeonTokenWillExpire);
event.addListener(_Consts.MethodTypeonTokenWillExpire, this.onTokenWillExpire.bind(this));
event.removeAllListeners(_Consts.MethodTypeonMultiDeviceEvent);
event.addListener(_Consts.MethodTypeonMultiDeviceEvent, this.onMultiDeviceEvent.bind(this));
event.removeAllListeners(_Consts.MethodTypeonSendDataToFlutter);
event.addListener(_Consts.MethodTypeonSendDataToFlutter, this.onCustomEvent.bind(this));
} else if (ChatClient.eventType === 2) {
this.setConnectNativeListener(event);
} else {
throw new Error('This type is not supported.');
}
}
onConnected() {
console.log(`${ChatClient.TAG}: onConnected: `);
this._connectionListeners.forEach(element => {
element.onConnected();
});
}
onDisconnected(params) {
console.log(`${ChatClient.TAG}: onDisconnected: ${params}`);
this._connectionListeners.forEach(element => {
let ec = params === null || params === void 0 ? void 0 : params.errorCode;
element.onDisconnected(ec);
});
}
onTokenWillExpire(params) {
console.log(`${ChatClient.TAG}: onTokenWillExpire: ${params}`);
this._connectionListeners.forEach(element => {
element.onTokenWillExpire();
});
}
onTokenDidExpire(params) {
console.log(`${ChatClient.TAG}: onTokenDidExpire: ${params}`);
this._connectionListeners.forEach(element => {
element.onTokenDidExpire();
});
}
onMultiDeviceEvent(params) {
console.log(`${ChatClient.TAG}: onMultiDeviceEvent: ${params}`);
this._multiDeviceListeners.forEach(element => {
let event = params === null || params === void 0 ? void 0 : params.event;
if (event > 10) {
element.onGroupEvent((0, _ChatEvents.ChatContactGroupEventFromNumber)(event), params === null || params === void 0 ? void 0 : params.target, params === null || params === void 0 ? void 0 : params.userNames);
} else {
element.onContactEvent((0, _ChatEvents.ChatContactGroupEventFromNumber)(event), params === null || params === void 0 ? void 0 : params.target, params === null || params === void 0 ? void 0 : params.userNames);
}
});
}
onCustomEvent(params) {
console.log(`${ChatClient.TAG}: onCustomEvent: ${params}`);
this._customListeners.forEach(element => {
element.onDataReceived(params);
});
}
reset() {
this._currentUsername = '';
}
/**
* Get SDK Configurations. Make sure to set the param, see {@link EMOptions}.
*
* @returns The configurations.
*/
get options() {
return this._options;
}
/**
* Get SDK version.
*/
get sdkVersion() {
return this._sdkVersion;
}
/**
* Get current user name.
*
* The value is valid after successful login.
*/
get currentUserName() {
return this._currentUsername;
}
/**
* Get React-native SDK version.
*/
get rnSdkVersion() {
return this._sdkVersion;
}
/**
* Make sure to initialize the SDK in the main thread. Make sure to set the param, see {@link ChatOptions}.
*
* **note**
*
* **This method must be called before any method can be called.**
*
* @param options The configurations.
*
* @throws Error, see {@link ChatError}
*/
async init(options) {
console.log(`${ChatClient.TAG}: init: ${options}`);
this._options = options;
await _Native.Native._callMethod(_Consts.MethodTypeinit, {
options
});
this._isInit = true;
}
/**
* Check whether you have successfully connected to the server.
*
* @returns
* - `true`: The server has been connected.
* - `false`: The server is not connected.
*
* @throws Error, see {@link ChatError}
*/
async isConnected() {
console.log(`${ChatClient.TAG}: isConnected: `);
let result = await _Native.Native._callMethod(_Consts.MethodTypeisConnected);
ChatClient.hasErrorFromResult(result);
let _connected = result === null || result === void 0 ? void 0 : result[_Consts.MethodTypeisConnected];
return _connected;
}
/**
* Get current user name from native. Get cache see {@link currentUserName}
* @returns The user name.
*
* @throws Error, see {@link ChatError}
*/
async getCurrentUsername() {
console.log(`${ChatClient.TAG}: getCurrentUsername: `);
let result = await _Native.Native._callMethod(_Consts.MethodTypegetCurrentUser);
ChatClient.hasErrorFromResult(result);
let userName = result === null || result === void 0 ? void 0 : result[_Consts.MethodTypegetCurrentUser];
if (userName && userName.length !== 0) {
if (userName !== this._currentUsername) {
this._currentUsername = userName;
}
}
return this._currentUsername;
}
/**
* Get login state.
*
* @returns
* - `true`: In automatic login mode, the value is true before successful login and false otherwise.
* - `false`: In non-automatic login mode, the value is false.
*
* @throws Error, see {@link ChatError}
*/
async isLoginBefore() {
console.log(`${ChatClient.TAG}: isLoginBefore: `);
let result = await _Native.Native._callMethod(_Consts.MethodTypeisLoggedInBefore);
ChatClient.hasErrorFromResult(result);
let _isLoginBefore = result === null || result === void 0 ? void 0 : result[_Consts.MethodTypeisLoggedInBefore];
return _isLoginBefore;
}
/**
* Get login access token.
*
* @returns The token value.
*
* @throws Error, see {@link ChatError}
*/
async getAccessToken() {
console.log(`${ChatClient.TAG}: isLoginBefore: `);
let result = await _Native.Native._callMethod(_Consts.MethodTypegetToken);
ChatClient.hasErrorFromResult(result);
let _token = result === null || result === void 0 ? void 0 : result[_Consts.MethodTypegetToken];
return _token;
}
/**
* Register a new user with your chat network.
*
* @param username The username. The maximum length is 64 characters. Ensure that you set this parameter. Supported characters include the 26 English letters (a-z), the ten numbers (0-9), the underscore (_), the hyphen (-), and the English period (.). This parameter is case insensitive, and upper-case letters are automatically changed to low-case ones. If you want to set this parameter as a regular expression, set it as ^[a-zA-Z0-9_-]+$.
* @param password The password. The maximum length is 64 characters. Ensure that you set this parameter.
*
* @throws Error, see {@link ChatError}
*/
async createAccount(username, password) {
console.log(`${ChatClient.TAG}: createAccount: ${username}, ${password}`);
let result = await _Native.Native._callMethod(_Consts.MethodTypecreateAccount, {
[_Consts.MethodTypecreateAccount]: {
username: username,
password: password
}
});
ChatClient.hasErrorFromResult(result);
}
/**
* An app user logs in to the chat server with a password or token.
*
* @param userName The username, see {@link createAccount}.
* @param pwdOrToken The password or token, see {@link createAccount} or {@link getAccessToken}
* @param isPassword The password or token flag. true is the password, otherwise it is the token.
*
* @throws Error, see {@link ChatError}
*/
async login(userName, pwdOrToken) {
var _result, _result2, _result3, _result4;
let isPassword = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
console.log(`${ChatClient.TAG}: login: ${userName}, ${pwdOrToken}, ${isPassword}`);
let result = await _Native.Native._callMethod(_Consts.MethodTypelogin, {
[_Consts.MethodTypelogin]: {
username: userName,
pwdOrToken: pwdOrToken,
isPassword: isPassword
}
});
ChatClient.hasErrorFromResult(result);
result = (_result = result) === null || _result === void 0 ? void 0 : _result[_Consts.MethodTypelogin];
this._currentUsername = (_result2 = result) === null || _result2 === void 0 ? void 0 : _result2.username;
console.log(`${ChatClient.TAG}: login: ${(_result3 = result) === null || _result3 === void 0 ? void 0 : _result3.username}, ${(_result4 = result) === null || _result4 === void 0 ? void 0 : _result4.token}`);
}
/**
* An app user logs in to the chat server with a agora token.
*
* @param userName The username, see {@link createAccount}.
* @param agoraToken The token from agora api.
*
* @throws Error, see {@link ChatError}
*/
async loginWithAgoraToken(userName, agoraToken) {
console.log(`${ChatClient.TAG}: loginWithAgoraToken: ${userName}, ${agoraToken}`);
let result = await _Native.Native._callMethod(_Consts.MethodTypeloginWithAgoraToken, {
[_Consts.MethodTypeloginWithAgoraToken]: {
username: userName,
agoraToken: agoraToken
}
});
ChatClient.hasErrorFromResult(result);
this._currentUsername = result === null || result === void 0 ? void 0 : result.username;
}
/**
* Renew token.
*
* When a user is in the Agora token login state and receives a callback
* notification of the token is to be expired in the {@link ChatConnectionListener}
* implementation class, this API can be called to update the token to
* avoid unknown problems caused by the token invalidation.
*
* @param agoraToken The new token.
*
* @throws Error, see {@link ChatError}
*/
async renewAgoraToken(agoraToken) {
console.log(`${ChatClient.TAG}: renewAgoraToken: ${agoraToken}`);
let result = await _Native.Native._callMethod(_Consts.MethodTyperefreshAgoraToken, {
[_Consts.MethodTyperefreshAgoraToken]: {
agoraToken: agoraToken
}
});
ChatClient.hasErrorFromResult(result);
}
/**
* An app user logs out and returns the result.
*
* @param unbindDeviceToken Whether to unbind the token.
* - `true`: means to unbind the device token when logout.
* - `false`: means to not unbind the device token when logout.
* @throws Error, see {@link ChatError}
*/
async logout() {
let unbindDeviceToken = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
console.log(`${ChatClient.TAG}: logout: ${unbindDeviceToken}`);
let result = await _Native.Native._callMethod(_Consts.MethodTypelogout, {
[_Consts.MethodTypelogout]: {
unbindToken: unbindDeviceToken
}
});
ChatClient.hasErrorFromResult(result);
this.reset();
}
/**
* Update the App Key, which is the unique identifier used to access Agora Chat.
*
* You retrieve the new App Key from Agora Console.
*
* As this key controls all access to Agora Chat for your app, you can only update the key when the current user is logged out.
*
* Also, you can set App Key by the following method when logged out {@link ChatOptions#appKey}.
*
* @param newAppKey The App Key, make sure to set the param.
*
* @throws Error, see {@link ChatError}
*/
async changeAppKey(newAppKey) {
console.log(`${ChatClient.TAG}: changeAppKey: ${newAppKey}`);
let r = await _Native.Native._callMethod(_Consts.MethodTypechangeAppKey, {
appKey: newAppKey
});
ChatClient.hasErrorFromResult(r);
}
/**
* Compresses the debug log into a gzip archive.
*
* Best practice is to delete this debug archive as soon as it is no longer used.
*
* @returns The path of the compressed gz file.
*
* @throws Error, see {@link ChatError}
*/
async compressLogs() {
console.log(`${ChatClient.TAG}: compressLogs:`);
let r = await _Native.Native._callMethod(_Consts.MethodTypecompressLogs);
ChatClient.hasErrorFromResult(r);
return r === null || r === void 0 ? void 0 : r[_Consts.MethodTypecompressLogs];
}
/**
* Gets all the information about the logged in devices under the specified account.
*
* @param username The user ID you want to get the device information.
* @param password The password.
* @returns The list of the online devices.
*
* @throws Error, see {@link ChatError}
*/
async getLoggedInDevicesFromServer(username, password) {
console.log(`${ChatClient.TAG}: getLoggedInDevicesFromServer: ${username}, ${password}`);
let result = await _Native.Native._callMethod(_Consts.MethodTypegetLoggedInDevicesFromServer, {
[_Consts.MethodTypegetLoggedInDevicesFromServer]: {
username: username,
password: password
}
});
ChatClient.hasErrorFromResult(result);
let r = new Array(1);
let list = result === null || result === void 0 ? void 0 : result[_Consts.MethodTypegetLoggedInDevicesFromServer];
list.forEach(element => {
r.push(new _ChatDeviceInfo.ChatDeviceInfo(element));
});
return r;
}
/**
* Force the specified account to logout from the specified device, to fetch the device ID: {@link ChatDeviceInfo#resource}.
*
* @param username The account you want to force logout.
* @param password The account's password.
* @param resource The device ID, see {@link ChatDeviceInfo#resource}.
*
* @throws Error, see {@link ChatError}
*/
async kickDevice(username, password, resource) {
console.log(`${ChatClient.TAG}: kickDevice: ${username}, ${password}, ${resource}`);
let r = await _Native.Native._callMethod(_Consts.MethodTypekickDevice, {
[_Consts.MethodTypekickDevice]: {
username: username,
password: password,
resource: resource
}
});
ChatClient.hasErrorFromResult(r);
}
/**
* Kicks out all the devices logged in under the specified account.
*
* @param username The account you want to log out from all the devices.
* @param password The account's password.
*
* @throws Error, see {@link ChatError}
*/
async kickAllDevices(username, password) {
console.log(`${ChatClient.TAG}: kickAllDevices: ${username}, ${password}`);
let r = await _Native.Native._callMethod(_Consts.MethodTypekickAllDevices, {
[_Consts.MethodTypekickAllDevices]: {
username: username,
password: password
}
});
ChatClient.hasErrorFromResult(r);
}
addConnectionListener(listener) {
console.log(`${ChatClient.TAG}: addConnectionListener: `);
this._connectionListeners.add(listener);
}
removeConnectionListener(listener) {
console.log(`${ChatClient.TAG}: removeConnectionListener: `);
this._connectionListeners.delete(listener);
}
removeAllConnectionListener() {
console.log(`${ChatClient.TAG}: removeAllConnectionListener: `);
this._connectionListeners.clear();
}
addMultiDeviceListener(listener) {
this._multiDeviceListeners.add(listener);
}
removeMultiDeviceListener(listener) {
this._multiDeviceListeners.delete(listener);
}
removeAllMultiDeviceListener() {
this._multiDeviceListeners.clear();
}
addCustomListener(listener) {
this._customListeners.add(listener);
}
removeCustomListener(listener) {
this._customListeners.delete(listener);
}
removeAllCustomListener() {
this._customListeners.clear();
}
get chatManager() {
return this._chatManager;
}
}
exports.ChatClient = ChatClient;
_defineProperty(ChatClient, "eventType", 2);
_defineProperty(ChatClient, "TAG", 'ChatClient');
_defineProperty(ChatClient, "_instance", void 0);
//# sourceMappingURL=ChatClient.js.map