Coder Social home page Coder Social logo

openimsdk / open-im-sdk-reactnative Goto Github PK

View Code? Open in Web Editor NEW
37.0 4.0 47.0 24.04 MB

IM ReactNative

License: MIT License

Shell 0.08% Java 34.46% JavaScript 1.07% TypeScript 19.83% Swift 0.03% C 0.05% Objective-C 42.04% Ruby 2.06% Objective-C++ 0.38%

open-im-sdk-reactnative's Introduction

React Native Client SDK for OpenIM 👨‍💻💬

Use this SDK to add instant messaging capabilities to your application. By connecting to a self-hosted OpenIM server, you can quickly integrate instant messaging capabilities into your app with just a few lines of code.

The iOS SDK core is implemented in OpenIM SDK Core. Using gomobile, it can be compiled into an XCFramework for iOS integration. iOS interacts with the OpenIM SDK Core through JSON, and the SDK exposes a re-encapsulated API for easy usage. In terms of data storage, iOS utilizes the SQLite layer provided internally by the OpenIM SDK Core.

The android SDK core is implemented in OpenIM SDK Core. Using gomobile, it can be compiled into an AAR file for Android integration. Android interacts with the OpenIM SDK Core through JSON, and the SDK exposes a re-encapsulated API for easy usage. In terms of data storage, Android utilizes the SQLite layer provided internally by the OpenIM SDK Core.

The React Native Client SDK use NativeModule system exposes instances of Java/Objective-C classes to JavaScript (JS) as JS objects, thereby allowing you to execute arbitrary native code from within JS.

Tips 🔔

  1. The [email protected] has contains significant disruptive updates. If you need to upgrade, please check the incoming data and the returned data.

  2. Unlike other SDKS, React Native SDK operationID is not optional, but required.

Documentation 📚

Visit https://doc.rentsoft.cn for detailed documentation and guides.

For the SDK reference, see https://doc.rentsoft.cn/sdks/quickstart/reactnative.

Installation 💻

Adding Dependencies

yarn add open-im-sdk-rn

For android add following urls to build gradle:

https://open-im-online.rentsoft.cn:51000/repository/maven2/

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext {
        buildToolsVersion = "33.0.0"
        minSdkVersion = 21
        compileSdkVersion = 33
        targetSdkVersion = 33

        // We use NDK 23 which has both M1 support and is the side-by-side NDK version from AGP.
        ndkVersion = "23.1.7779620"
    }
    repositories {
        google()
        mavenCentral()
        maven {
            allowInsecureProtocol = true
            url 'https://open-im-online.rentsoft.cn:51000/repository/maven2/'
        }
    }
    dependencies {
        classpath("com.android.tools.build:gradle")
        classpath("com.facebook.react:react-native-gradle-plugin")
    }
}
allprojects {
    repositories {
        maven {
            allowInsecureProtocol = true
            url 'https://open-im-online.rentsoft.cn:51000/repository/maven2/'
        }
    }
}

Usage 🚀

The following examples demonstrate how to use the SDK. TypeScript is used, providing complete type hints.

Importing the SDK and init

import OpenIMSDKRN from 'open-im-sdk-rn';
import RNFS from 'react-native-fs';

RNFS.mkdir(RNFS.DocumentDirectoryPath + '/tmp');

OpenIMSDKRN.initSDK({
  platformID: 2,  // 1: ios, 2: android
  apiAddr: 'http://your-server-ip:10002',
  wsAddr: 'ws://your-server-ip:10001',
  dataDir: RNFS.DocumentDirectoryPath + '/tmp',
  logLevel: 5,
  isLogStandardOutput: true,
}, 'opid');

Logging In and Listening for Connection Status

import OpenIMSDKRN, { OpenIMEmitter } from 'open-im-sdk-rn';

OpenIMSDKRN.login({
  userID: 'IM user ID',
  token: 'IM user token',
}, 'opid');

OpenIMEmitter.addListener('onConnecting', () => {
  console.log('onConnecting');
});

OpenIMEmitter.addListener('onConnectSuccess', () => {
  console.log('onConnectSuccess');
});

OpenIMEmitter.addListener('onConnectFailed', ({ errCode, errMsg }) => {
  console.log('onConnectFailed', errCode, errMsg);
});

To log into the IM server, you need to create an account and obtain a user ID and token. Refer to the access token documentation for details.

Receiving and Sending Messages 💬

OpenIM makes it easy to send and receive messages. By default, there is no restriction on having a friend relationship to send messages (although you can configure other policies on the server). If you know the user ID of the recipient, you can conveniently send a message to them.

import OpenIMSDKRN, { OpenIMEmitter } from 'open-im-sdk-rn';
import type { MessageItem } from 'open-im-sdk-rn';

OpenIMEmitter.addListener('onRecvNewMessages', (data: MessageItem[]) => {
  console.log('onRecvNewMessages', data);
});

const message = await OpenIMSDKRN.createTextMessage('hello openim', 'opid');

OpenIMSDKRN.sendMessage({
  recvID: 'recipient user ID',
  groupID: '',
  message,
}, 'opid')
  .then(() => {
    // Message sent successfully ✉️
  })
  .catch(err => {
    // Failed to send message ❌
    console.log(err);
  });

Examples 🌟

You can find a demo web app that use the SDK in the openim-reactnative-demo repository.

or:

Use the examples(only the simplest SDK calls) under this project to try it out:

yarn

yarn example android

yarn example ios

Community 👥

Community Meetings 📆

We want anyone to get involved in our community and contributing code, we offer gifts and rewards, and we welcome you to join us every Thursday night.

Our conference is in the OpenIM Slack 🎯, then you can search the Open-IM-Server pipeline to join

We take notes of each biweekly meeting in GitHub discussions, Our historical meeting notes, as well as replays of the meetings are available at Google Docs 📑.

Who are using OpenIM 👀

Check out our user case studies page for a list of the project users. Don't hesitate to leave a 📝comment and share your use case.

License 📄

OpenIM is licensed under the Apache 2.0 license. See LICENSE for the full license text.

open-im-sdk-reactnative's People

Contributors

andrewzuo avatar andrewzuo01 avatar bloomingg avatar githubxiaobo avatar lgz5689 avatar skiffer-git avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

open-im-sdk-reactnative's Issues

[Other]: React Native version issue

What would you like to share?

我在 npmjs 网站看到目前 OpenIM React Native 的版本是 3.4.2,但是目前项目储存库中的 package.json 版本是 3.4.0,Tag 和 Release 只有一个不存在的版本 1.0.7,请问是否会更新一下提交、Tag 和 Release?

Additional information

No response

Maven link

What happened?

maven无法下载

What did you expect to happen?

maven无法下载

How can we reproduce it (as minimally and precisely as possible)?

maven无法下载

Anything else we need to know?

No response

version

```console $ {name} version # paste output here ```

Cloud provider

OS version

```console # On Linux: $ cat /etc/os-release # paste output here $ uname -a # paste output here # On Windows: C:\> wmic os get Caption, Version, BuildNumber, OSArchitecture # paste output here ```

Install tools

Feature: supplement the complete method

Checklist

  • I've searched for similar issues and couldn't find anything matching
  • I've discussed this feature request in the OpenIMSDK Slack and got positive feedback

Is this feature request related to a problem?

None

Problem Description

Solution Description

supplement the complete method

Benefits

supplement the complete method

Potential Drawbacks

No response

Additional Information

No response

duration transform bug

明显错误的写法
NSString *msg = Open_im_sdkCreateVideoMessageFromFullPath(opid,path, type, (int64_t)duration, snapshotPath); resolver(msg);

应该是

NSString *msg = Open_im_sdkCreateVideoMessageFromFullPath(opid,path, type, [duration longLongValue], snapshotPath); resolver(msg);

Bug: Time is always empty

What happened?

On events

  • onConversationChanged (setPin)
  • onRecvNewMessage (newMessage)
  • onRecvNewMessages (newMessages)

and method getAdvancedHistoryMessageList

return message send time and conversation messageLatestSendTime is always empty

What did you expect to happen?

converstion latestMessageSendTime is number
message sendTime is number

How can we reproduce it (as minimally and precisely as possible)?

OpenIMEmitter.addListener(CbEvents.OnConversationChanged, conversationChangeHandler);
OpenIMEmitter.addListener(CbEvents.OnRecvNewMessage, newMessageHandler);
OpenIMEmitter.addListener(CbEvents.OnRecvNewMessages, newMessageHandler);
const newMessageHandler = (data) => {
        console.log("newMessageHandler", typeof data, data)
};

newMessageHandler object [{"attachedInfo": "{\"groupHasReadInfo\":{\"hasReadCount\":0,\"groupMemberCount\":4},\"isPrivateChat\":false,\"burnDuration\":0,\"hasReadTime\":0,\"isEncryption\":false,\"inEncryptStatus\":false}", "attachedInfoElem": {"burnDuration": 0, "groupHasReadInfo": [Object], "hasReadTime": 0, "inEncryptStatus": false, "isEncryption": false, "isPrivateChat": false}, "clientMsgID": "00387be8f8a777fad977354f96e28f45", "contentType": 101, "createTime": null, "groupID": "441", "isRead": false, "msgFrom": 100, "sendID": "433", "sendTime": null, "senderNickname": "admin", "senderPlatformID": 5, "seq": 120, "serverMsgID": "614f6f2fe7801d2077aa0faf8eabe321", "sessionType": 3, "status": 2, "textElem": {"content": "dsvsd"}}]
const conversationChangeHandler = (data) => {
        console.log("conversationChangeHandler", typeof data, data)
};

conversationChnageHandler object [{"attachedInfo": "", "burnDuration": 0, "conversationID": "sg_441", "conversationType": 3, "draftText": "", "draftTextTime": 0, "ex": "", "faceURL": "", "groupAtType": 0, "groupID": "441", "hasReadSeq": 0, "isMsgDestruct": false, "isNotInGroup": false, "isPinned": false, "isPrivateChat": false, "latestMsg": "{\"clientMsgID\":\"3316167a808151cc5c3b53589311449b\",\"serverMsgID\":\"a534d4255bf79c4a43603b0c56da0a29\",\"createTime\":1711925246158,\"sendTime\":1711925246321,\"sessionType\":3,\"sendID\":\"433\",\"msgFrom\":100,\"contentType\":101,\"senderPlatformID\":5,\"senderNickname\":\"admin\",\"groupID\":\"441\",\"seq\":118,\"isRead\":false,\"status\":2,\"attachedInfo\":\"{\\\"groupHasReadInfo\\\":{\\\"hasReadCount\\\":0,\\\"groupMemberCount\\\":4},\\\"isPrivateChat\\\":false,\\\"burnDuration\\\":0,\\\"hasReadTime\\\":0,\\\"isEncryption\\\":false,\\\"inEncryptStatus\\\":false}\",\"textElem\":{\"content\":\"sdfsd\"},\"attachedInfoElem\":{\"groupHasReadInfo\":{\"hasReadCount\":0,\"groupMemberCount\":4},\"isPrivateChat\":false,\"burnDuration\":0,\"hasReadTime\":0,\"isEncryption\":false,\"inEncryptStatus\":false}}", "latestMsgSendTime": null, "maxSeq": 0, "minSeq": 0, "msgDestructTime": 0, "recvMsgOpt": 0, "showName": "ПАО СБЕРБАНК", "unreadCount": 2, "updateUnreadCountTime": 0, "userID": ""}]
const getHistoryMessageListByReq =  async () => {
        const conversationID = useConversationStore.getState().currentConversation?.conversationID;
            
        const data = await OpenIMSDKRN.getAdvancedHistoryMessageList({
            userID: "",
            groupID: "",
            count: 15,
            lastMinSeq: 0,
            startClientMsgID: "",
            conversationID,
        }, Date.now().toString());
        console.log("getHistoryMessageListByReq", typeof data, data)
}
getHistoryMessageListByReq()

getAdvancedHistoryMessageList object {"errCode": 0, "errMsg": "", "isEnd": false, "lastMinSeq": 13, "messageList": [{"attachedInfoElem": [Object], "clientMsgID": "099e34c07d4d516656c2922d537714f2", "contentType": 101, "createTime": null, "groupID": "431", "isRead": false, "msgFrom": 100, "recvID": "493", "sendID": "493", "sendTime": null, "senderNickname": "client", "senderPlatformID": 2, "seq": 13, "serverMsgID": "5f843ed4eb4aae503591b666d16d0a7f", "sessionType": 3, "status": 2, "textElem": [Object]}]

Anything else we need to know?

I'm using the version 3.5.1-rc.0 because the version 3.4.3 doesn't raise event onConversationChanged

On the Browser sdk sendTime is always returned

version

```console $ {name} version # 3.5.1-rc.0 ```

Cloud provider

latest

OS version

```console # On Linux: $ cat /etc/os-release # paste output here $ uname -a # paste output here # On Windows: C:\> wmic os get Caption, Version, BuildNumber, OSArchitecture # paste output here ```

Install tools

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.