Write your First mesibo Enabled Application - Javascript

Estimated reading time: 14 minutes

In this part, we will create a simple real-time app in Javascript.

Please go through the following prerequisites before you read further.

Prerequisites

  • Read the section Create Users to learn about creating an app in mesibo console and creating users & access tokens for your app.
  • Basic knowledge of using Javascript

First Javascript App

Now let’s quickly start coding:

Add mesibo API for javascript in your code:

<script type="text/javascript" src="https://api.mesibo.com/mesibo.js"></script>

Initialize mesibo

Before you send and receive real-time messages and calls, you need to initialize mesibo. The initialization involves the following steps:

  1. Use setAccessToken to set the user’s access token that you obtained while creating the user
  2. Set up mesibo to invoke your listener class using addListener
  3. Set up database to store sent and received messages using setDatabase (Optional)
  4. Start mesibo
var demo_user_token = 'xxxxxxxxxxxxxxxxxxxx';
/* App ID used to create a user token. */
var demo_appid = 'web';

var api = new Mesibo();

api.setListener(new MesiboListener());
api.setAppName(demo_app_id);
api.setCredentials(demo_user_token);
api.setDatabase("mesibo");

api.start();

Implement MesiboListener to receive messages and status in real-time.

function MesiboListener() {
}

MesiboListener.prototype.Mesibo_OnConnectionStatus = function(status, value) {
	console.log("TestNotify.prototype.Mesibo_OnConnectionStatus: "  + status);
}

MesiboListener.prototype.Mesibo_OnMessageStatus = function(m) {
	console.log("TestNotify.prototype.Mesibo_OnMessageStatus: from "  
			+ m.peer + " status: " + m.status);
}

MesiboListener.prototype.Mesibo_OnMessage = function(m, data) {
	console.log("TestNotify.prototype.Mesibo_OnMessage: from "  + m.peer);
}

That’s it - you are now ready to send and receive your first real-time message.

Testing your first application

  1. Load and Run Application.
  2. Mesibo_onConnectionStatus should cycle through various status information. Finally, you should receive status=1 which indicates that your app is successfully connected to the mesibo real-time server and ready to send and receive real-time messages.
  3. Since we do not have any other users right now, we will use mesibo console to send a test message. In a later section, we will learn how to send messages from the app itself.
    • Go to Console ->Application->Users. You should see the user you have created.
    • Go to user details by clicking the Edit button. Scroll down, you will see a section to Message User
    • Enter 1000 (or anything) in the From field, check the Create This User checkbox, type the message and click on Send.
  4. You will instantly receive this message in your mobile app in the Mesibo_onMessage listener.

Sending and Receiving Messages

In the previous section, we have used mesibo console to send a message. Now we will quickly learn how to send messages from the app itself. To send messages, we will use sendMessage real-time API for which we will need destination user, message-id, and the message itself.

Invoke the following function anywhere from your code to send a text message. In a later section, we will learn how to send rich messages.

function sendTextMessage(to, message) {
	var p = {};
       	p.peer = to;
	p.flag = MESIBO_FLAG_DEFAULT;
	var id = parseInt(Math.random()*10000);
	api.sendMessage(p, id, message);
}

That’s it! Try it out by creating two instances of the app and send messages to each other by using the above function.

Once you send a message, the recipient will receive the message through Mesibo_OnMessage. mesibo will inform the sender of the message about the status of the message - sent, delivered, or read through the listener Mesibo_onMessageStatus.

Voice and Video Calls

mesibo allows you to enable peer-to-peer HD video and voice calls between your users in just a few lines of code. As with messaging, mesibo video and voice calls are encrypted and hence secure. mesibo does not bill any additional amount for the voice or video call API.

Making and receiving voice & video calls with mesibo is simple. You only need to initialize MesiboCall once using just two lines of code! Then, mesibo will automatically handle incoming calls. For outgoing calls, you can invoke call API as required.

You can use mesibo voice and video calls as it is. But, if you wish, you can customize it to your needs. For example, you can customize the call screen UI, filter incoming calls, etc. Refer to Call API Reference to learn more.

To make a voice call using mesibo Javascript SDK add an <audio> HTML element.

<audio id="audioPlayer" autoplay="autoplay" controls="controls" style="visibility:hidden; height:5px;"></audio>

Then, call the method setupVoiceCall and pass the id of your <audio> element. Place a call to the destination user using the call method.

//initialize mesibo API
//api is the initialized mesibo api object
...

api.setupVoiceCall("audioPlayer");
api.call("123"); //Make a voice call to user with address "123"

To make a video call using mesibo Javascript SDK add <video> HTML elements.

<div class="row" style="background-color: #f1f1f1;">
	<div class="col-6" style="padding: 10px;">
		<video id="localVideo" playsinline autoplay muted></video>
	</div>
	<div class="col-6" style="padding: 10px;">
		<video id="remoteVideo" playsinline autoplay></video>
	</div>
</div>

localVideo element to display your video(From your WebCam), remoteVideo element to display destination video.

Then, call the method setupVideoCall and pass the ids of your <video> elements you need to display: your local video and remote video. Place a call to the destination user using the call method.

//initialize mesibo API
//api is the initialized mesibo api object
...

api.setupVideoCall("localVideo", "remoteVideo", true);
api.call("123"); //Make a video call to user with address "123"

To handle incoming calls, implement Mesibo_OnCall as follows:

DemoNotify.prototype.Mesibo_OnCall = function(callid, from, video) {
	console.log("Mesibo_onCall: " + (video?"Video":"Voice") + " call from: " + from);
	if(video)
		this.api.setupVideoCall("localVideo", "remoteVideo", true);
	else
		this.api.setupVoiceCall("audioPlayer");
	
	// Show Incoming Call Screen
	var s = document.getElementById("ansBody");
	if(s)
		s.innerText = "Incoming " + (video?"Video":"Voice") + " call from: " + from;

	$('#answerModal').modal({ show: true });
}

In the first app tutorial we have now learned about two of the most fundamental mesibo APIs - the messaging API and call API. In the upcoming sections, we will learn more about various mesibo APIs and features that you can use. Such as group messaging, group calls, reading stored messages, UI Modules, etc.

Group Messaging and Group Calls

In this section, we will learn about group messaging and group calls(conferencing). The group messaging API is similar to the one-to-one messaging API and the group call API is similar to the one-to-one voice and video call API.

Group Messaging

You can invoke one of the messaging APIs to send a group message, just like the way you used the one-to-one messaging API. Here, instead of the user’s address you need to specify the groupid. To learn about creating a group and getting the groupid refer to Group Management APIs.

For example, here is an example of how you use sendMessage to send a message to a group. Let’s say you have created a group with the group-id 96568. Then, you use the same function that you use for sending a one-to-one message, where instead of setting the peer to the user address, now you set it to the group -id.

Using Javascript,

var p = {};
p.groupid = 96568;
var id = parseInt(Math.random()*10000);
var string = "This is a group message";
api.sendMessage(p, id, message);	

A message sent will be delivered to all members of the group and you will get the message delivery and read status for each user.

Group Calls (Conferencing)

mesibo group calling simply extends the existing features of group messaging with additional permissions and control, for example, room resolution, talk detection, who can publish and who can video, voice+video or voice only, etc. Your existing groups will now have additional conferencing settings.

To add mesibo Group Calling to your app, here is an overview of steps to follow:

  1. Have a group of members with required permissions
  2. Create a group call object with groupCall()
  3. To publish your stream to the group, get a Participant object using createPublisher and make a call()
  4. To subscribe to other users’ streams, get their call object in MesiboGroupCall_OnPublisher and make a call()
  5. Display the stream using setVideoView

For detailed documentation and examples for conferencing refer to Mesibo Conferencing Docs and download the example source code for conferencing from Github

You can also try a live demo of a Zoom-like conferencing app, Mesibo Live built using mesibo conferencing and streaming API. The source code of the app is available on Github. You can download it, modify or rebrand it, and integrate it into your app or website.

Reading Messages

mesibo provides a set of APIs deal with stored messages in the database and sending read receipts. A read receipt is an acknowledgment that the user has read the message.

To read stored messages from the database, you need to create a read session and set the criteria to read messages; for example,

  • read all messages
  • read messages from a sender
  • read messages for a particular group
  • read messages matching a search query etc.

The read session you create filters the messages in the database based on the criteria provided and gives the resulting list of messages to you.

Reading Modes

There are two modes of operation:

  • Read Messages and call logs. This mode is enabled by default
  • Read Summary (active conversations), read the latest message from each user and group. This allows you to get a snapshot of all the communicating users and groups. You can then create another read session to read messages for any of those users or groups.

Reading Order

Once you set a read session, you can start reading messages by calling read API. You can read messages in the first-in-first-out (FIFO) mode or the last-in-first-out (LIFO) mode. In the first-in-first-out model, the oldest messages are read first. By default, the first-in-first-out mode is disabled.

Read Receipts

You can enable the automatic sending of read-receipts every time you read a message. This can be achieved by enabling a read-receipt for the read session. On reading or receiving a message, read receipts will be automatically sent if

  • The app is set to be in the foreground
  • Sending Read Receipt is enabled for the reading session, AND
  • Read receipt requested by the sender, AND
  • A new real-time or database message matches the read session.

A call to read will return the number of messages read. You can call read on demand. For example, in the case of a messaging app, you only need to show the latest messages on the screen initially. So, first, you can call read(10) to load the last 10 messages. As the user scrolls up the chat history, you can call read again. All subsequent calls to read will read older messages.

The way read works in the mesibo Javascript API differs slightly from Android/iOS APIs. This is mainly because of how the local database(IndexedDB) operates. In Android/iOS read messages are received in the onMessage callback. In Javascript, you get the number of messages through the read handler that you set while creating the read session.

Here is an example in Javascript, to read all messages of an example user, with the address testuser. Replace it with the user address you have. Set the groupid parameter to 0, while reading user messages.

var messageSession = api.readDbSession('testuser', 0, null,
    function on_read(count) {
	console.log("Read "+ count + " number of messages");
        var messages = messageSession.getMessages();
});

messageSession.enableReadReceipt(true);
messageSession.read(100);

To read message summary,

var summarySession = api.readDbSession(null, 0, null, 
    function on_read(count) {
	var messages = summarySession.getMessages();
	//Here you will get a message summary which contains a list of each user who was sent/recieved message, their last message, etc.
});
summarySession.enableSummary(true);
summarySession.read(100);

Here is an example in Javascript, to read all messages of a group, with the groupid 98765. Replace it with the groupid you have. Set the peer parameter to null, while reading group messages.

var groupSession = api.readDbSession(null, 98765, null,
    function on_read(count) {
        var messages = groupSession.getMessages();
});

groupSession.enableReadReceipt(true);
groupSession.read(100);

First mesibo Application - C/C++ >>

mesibo, js, javascript