preface

Recently, the Vue+Element packaging continued to improve, and then started to work on the instant messaging.

Before the old code is rongyun 2. X version, now 4.x, naturally to update, rongyun 4. X change is quite big, a lot of APIS have been changed, but relatively speaking is relatively simple to use.

Since there is no prototype map, I directly design to do coding, and I still keep smiling for this demand to play by myself. (This should be to my aesthetic affirmation!) First the whole sample diagram is as follows

The height is lonely, dance clear shadow.

Now let’s get down to business

Analyze requirements

The project is a background management project of social APP. In the project, there is a module about chat room, which links to the chat hall in the APP. If a user posts undesirable information, the user can be banned and the announcement can also be issued.

task

  1. Obtain the token and link to the cloud
  2. Get historical messages and simulate chat display
  3. Send the message, this is done by the back end, I send the message and I request the interface
  4. You can gag users, and this is done uniformly by the back end

The melting of cloud

The instant messaging service provided by Rongyun does not need to establish a parallel user system outside the App, and does not need to synchronize the user information under the App to Rongyun. It does not affect the existing system architecture and account system of the App, and can achieve perfect integration with the existing business system.

Compatible with that

Chrome Firefox Safari IE Edge QQ browser Wechat browser Android
9 +

Import the SDK

4. X refactorings to Typescript, provides Typescript users with friendly typing support, and recommends that developers use Typescript for business development to improve code robustness and maintainability.

NPM Introduction (recommended)

  1. Depend on the installation
npm install @rongcloud/imlib-v4
Copy the code
  1. Code integration
/ / not ESModule
const RongIMLib = require('@rongcloud/imlib-v4')
// ESModule
import * as RongIMLib from '@rongcloud/imlib-v4'
Copy the code

Introduced the CDN

  • inindex.html
<script src="https://cdn.ronghub.com/RongIMLib-4.3.latest.js"></script>
Copy the code

App Key

The App Key is a necessary condition for the development of the im function using IMLib. It is also the unique identifier of the application. Before using IMLib integration, please register and obtain the developer’s exclusive App Key through The New Window.

Messages between different users can be exchanged only when the App Key is the same.

Initialize the

All the capabilities provided by IMLib are based on the instance objects obtained after IMLib is initialized. Therefore, before using the capabilities of IMLib, you must first call the IMLib initialization interface and ensure that the interface is invoked only once in the entire application life cycle.

// Initialize the application to get the RongIMLib instance object. Make sure this process is performed only once
const im = RongIMLib.init({ appkey: '<Your-App-Key>' });
Copy the code

In all subsequent code examples, im refers to the RongIMLib instance object obtained through initialization

Set up to monitor

After initialization, add an event listener to the IM object before setting up a connection to obtain timely event notifications.

// Add event listener
im.watch({
  // Listen for session list change events
  conversation (event) {
    / / the putative getExistedConversationList method, in order to obtain a list of the current existing session data
    const conversationList = getExistedConversationList()
    // The list of changed sessions
    const updatedConversationList = event.updatedConversationList;
    // Calculate the latest list of sessions using im.conversation.merge
    const latestConversationList = im.Conversation.merge({ conversationList, updatedConversationList })
  },
  // Listen for message notifications
  message (event) {
    // The content of the new received message
    const message = event.message;
  },
  // Listen for IM connection status changes
  status (event) {
    console.log('connection status:', event.status);
  },
  // Monitor chat room KV data change
  chatroom (event) {
    /** * Chat room KV storage data update *@example* [* {* "key" : "name," * "value" : "I am a little happy," * "timestamp" : 1597591258338, * "chatroomId" : "z002," * "type" : 1 / / 1: Update (including modified and added), 2: Delete *}, *] */
    const updatedEntries = event.updatedEntries
  },
  expansion (event) {
    /** * Update the message extension data *@example { * expansion: { key: 'value' }, // set or update the extended value * messageUId: 'urit-urit-odmf-durr' // set or update the extended messageUId *} */
    const updatedExpansion = event.updatedExpansion;
    /** * Delete message extension data *@example {* deletedKeys: ['key1', 'key2'], // set or update the extended value * messageUId: 'urit-urit-odmf-durr' // set or update the extended messageUId *}* /
    const deletedExpansion = event.deletedExpansion;
});

Copy the code

Setting up an IM connection

The App Key is the unique identification of the application, and the Token is the unique identification of the user. It is the identity credential necessary for the user to connect to the Cloud IM service. Generally, the developer’s application Server invokes the Rongyun Server API to obtain the Token interface, and then the application Server delivers the Token to the application client.

My token is obtained from the back end, and then stored to the local, with the time to see expired, expired to obtain again. Equivalent to the front end interacting only partially.

  • Access token
    / / access token
    getIMToken() {
      getIMToken().then(res= > {
        var time = new Date().getTime()
        res.time = time
        // Save the token
        this.gobalToken = res
        var tokenStr = JSON.stringify(res)
        localStorage.setItem('token', tokenStr)
        // Initialize the melt cloud
        this.linkToRongs(res.data)
      })
    },
    // Check whether the token has expired
    isToken() {
      var now = new Date().getTime()
      // Obtain the last stored token
      var oldToken = JSON.parse(localStorage.getItem('token'))
      // The token obtained before judging
      if (oldToken) {
        var tokenTime = oldToken.time
        // Check whether the time has expired
        if (now - tokenTime > 29 * 24 * 60 * 60 * 1000) {
          this.getIMToken()
        } else {
          this.gobalToken = JSON.parse(localStorage.getItem('token'))
          this.linkToRongs(this.gobalToken.data)
          return}}this.getIMToken()
    }
Copy the code
  • Establish a connection
im.connect({ token: '<Your-Token>' }).then(user= > {
  console.log('Link successful, link user ID:', user.id);
}).catch(error= > {
  console.log('Link failed:', error.code, error.msg);
});
Copy the code

Obtaining the session list

The Web terminal does not provide persistent data storage. For this to take effect, developers need to enable the single group chat cloud storage function in the commercial IM edition. This function needs to be performed after the call to im.connect() has been made and the connection has been successfully established.

IMLib uses conversationType and targetId to identify the uniqueness of a session. The conversationType and targetId attributes are defined as follows:

  1. conversationTypeIdentifies the session type (e.g. single chat, group chat…) , its value isRongIMLib.CONVERSATION_TYPEConstant definition in
  2. targetIdId of the person or group that is talking to the local end:
  • whenconversationTypeThe value is rongimlib.conversation_type.PRIVATE, and targetId is the user Id of the other party
  • whenconversationTypeThe value is rongimlib.conversation_type.GROUP, and targetId is the GROUP Id
  • whenconversationTypeThe value is rongimlib.conversation_type.CHATROOM, and targetId is the CHATROOM Id
// Get the list of sessions
im.Conversation.getList().then(conversationList= > {
  console.log('Succeeded in obtaining session list', conversationList);
}).catch(error= > {
  console.log('Failed to get session list:', error.code, error.msg);
});

Copy the code

Send a message

This function needs to be performed after the call to im.connect() has been made and the connection has been successfully established. The IMLib built-in message type can be defined by using rongimlib. MESSAGE_TYPE

// Get an abstract instance of the specified session, based on which operations on the session are performed
const conversation = im.Conversation.get({
  // targetId
  targetId: '<TargetId>'./ / session types: RongIMLib. CONVERSATION_TYPE. PRIVATE | RongIMLib. CONVERSATION_TYPE. GROUP
  type: '<Conversation-Type>'
});
// Send a message to the session
conversation.send({
  // Rongimlib. MESSAGE_TYPE is a built-in message type constant defined within IMLib
  messageType: RongIMLib.MESSAGE_TYPE.TEXT, // 'RC:TxtMsg'
  // Message content
  content: {
    content: 'Hello RongCloud' // The text content
  }
}).then(function(message){
  console.log('Text message sent successfully', message);
}).catch(error= > {
  console.log('Failed to send text message', error.code, error.msg);
});

Copy the code

Receives the message

When the local end is the recipient of the message, the received message is thrown to the business layer through the message listener registered with im.watch(). For details, refer to the above section on setting listening

Get historical messages

The Web terminal does not provide persistent data storage. For this to take effect, developers need to enable the single group chat cloud storage function in the commercial IM edition. This function needs to be performed after the call to im.connect() has been made and the connection has been successfully established.

const conversation = im.Conversation.get({
  targetId: '<TargetId>'.type: '<Conversation-Type>'
});
const option = {
  // Get the timestamp of the history message. The default value is 0, indicating that the timestamp is obtained from the current time
  timestamp: +new Date(),
  The value ranges from 1 to 20. The default value is 20
  count: 20}; conversation.getMessages(option).then(result= > {
  const list = result.list;       // Get the list of messages
  const hasMore = result.hasMore; // Whether historical messages are still available
  console.log('History message obtained successfully', list, hasMore);
}).catch(error= > {
  console.log('Failed to send text message', error.code, error.msg);
});

Copy the code

disconnect

The current user is disconnected. After the connection is disconnected, the user cannot receive messages, send messages, obtain historical messages, or obtain the session list. After connecting to the cloud, the system receives the offline messages. The offline messages are saved for 7 days by default.

im.disconnect().then(() = > console.log('Disconnected successfully'));
Copy the code

Practical use

The token gets it and walks forward

created() {
    this.isToken()
 }
 methods: {/ / access token
    getIMToken() {
      getIMToken().then(res= > {
        var time = new Date().getTime()
        res.time = time
        // Save the token
        this.gobalToken = res
        var tokenStr = JSON.stringify(res)
        localStorage.setItem('token', tokenStr)
        // Initialize the melt cloud
        this.linkToRongs(res.data)
      })
    },
    // Check whether the token has expired
    isToken() {
      var now = new Date().getTime()
      // Obtain the last stored token
      var oldToken = JSON.parse(localStorage.getItem('token'))
      // The token obtained before judging
      if (oldToken) {
        var tokenTime = oldToken.time
        // Check whether the time has expired
        if (now - tokenTime > 29 * 24 * 60 * 60 * 1000) {
          this.getIMToken()
        } else {
          this.gobalToken = JSON.parse(localStorage.getItem('token'))
          this.linkToRongs(this.gobalToken.data)
          return}}this.getIMToken()
    },
}
Copy the code

Init init. Good to hear you

The general test server has one Appkey, and the official server has one Appkey. This Appkey needs to be applied by yourself

 // Link to the cloud
 linkToRongs(token) {
    const that = this
    let RongClientKey
    if (process.env.VUE_APP_BASE_API2 === ' ') {/ / test
    RongClientKey = '4215151sadasas'
    } else {/ / formal clothing
    RongClientKey = 'adsada12asda1a'
    }
    // Initialize the application to get the RongIMLib instance object. Make sure this process is performed only once
    // eslint-disable-next-line no-undef
    that.rongyun = RongIMLib.init({ appkey: RongClientKey })
}
Copy the code

Listen first, link later

After initialization, add an event listener to the IM object before setting up a connection to obtain timely event notifications.

 // Link to the cloud
 linkToRongs(token) {
    const that = this
    let RongClientKey
    if (process.env.VUE_APP_BASE_API2 === ' ') {/ / test
    RongClientKey = '4215151sadasas'
    } else {/ / formal clothing
    RongClientKey = 'adsada12asda1a'
    }
    // Initialize the application to get the RongIMLib instance object. Make sure this process is performed only once
    // eslint-disable-next-line no-undef
    that.rongyun = RongIMLib.init({ appkey: RongClientKey })
    const im = that.rongyun
    // Add event listener
      im.watch({
        // Listen for session list change events
        conversation(event) {
          / / the putative getExistedConversationList method, in order to obtain a list of the current existing session data
          const conversationList = that.getExistedConversationList(im)
          // The list of changed sessions
          const updatedConversationList = event.updatedConversationList
          // Calculate the latest list of sessions using im.conversation.merge
          const latestConversationList = im.Conversation.merge({ conversationList, updatedConversationList })
          console.log(latestConversationList)
        },
        // Listen for message notifications
        message(event) {
          // This is where the initialization messages are
          // The content of the new received message
          const message = event.message
          console.log(message)
        },
        // Listen for IM connection status changes
        status(event) {
          console.log('connection status:', event.status)
        },
        // Monitor chat room KV data change
        chatroom(event) {
          const updatedEntries = event.updatedEntries
          console.log('Chat room KV store data update', updatedEntries)
        }
      })
}
Copy the code

Link rong cloud first with key, drive straight into no one to block

 // Link to the cloud
 linkToRongs(token) {
    const that = this
    let RongClientKey
    if (process.env.VUE_APP_BASE_API2 === ' ') {/ / test
    RongClientKey = '4215151sadasas'
    } else {/ / formal clothing
    RongClientKey = 'adsada12asda1a'
    }
    // Initialize the application to get the RongIMLib instance object. Make sure this process is performed only once
    // eslint-disable-next-line no-undef
    that.rongyun = RongIMLib.init({ appkey: RongClientKey })
    const im = that.rongyun
    // Add event listener
      im.watch({
        // Listen for session list change events
        conversation(event) {
          / / the putative getExistedConversationList method, in order to obtain a list of the current existing session data
          const conversationList = that.getExistedConversationList(im)
          // The list of changed sessions
          const updatedConversationList = event.updatedConversationList
          // Calculate the latest list of sessions using im.conversation.merge
          const latestConversationList = im.Conversation.merge({ conversationList, updatedConversationList })
          console.log(latestConversationList)
        },
        // Listen for message notifications
        message(event) {
          // This is where the initialization messages are
          // The content of the new received message
          const message = event.message
          console.log(message)
        },
        // Listen for IM connection status changes
        status(event) {
          console.log('connection status:', event.status)
        },
        // Monitor chat room KV data change
        chatroom(event) {
          const updatedEntries = event.updatedEntries
          console.log('Chat room KV store data update', updatedEntries)
        }
      })
      // Establish an IM connection
      const chatRoomId = '627865222'
      var count = 50 / / the number of
      im.connect({ token: token }).then(user= > {
        this.$message.success('Succeeded in joining chat room')
        console.log('Link successful, link user ID:', user.id)
        var chatRoom = im.ChatRoom.get({
          id: chatRoomId
        })
        chatRoom.join({
          count: count // After entering, automatically pull 20 chat room latest news
        }).then(function() {
          console.log('Succeeded in joining chat room')
          chatRoom.getInfo().then(function(result) {
            var userCount = result.userCount
            var user = that.uniq(that.messageList)
            // Brush the user
            user.map(item= > {
              that.list.push(item.user)
            })
            that.num = userCount
          })
        })
      }).catch(error= > {
        this.$message.success('Failed to join the chat room')
        console.log('Link failed:', error.code, error.msg)
      })
}
Copy the code

The last step is the most important. Exit the chat promptly

When switching pages, be sure to exit the chat hall, otherwise the next time to join the chat hall can not get the previous message. Of course, you can also get the history message, I tried to get the history message has been wrong, so I choose to open the page to join, after the end of the leave. (Will stay connected if you don’t quit)

destroyed() {
    var chatRoom = this.rongyun.ChatRoom.get({
      id: 'Chat room ID'
    })
    chatRoom.quit().then(function() {
      console.log('Exit the chat room successfully')})}Copy the code

At the end

The instant messaging part is fun to do, there are always some unexpected things that happen.

Life is full of surprises, and so is the world of code.

Finally, I put the source code on Github

Official document of Rongyun

Write in the last

I am Liangcheng A, a front end, who loves technology and life.

I’m glad to meet you.

If you want to learn more, please click here and look forward to your little ⭐⭐

  • Feel free to correct any mistakes in the comments section, and if this post helped you, feel free to like and follow 😊

  • This article was originally published in Nuggets and cannot be reproduced without permission at 💌