# @relationlabs/im

> >JS SDK for relation IM: A simple API for building IM services.

Latest version **0.4.0-beta-3** (published 2023-08-16) · 0 weekly downloads

## Install

```sh
npm install @relationlabs/im
pnpm add @relationlabs/im
yarn add @relationlabs/im
bun add @relationlabs/im
```

## Health

**Score 25/100 (F)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities.

Warnings: low downloads; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.4.0-beta-3 |
| Published | 2023-08-16 |
| First published | 2022-05-10 |
| Weekly downloads | 0 |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 1 |
| Unpacked size | 92.6 KB |
| Known vulnerabilities | 0 (+23 in 1 direct dependencies) |
| Install scripts | no |
| Author | relationlabs |
| Maintainers | ins893412899, relationlabs |

## Links

- npm: https://www.npmjs.com/package/@relationlabs/im
- npm.io page: https://npm.io/package/@relationlabs/im

## Dependencies (1)

- [axios](https://npm.io/package/axios.md) ^0.27.2

## Recent versions

- 0.4.0-beta-3 (latest) — 2023-08-16
- 0.4.0-beta-2 — 2023-08-02
- 0.4.0-beta — 2023-08-01
- 0.3.3 — 2023-03-05
- 0.3.2 — 2023-02-24
- 0.2.1 — 2022-06-01
- 0.2.0 — 2022-05-25
- 0.1.4 — 2022-05-10
- 0.1.1 — 2022-05-10
- 0.1.0 — 2022-05-10

## README

# @relationlabs/im

>JS SDK for relation IM: A simple API for building IM services.

## `Quick start`

Download using NPM
```bash
npm install --save @relationlabs/im
npm install --save @relationlabs/auth
```

then

use `authByMetamask` to activate `Metamask` signing and acquire an `addressAuthToken`

```javascript
import { authByMetamask } from "@relationlabs/auth";

const { error, token: addressAuthToken } = await authByMetamask()
```

then

use  `getRelationToken` to acquire `unifiedAuthToken`. The `APIKEY` should be acquired from the Admin.

```javascript
import RelationIM from "@relationlabs/im";
import { authByMetamask } from "@relationlabs/auth";

const { error, token: addressAuthToken } = await authByMetamask()

const APIKEY = '581c6c4fa0b54912b00088aa563342a4'

if (!error && addressAuthToken) {
    const { error, token: unifiedAuthToken } = await RelationIM.getRelationToken(addressAuthToken, APIKEY)
    if (!error && unifiedAuthToken) {

    }
}
```

then

instantiate an `im` instance

```javascript
const myIm = RelationIM.init({token: unifiedAuthToken, apiKey: APIKEY, connect: true})
```

---

## `API reference`

### Static Method

#### RelationIM.getRelationToken (acquire a unifiedAuthToken)

```javascript
RelationIM.getRelationToken(addressAuthToken, APIKEY)
```

| **Config options**  | **Description** |  **Default**   |
| :-----------------: | :-------------: | :------------: |
|  addressAuthToken: *string*  | Required field. The token is acquired via authByMetamask. |                |
| apiKey: *string*  |   Required field. It is acquired from the Admin.    |                |

Note: In the return message, `token` refers to the account's `unifiedAuthToken` in `relation`. If there is no such account, one will be registered by default.

#### RelationIM.init(You need to initialize an API before calling it.)

```javascript
RelationIM.init({configOptions})
```

| **Config options** |          **Description**           | **Default** |
| :----------------: | :--------------------------------: | :---------: |
|  token: *string*   |         Required. The unifiedAuthToken of a user          |             |
|  apiKey: *string*  |        Required. Acquired from the Admin.         |             |
| connect: *boolean* | Optional. Whether to establish a socket connection to receive message. |    false    |
| refresh: *boolean* | Optional. Whether to initialize the interface again(refresh it). |    false    |

Note: When using `init` to initialize the interface, you can use `connect` to specify whether to connect to `socket`. The parameter `refresh` means whether to refresh the `RelationIM` instance.

#### RelationIM.getInstance(to acquire the `RelationIM` instance already initialized.)

```javascript
RelationIM.getInstance()
```

Note: Normally you only need one  `RelationIM`  instance. However, you may frequently call  common APIs. To avoid redunant initiations of `RelationIM` and  `socket , we suggest you manually specify a static method  `RelationIM.getInstance` where needed so that you can acquire the `RelationIM` instance already initialized.

---

### Events

```javascript
import { Im } from "@relationlabs/im";

myIm.bind(Im.RECEIVE_MSG_OK, (e) => {
    const message = e['im-message']
})
```



|     **Name**      |       **Description**        |                     **Callback Params**                      |
| :---------------: | :--------------------------: | :----------------------------------------------------------: |
| Im.CONNECT_OK | 成功连接socket时触发 |  |
| Im.CONNECT_ERR | socket错误时触发 |  |
| Im.CONNECT_CLOSE | socket关闭时触发 | { reason: '' } |
| Im.RECEIVE_MSG_OK | 连接socket之后有新消息时触发 | { 'im-message': { channelUuid, sendUuid, from, content } } |
|                   |                              |                                                              |
---
### Methods

#### setImToken(token: string)

> Update the token for an instance

```javascript
myIm.setImToken('new token')
```

#### setImApiKey(apiKey: string)

> Update the ApiKey for an instance

```javascript
myIm.setImApiKey('new apiKey')
```

#### getUserInfo(address?: string)

> Acquire a user's basic information

|  **Parameter** | **Type** | **Description** |  **Default** |
|  ---- | ----  | ---- | ----  |
| address | string | Optional. To specify a user's `relationId` or web3 address. Empty means querying oneself. |   |

#### getFollowing(data: { address: string, cursor?: string, limit?: number })

> To acquire a list of the people the user is following.

|  **Parameter** | **Type** | **Description** |  **Default** |
|  ---- | ----  | ---- | ----  |
| address | string | Required. To specify a user's `relationId` or web3 address. |   |
| cursor | string | The cursor data returned by the last page(optional). If cursor is empty, then you are querying the first page. |  |
| limit | number | How much data should be returned per page(optional). The upper limit is 100. | 20 |

#### recommend(data: { address: string, cursor?: string, limit?: number })

> The recommendation engine will recommend potential friends based on these factors: the  user's Twitter followers, transactions on the Ethereum chain, NFT holdings, and users in the lists of following.

|  **Parameter** | **Type** | **Description** |  **Default** |
|  ---- | ----  | ---- | ----  |
| cursor | string | The cursor data returned by the last page(optional). If cursor is empty, then you are querying the first page. |  |
| limit | number | How much data should be returned per page(optional). The upper limit is 100. | 20 |

#### follow(address: string)

> To follow a user

|  **Parameter** | **Type** | **Description** |  **Default** |
|  ---- | ----  | ---- | ----  |
| address | string | Required. To specify a user's `relationId` or web3 address. |   |

#### unfollow(address: string)

> To unfollower a user

|  **Parameter** | **Type** | **Description** |  **Default** |
|  ---- | ----  | ---- | ----  |
| address | string | Required. To specify a user's `relationId` or web3 address. |   |


#### sendMessage(data: sendMessageType)

> To send a message. The data structure sendMessageType has the following parameters:

|  **Parameter** | **Type** | **Description** |  **Default** |
|  ---- | ----  | ---- | ----  |
| content | string | content of the message | Required. The text content. |
| channelUuid | string | Required. The uuid of the channel. | - |
| toRelationId | string | Optional. The receiver's `relationId` | - |
| sendUuid | string | Optional. The uuid of the message|  |
| type | string | Optional. The message type. | TEXT |
Note: `channelUuid` and `toRelationId` cannot be empty at the same time. If the `sendUuid`is empty, the system will connect the current timestamp and a random number with `channelUuid` and `toRelationId` as the default `sendUuid`.
If you are sending a message to a user never had a conversation before, once the message is sent, a new channel will be created automatically and its `channelUuid` will be returned.

#### userChannelsList(data: listRequestType)

> To acquire a user's list of channels. The parameters of listRequestType are as follows:

|  **Parameter** | **Type** | **Description** |  **Default** |
|  ---- | ----  | ---- | ----  |
| keyword | string | Optional. Descending order. | The name of the channel. Fuzzy search is supported. |
| cursor | string | The cursor data returned by the last page(optional). If cursor is empty, then you are querying the first page. |  |
| limit | number | How much data should be returned per page(optional).  | 20 |

#### messageList(data: messageListRequestType)

> To acquire the list of messages of a channel for a user. The parameters of messageListRequestType are as follows:

|  **Parameter** | **Type** | **Description** |  **Default** |
|  ---- | ----  | ---- | ----  |
| maxCreateAt | number | Required. A timestamp based on milliseconds. It needs to be greater than the timestamp of the last message sent on the current page. | - |
| channelUuid | string | Optional. UUID of the channel. | - |
| toRelationId | string | Optional. The receiver's `toRelationId` . | - |
| limit | number | How much data should be returned per page(optional). | 50 |

#### channelCreate(data: {members, name, type})

> To create a new channel

|  **Parameter** | **Type** | **Description** |  **Default** |
|  ---- | ----  | ---- | ----  |
| name | string | Required. The name of the channel. |  |
| type | string |  Group Chat Type, enumerated as: G-Regular Group Chat, P-p2p Group Chat  |  |
| members | string[] | The collection of group members' relationId. If type=P, then it will only see the caller and the first user as group chat members. The admin of the group chat is the current caller. | - |

#### channelInfo(channelUuid: string)

> To acquire the details of a channel.

|  **Parameter** | **Type** | **Description** |  **Default** |
|  ---- | ----  | ---- | ----  |
| channelUuid | string | Required. The uuid of the channel. | - |


#### channelDisband(channelUuid: string)

> dismiss a channel

|  **Parameter** | **Type** | **Description** |  **Default** |
|  ---- | ----  | ---- | ----  |
| channelUuid | string | Required. The uuid of the channel. | - |

#### channelMemberLeave(channelUuid: string)

> when the current user choose to leave a channel.

|  **Parameter** | **Type** | **Description** |  **Default** |
|  ---- | ----  | ---- | ----  |
| channelUuid | string | Required field. The UUID of the channel. | - |
---

### to parse a message

use the 'messageParse()' method to parse an original message

```javascript
import { messageParser } from "@relationlabs/im"

const msg: Message

const parsedMsg: ParsedMessage = messageParser(msg)
```

// to define types

```typescript
// message type
type MessageType = 'SYS' | 'TEXT' | 'CARD' | 'ANNOUNCEMENT' | 'BATCH_TRANSFER';

// the construct of an original message
type Message = {
    type: MessageType;
    content: string;
    quote?: Message;
}

// the construct generated by parsing a message
type ParsedMessage = {
    type: MessageType;
    content: string;
    parsedContent?: ParsedContent;
    quote?: Message;
    unidentified?: boolean | undefined;
}

//content parsed
type ParsedContent = string|JoinGroupMessage|ShareMessage|NormalImageMessage|NFTMessage|MentionMessage

// invitation to join a chat group
type JoinGroupMessage = {
    groupId: string;
    groupName: string;
    chatType: 'p2p'|'group'
}

// sharing an URL
type ShareMessage = {
    shareUrl: string;
    shareName: string;
    shareIcon: string;
}

// normal image
type NormalImageMessage = {
    imgUrl: string;
    s3Key: string;
}

// NFT
type NFTMessage = {
    imgUrl: string;
    nftChain: string;
}

// to quote a message
type MentionMessage = {
    mentionContent: string;
    mentionPosition: number[];
}
```

In `ParsedMessage` construct, `unidentified` flags if the message can be parsed, and `parsedContent` is the result parsed from the content in the original message. Other keys in the construct come from respective segments in the construct of the original message.

---
_Source: https://npm.io/package/@relationlabs/im · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
