Giter VIP home page Giter VIP logo

open-im-sdk-web's Introduction

MiniProgram 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.

open-im-sdk is a pure javascript library. It doesn't store any information inside browser, instead it connects to oimws the proxy layer. This proxy layer is OpenIM SDK Core's websocket proxy(listening on port 10003 by deafult). open-im-sdk and open-im-sdk-wasm's interfaces are completely the same. Without modifying any code, your website can run in mini-app.

Documentation 📚

Visit https://docs.openim.io/ for detailed documentation and guides.

For the SDK reference, see https://docs.openim.io/sdks/quickstart/browser.

Installation 💻

Adding Dependencies

npm install open-im-sdk --save

Usage 🚀

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

Importing the SDK

import { OpenIMSDK } from 'open-im-sdk';

const OpenIM = new OpenIMSDK();

Logging In and Listening for Connection Status

Note: You need to deploy OpenIM Server first, the default port of OpenIM Server is 10001, 10002, 10003.

import { CbEvents } from 'open-im-sdk';
import type { WsResponse } from 'open-im-sdk';

OpenIM.on(CbEvents.OnConnecting, handleConnecting);
OpenIM.on(CbEvents.OnConnectFailed, handleConnectFailed);
OpenIM.on(CbEvents.OnConnectSuccess, handleConnectSuccess);

OpenIM.login({
  userID: 'IM user ID',
  token: 'IM user token',
  platformID: 5,
  wsAddr: 'ws://your-server-ip:10003',
  apiAddr: 'http://your-server-ip:10002',
});

function handleConnecting() {
  // Connecting...
}

function handleConnectFailed({ errCode, errMsg }: WsResponse) {
  // Connection failed ❌
  console.log(errCode, errMsg);
}

function handleConnectSuccess() {
  // Connection successful ✅
}

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 { CbEvents } from 'open-im-sdk';
import type { WsResponse, MessageItem } from 'open-im-sdk';

// Listenfor new messages 📩
OpenIM.on(CbEvents.OnRecvNewMessages, handleNewMessages);

const message = (await OpenIM.createTextMessage('hello openim')).data;

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

function handleNewMessages({ data }: WsResponse<MessageItem[]>) {
  // New message list 📨
  console.log(data);
}

Examples 🌟

You can find a demo web app that uses the SDK in the openim-pc-web-demo repository.

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-web's People

Contributors

bloomingg avatar rfyiamcool 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

open-im-sdk-web's Issues

sendMessage支持conversationID参数

The current parameters are:

export type SendMsgParams = {
  recvID: string;
  groupID: string;
  offlinePushInfo?: OfflinePush;
  message: string;
};

I don't support session IDs. I want group chat and single chat to follow the same logic. If it supports conversationID, it would be very simple. Why can't we use conversationID? And it is important to distinguish between recvID and groupID

Feature: add group Api for miniProgram

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

mini program do not support wasm so we need to develop a new way to support it

Solution Description

add group Api for miniProgram

Benefits

add group Api for miniProgram

Potential Drawbacks

none

Additional Information

none

Bug: Emoji in message be shown as unreadable codes when sending or receiving messages though miniapp

What happened?

Emoji in message be shown as unreadable codes when sending or receiving messages though miniapp.

The reason maybe is that there is no TextEncoder/TextDecoder in weixin miniapp .

What did you expect to happen?

please repair the Encoder/Decoder implemented in sdk for emoji

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

send text message with emoji though miniapp sdk

Anything else we need to know?

No response

version

open-im-sdk 3.4.1

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

Bug: <no exported member  WsResponse>

What happened?

I tried to use an example, but I couldn't import WsResponse

import { OpenIMSDK } from 'open-im-sdk';

const OpenIM = new OpenIMSDK();
import { CbEvents } from 'open-im-sdk';
import type { WsResponse } from 'open-im-sdk';

OpenIM.on(CbEvents.OnConnecting, handleConnecting);
OpenIM.on(CbEvents.OnConnectFailed, handleConnectFailed);
OpenIM.on(CbEvents.OnConnectSuccess, handleConnectSuccess);

OpenIM.login({
userID: 'IM user ID',
token: 'IM user token',
platformID: 5,
wsAddr: 'ws://your-server-ip:10003',
apiAddr: 'http://your-server-ip:10002',
});

function handleConnecting() {
// Connecting...
}

function handleConnectFailed({ errCode, errMsg }: WsResponse) {
// Connection failed ❌
console.log(errCode, errMsg);
}

function handleConnectSuccess() {
// Connection successful ✅
}

What did you expect to happen?

I want to import WsResponse

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

Try importing WsResponse

Anything else we need to know?

image

version

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

Cloud provider

1

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

SDK使用(wasm),wasm_exec.js:198 exit code: 2

SDK使用步骤(wasm)
根据这个操作配置webpack4+vue项目,代码是跑起来了,但是socket连接不上,调试窗口,连ws都没有发送出去
只有下面这个信息以及错误
SDK => (invoked by js) run login with args {"params":{"userID":"xxx","token":"xxx","url":"ws://ip:10001","platformID":5,"operationID":"1669881005699"},"operationID":"fccbf721-523c-4cd2-9ce4-b730901e977a"}
wasm_exec.js:198 exit code: 2

Bug: upload img error

What happened?

WechatIMG3490

What did you expect to happen?

fix this bug

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

IMSDK.createImageMessageByFile

Anything else we need to know?

No response

version

```console $ {name} version # paste output here "open-im-sdk": "^3.5.1-alpha.7",

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

微信小程序不支持Worker对象导致心跳失败

  • name: open-im-sdk
  • version: 2.3.0

WeChat mini program documentation

Worker
Related documents: Multi threaded Worker

Worker instance, which can be accessed in the main thread through wx.createWorker interface acquisition, which can be obtained through the global variable worker in the worker thread.

src/utils/worker.ts

function create(fun: any) {
  const blob = new Blob(["(" + fun + ")()"]);
  const url = window.URL.createObjectURL(blob);
  const worker = new Worker(url);
  return worker;
}

调用jssdk deleteConversationFromLocalAndSvr

Unable to delete session information. Calling deleteConversationFromLocalAndSvr based on conversionid failed to delete callback information. Deleting the session returned success with no error. Calling getConversationListSplit again will continue to display the deleted session ID?

SendMessage errCode: 1001 "Request Parameter Error",groupId 不能为null导致

error

openIm.createTextMessage('send message').then(res => {
                    console.log(res.data)
                    const params = {
                        recvID: "f400ccbf06b642a4abf9c589876566ec",
                        groupID: null,
                        message: res.data,
                    };
                    openIm.sendMessage(params)
                })

success

 openIm.createTextMessage('send message').then(res => {
                    console.log(res.data)
                    const params = {
                        recvID: "f400ccbf06b642a4abf9c589876566ec",
                        groupID: "",
                        message: res.data,
                    };
                    openIm.sendMessage(params)
                })

GroupId cannot be null, can only be an empty string

没有创建会话api

场景:将会话A删除后,就无法与该用户发送消息。缺少创建会话的api

请问微信小程序支持吗?

May I ask if the WeChat mini program supports it? In the WeChat developer tool, the websocket connection reported an error as follows:
image

同一userID使用不同platformID申请到不同的token, 用jssdk登录, 会出现概率无法监听到新消息的情况

What happened?

使用同一个userID+2个不同的platformID, 获得到2个不同的token, 在2个浏览器窗口分别使用这些token登录, 并监听新消息(IMSDK.on(CbEvents.OnRecvNewMessages)), 会概率性出现 其中一个窗口监听不到新消息

What did you expect to happen?

两个窗口都能正常使用

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

  1. 使用同一个userID+2个不同的platformID, 获得到2个不同的token(使用api中/auth/user_token)
  2. openim-server 配置多端登陆为10(multiLoginPolicy: 10)
  3. 在2个浏览器窗口分别使用这些token登录, 并监听新消息(IMSDK.on(CbEvents.OnRecvNewMessages))
  4. 发送消息给第一步的userID
    image

Anything else we need to know?

No response

version

截止当前的最新版本

Cloud provider

none

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: add User / message api List

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?

❎ No

Problem Description

from websocket transfer to http protocol

Solution Description

new custom protocol to imgrate from websocket

Benefits

miniprogram developer

Potential Drawbacks

none

Additional Information

none

open-im-sdk failed to log in

What happened?

error *errors.withStack not implement CodeError: init database ==> github.com/openimsdk/openim-sdk-core/v3/pkg/db.NewDataBase()https://github.com/108: initDB failed ./db: ==> github.com/openimsdk/openim-sdk-core/v3/pkg/db.(*DataBase).initDB()@139: open db failed /home/linux/oimws/db/OpenIM_v3_openIM123456.db: Binary was compiled with 'CGO_ENABLED=0', go-sqlite3 requires cgo to work. This is a stub: 10006 SdkInternalError

What did you expect to happen?

Be able to log in

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

import { OpenIMSDK } from 'open-im-sdk';
const OpenIM = new OpenIMSDK();
import { CbEvents } from 'open-im-sdk';
import type { WsResponse } from 'open-im-sdk';

OpenIM.on(CbEvents.OnConnecting, handleConnecting);
OpenIM.on(CbEvents.OnConnectFailed, handleConnectFailed);
OpenIM.on(CbEvents.OnConnectSuccess, handleConnectSuccess);

OpenIM.login({
userID: 'openIM123456',
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySUQiOiJvcGVuSU0xMjM0NTYiLCJQbGF0Zm9ybUlEIjo1LCJleHAiOjE3MDk0Mjg3OTEsIm5iZiI6MTcwMTY1MjQ5MSwiaWF0IjoxNzAxNjUyNzkxfQ.D4m4mJuk_JJLVgfQflNYNIfi86LsYJohqQJcVGrxPt4',
platformID: 5,
wsAddr: 'ws://192.168.1.127:10003',
apiAddr: 'http://192.168.1.127:10002/',
})

function handleConnecting() {
// Connecting...
}

function handleConnectFailed({ errCode, errMsg }: WsResponse) {
// Connection failed ❌
console.log(errCode, errMsg);
}

function handleConnectSuccess() {
// Connection successful ✅
}

Anything else we need to know?

No response

version

"@types/vue": "^2.0.0", "@vitejs/plugin-vue": "^4.5.1", "@vue/cli-service": "^5.0.8", "open-im-sdk": "^3.4.1", "vue": "^3.3.8"

Cloud provider

OS version

win11 22631.2715

Install tools

Feature: <add jssdk for miniprogram>

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?

❎ No

Problem Description

mini-program do not support wasm.

Solution Description

add a specified jssdk for mini-program.

Benefits

none

Potential Drawbacks

none

Additional Information

none

接收到重复数据,在wsSend函数里面设置onmessage函数存在问题

你好,使用SDK测试发现,会有接收到多条重复数据的问题。一路查下去发现每次发送信息都对应 onmessage 进行赋值
private wsSend = (
params: WsParams,
resolve: (value: WsResponse | PromiseLike) => void,
reject: (reason?: any) => void
) => {
...
this.ws!.onMessage(handleMessage);
}

把this.ws!.onMessage(handleMessage);放到createWs是正常的。
这问题在小程序里面尤其严重,每次调用发送相关的函数,接收信息就会多一条。

个人对这SDK也不是很熟悉。都是参照h5 demo 使用。不知道是我使用方式又问题还是确实存在问题。

复现方式:h5 demo 。A退出登录,重新登录。B发送信息给A。A会收到2条重复的信息。

非好友关系,给对方发消息,监听不到

For example, there are now three users: 'A', 'B', and 'C'
A 'user logs in based on' OpenMetaOffice Electron ', while' B 'and' C 'obtain' token 'login through' API 'and send messages to' A 'user.' A 'user only listens to' B 'user messages, while' C 'user cannot listen. The' OnConversationChanged 'event will not be triggered The pull session list method is also invalid for 'openIM. getAllConversationList' and 'openIM. getConversationListSplit'
During the testing process, did the scenario of deleting all sessions several times and then initiating the session result in the resend message not being received?

Regarding token

The doc() only describes that we should take secret to server in order to get token, but doc doesn't tell us how to get secret and how to take secret to get token, could you describe more details?

uniapp 用这套代码跑不成功

What would you like to share?

我们现在H5用纯JSSDK库是跑起来了,连接ws是10003端口, 能正常登录、收发消息, 但是在uni-app环境中跑这个纯JSSDK库的时候, 不能正常登录, 从服务端的日志看, 是正常收到login请求, 并发送了回执了, 但是客户端没有收到回执, 请问是什么原因?

Additional information

uniapp跑这套代码,客户端没有收到回执

Bug: logout in miniprogram sdk can not work, promise has no return

What happened?

when in miniprogram sdk, logout api can not work, promise has no return. so that , app can not logout . after a white, sdk will reconnect to im-server automaticly . but this is not we want.

when client call logout , oimws server has a error message "use of closed network connection"

What did you expect to happen?

please check the logout api in open-im-sdk for miniprogram, maybe there is a bug. we hope the bug could be fixed as soon as possible.

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

  1. start oimws/im-server
  2. login with open-im-sdk for miniprogram
  3. logout, then there is no return.

Anything else we need to know?

No response

version

"open-im-sdk": "^3.4.0" oimws: 873acb276a70c964a0bc131977debb5bd4a29ccf open-im-server: release-vv3.4

Cloud provider

OS version

ubuntu 20

Install tools

Feature: complete group api for v3

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

complete group api for v3

Benefits

complete group api for v3

Potential Drawbacks

No response

Additional Information

No response

在uni-app中使用的问题

Question 1

The getPlatform method returns unknown on both the mini program and the app, and the subsequent logic will cause both the app and the mini program to use wx to create websockets. This issue can be temporarily resolved in this way
<img width="362" alt="Screenshot 2022-08-29 PM 3 48 49" src=“ https://user-images.githubusercontent.com/43745492/187151193-c739668d-580b-4096-9b2a-2ac5dc63bbe4.png >

Question 2

On the WeChat applet side, after logout failed to close websocket, messages could be received after logout. After debugging, it was found that it was a problem to judge logout in handleMessage. When the logout request had been answered, data.event was Logout, but the value circled in the figure was still Login (the logout I called after login). This logout condition was entered after calling logout several times, On the H5 end, there is no such issue. Can we directly determine whether it is a logout instruction based on data. event?
<img width="808" alt="Enterprise WeChat screenshot _80d26063-2a2b-4b7e-ae05-011b25dd9a9c" src=“ https://user-images.githubusercontent.com/43745492/187152106-c4563a60-a9c0-4ddb-bf9f-90d11568aa41.png >

Question 3

The SDK homepage indicates that it can be used on the uni app, but there are often problems with the app and iOS, which are basically unusable. This may be my personal problem, but I have tried many methods and always encounter various problems. Therefore, I raise a question here, what is the relationship between this SDK and the uni app's SDK, or what is the difference? Currently, in my opinion, this SDK is not easy to use in places other than H5
<img width="916" alt="Enterprise WeChat screenshot edf0b2a9-7134-43e1-b091-7fd7c7f36f24" src=“ https://user-images.githubusercontent.com/43745492/187153915-1b8d9d65-40e5-47b5-b0fa-1de6e3313cf8.png >

Bug: Failed to execute 'decode' on 'TextDecoder': The provided value is not of type '(ArrayBuffer or ArrayBufferView)'.

What happened?

启动时报错
image

What did you expect to happen?

正常启动

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

按文档启动

Anything else we need to know?

No response

version

"open-im-sdk": "^3.5.1-alpha.7"
oimws: 3.5.1-alpha.8

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: v3 refactor and complete friend api

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

v3 refactor and complete friend api

Benefits

v3 refactor and complete friend api

Potential Drawbacks

No response

Additional Information

No response

Bug: mini program sdk doesn‘t work,when network failure happens

What happened?

When the mini program application logs in to the server, if there is a network problem or disconnection, SDK will only retry the connection once. Afterwards, if the application is not restarted, any OpenIM sdk methods will be unable to be called and all will get stuck

What did you expect to happen?

1, fix sdk connect retry count;
2, when network failure happens, sdk could throw exception to application. so that , the application can do something.

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

1, login successful with sdk;
2, broke the network ,or open airplane mode;
3, wait for sdk automatic reconnect fail, almost 20 seconds;
4, call some api with sdk, then you are stacked;

Anything else we need to know?

No response

version

open-im-sdk: 3.4.1

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

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.