0.4.0-beta-3 • Published 9 months ago

@relationlabs/im v0.4.0-beta-3

Weekly downloads
-
License
-
Repository
-
Last release
9 months ago

@relationlabs/im

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

Quick start

Download using NPM

npm install --save @relationlabs/im
npm install --save @relationlabs/auth

then

use authByMetamask to activate Metamask signing and acquire an addressAuthToken

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.

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

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

API reference

Static Method

RelationIM.getRelationToken (acquire a unifiedAuthToken)

RelationIM.getRelationToken(addressAuthToken, APIKEY)
Config optionsDescriptionDefault
addressAuthToken: stringRequired field. The token is acquired via authByMetamask.
apiKey: stringRequired 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.)

RelationIM.init({configOptions})
Config optionsDescriptionDefault
token: stringRequired. The unifiedAuthToken of a user
apiKey: stringRequired. Acquired from the Admin.
connect: booleanOptional. Whether to establish a socket connection to receive message.false
refresh: booleanOptional. 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.)

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 methodRelationIM.getInstancewhere needed so that you can acquire theRelationIM` instance already initialized.


Events

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

myIm.bind(Im.RECEIVE_MSG_OK, (e) => {
    const message = e['im-message']
})
NameDescriptionCallback Params
Im.CONNECT_OK成功连接socket时触发
Im.CONNECT_ERRsocket错误时触发
Im.CONNECT_CLOSEsocket关闭时触发{ reason: '' }
Im.RECEIVE_MSG_OK连接socket之后有新消息时触发{ 'im-message': { channelUuid, sendUuid, from, content } }

Methods

setImToken(token: string)

Update the token for an instance

myIm.setImToken('new token')

setImApiKey(apiKey: string)

Update the ApiKey for an instance

myIm.setImApiKey('new apiKey')

getUserInfo(address?: string)

Acquire a user's basic information

ParameterTypeDescriptionDefault
addressstringOptional. 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.

ParameterTypeDescriptionDefault
addressstringRequired. To specify a user's relationId or web3 address.
cursorstringThe cursor data returned by the last page(optional). If cursor is empty, then you are querying the first page.
limitnumberHow 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.

ParameterTypeDescriptionDefault
cursorstringThe cursor data returned by the last page(optional). If cursor is empty, then you are querying the first page.
limitnumberHow much data should be returned per page(optional). The upper limit is 100.20

follow(address: string)

To follow a user

ParameterTypeDescriptionDefault
addressstringRequired. To specify a user's relationId or web3 address.

unfollow(address: string)

To unfollower a user

ParameterTypeDescriptionDefault
addressstringRequired. To specify a user's relationId or web3 address.

sendMessage(data: sendMessageType)

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

ParameterTypeDescriptionDefault
contentstringcontent of the messageRequired. The text content.
channelUuidstringRequired. The uuid of the channel.-
toRelationIdstringOptional. The receiver's relationId-
sendUuidstringOptional. The uuid of the message
typestringOptional. The message type.TEXT

Note: channelUuid and toRelationId cannot be empty at the same time. If the sendUuidis 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:

ParameterTypeDescriptionDefault
keywordstringOptional. Descending order.The name of the channel. Fuzzy search is supported.
cursorstringThe cursor data returned by the last page(optional). If cursor is empty, then you are querying the first page.
limitnumberHow 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:

ParameterTypeDescriptionDefault
maxCreateAtnumberRequired. A timestamp based on milliseconds. It needs to be greater than the timestamp of the last message sent on the current page.-
channelUuidstringOptional. UUID of the channel.-
toRelationIdstringOptional. The receiver's toRelationId .-
limitnumberHow much data should be returned per page(optional).50

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

To create a new channel

ParameterTypeDescriptionDefault
namestringRequired. The name of the channel.
typestringGroup Chat Type, enumerated as: G-Regular Group Chat, P-p2p Group Chat
membersstring[]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.

ParameterTypeDescriptionDefault
channelUuidstringRequired. The uuid of the channel.-

channelDisband(channelUuid: string)

dismiss a channel

ParameterTypeDescriptionDefault
channelUuidstringRequired. The uuid of the channel.-

channelMemberLeave(channelUuid: string)

when the current user choose to leave a channel.

ParameterTypeDescriptionDefault
channelUuidstringRequired field. The UUID of the channel.-

to parse a message

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

import { messageParser } from "@relationlabs/im"

const msg: Message

const parsedMsg: ParsedMessage = messageParser(msg)

// to define types

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