undefined

Messaging

ConnectyCube Chat (messaging) API is built on top of Real-time(XMPP) protocol. In order to use it you need to setup real-time connection with ConnectyCube Chat server and use it to exchange data.

By default Real-time Chat works over secure TLS connection.

Code samples

There are ready-to-go FREE code samples to help you better understand how to integrate messaging capabilities in your apps:

Connect to chat

var userCredentials = {
    userId: 4448514,
    password: 'awesomepwd'
};

ConnectyCube.chat.connect(
    userCredentials,
    function(error, contactList) {}
);

Disconnect

ConnectyCube.chat.disconnect();

ConnectyCube.chat.onDisconnectedListener = onDisconnectedListener;

function onDisconnectedListener() {}

Reconnection

The SDK reconnects automatically when connection to Chat server is lost.

The following 2 callbacks are used to track the state of connection:

ConnectyCube.chat.onDisconnectedListener = onDisconnectedListener;
ConnectyCube.chat.onReconnectListener = onReconnectListener;

function onDisconnectedListener() {}

function onReconnectListener() {}

Conversations

All chats between users are organized in conversations. The are 3 types of conversations:

  • 1-1 chat - a conversation between 2 users.
  • group chat - a conversation between specified list of users.
  • public group chat - an open conversation. Any user from your app can chat there.

You need to create a new conversation and then use it to chat with other users. You also can obtain a list of your existing conversations.

Create new conversation

Create 1-1 chat

You need to pass type: 3 and an id of an opponent you want to create a chat with:

var params = {
    type: 3,
    occupants_ids: [56]
};

ConnectyCube.chat.dialog.create(params, function(error, conversation) {});

Create group chat

You need to pass type: 2 and ids of opponents you want to create a chat with:

var params = {
    type: 2,
    occupants_ids: [56, 98, 34],
    name: 'Hawaii relax team'
};

ConnectyCube.chat.dialog.create(params, function(error, conversation) {});

Create public group chat

It's possible to create a public group chat, so any user from you application can join it. There is no a list with occupants, this chat is just open for everybody.

You need to pass type: 3 and ids of opponents you want to create a chat with:

var params = {
    type: 1,
    name: 'Blockchain trends'
};

ConnectyCube.chat.dialog.create(params, function(error, conversation) {});

List conversations

It's common to request all your conversations on every app login:

var filters = {};

ConnectyCube.chat.dialog.list(filters, function(error, dialogs) {});

If you want to retrieve only conversations updated after some specific date time, you can use updated_at[gt] filter. This is useful if you cache conversations somehow and do not want to obtain the whole list of your conversations on every app start.

Update conversation

User can update group chat name, photo or add/remove occupants:

var dialogId = '5356c64ab35c12bd3b108a41';

var toUpdateParams = {
    name: 'Tesla club'
};

ConnectyCube.chat.dialog.update(dialogId, toUpdateParams, function(error, dialog) {});

Add/Remove occupants

To add more occupants use push_all operator. To remove yourself from the conversation use pull_all operator:

var dialogId = '5356c64ab35c12bd3b108a41';

var toUpdateParams = {
    push_all: { occupants_ids: [97, 789] }
};

ConnectyCube.chat.dialog.update(dialogId, toUpdateParams, function(error, dialog) {});

Important note: Only group chat owner can remove other users from group chat.

Remove conversation

The following snippet is used to delete a conversation:

var dialogId = '5356c64ab35c12bd3b108a41';

ConnectyCube.chat.dialog.delete([dialogId], function(error) {});

This request will remove this conversation for current user, but other users still will be able to chat there. Only group chat owner can remove the group conversation for all users.

You can also delete multiple conversations in a single request.

Chat history

Every chat conversation stores its chat history which you can retrieve:

var dialogId = '5356c64ab35c12bd3b108a41';

var filter = { chat_dialog_id: dialogId, sort_desc: 'date_sent', limit: 100, skip: 0 };

ConnectyCube.chat.message.list(params, function(error, messages) {});

If you want to retrieve chat messages that were sent after or before specific date time only, you can use date_sent[gt] or date_sent[lt] filter. This is useful if you implement pagination for loading messages in your app.

Send/Receive chat messages

1-1 chat

var dialog = ...;

var message = {
  type: dialog.type === 3 ? 'chat' : 'groupchat',
  body: "How are you today?",
  extension: {
    save_to_history: 1,
    dialog_id: dialog._id
  },
  markable: 1
};

var opponentId = 78;
message.id = ConnectyCube.chat.send(opponentId, message);

...

ConnectyCube.chat.onMessageListener = onMessage;

function onMessage(userId, message) {

}

Group chat

Before you start chatting in a group conversation, you need to join it by calling join function:

var dialog = ...;

ConnectyCube.chat.muc.join(dialog._id, function(error) {

});

Then you are able to send/receive messages:

var message = {
  type: dialog.type === 3 ? 'chat' : 'groupchat',
  body: "How are you today?",
  extension: {
    save_to_history: 1,
    dialog_id: dialog._id
  },
  markable: 1
};

message.id = ConnectyCube.chat.send(dialog._id, message);

...

ConnectyCube.chat.onMessageListener = onMessage;

function onMessage(userId, message) {

}

When it's done you can leave the group conversation by calling leave function:

ConnectyCube.chat.muc.leave(dialog._id, function(error) {});

'Sent' status

There is a 'sent' status to ensure that message is delivered to the server.

In order to use the feature you need to enable it when you pass config in ConnectyCube.init:

chat: {
    streamManagement: {
        enable: true;
    }
}

The following callback is used to track it:

ConnectyCube.chat.onSentMessageCallback = function(messageLost, messageSent) {};

'Delivered' status

The following callback is used to track the 'delivered' status:

ConnectyCube.chat.onDeliveredStatusListener = function(messageId, dialogId, userId) {};

The SDK sends the 'delivered' status automatically when the message is received by the recipient. This is controlled by markable: 1 parameter when you send a message. If markable is 0 or omitted, then you can send the delivered status manually:

var params = {
    messageId: '557f1f22bcf86cd784439022',
    userId: 21,
    dialogId: '5356c64ab35c12bd3b108a41'
};

ConnectyCube.chat.sendDeliveredStatus(params);

'Read' status

Send the 'read' status:

var params = {
  messageId: "557f1f22bcf86cd784439022",
  userId: 21,
  dialogId: "5356c64ab35c12bd3b108a41"
};

ConnectyCube.chat.sendReadStatus(params);

...

ConnectyCube.chat.onReadStatusListener = function(messageId, dialogId, userId){

}

'Is typing' status

The following 'typing' notifications are supported:

  • typing: The user is composing a message. The user is actively interacting with a message input interface specific to this chat session (e.g., by typing in the input area of a chat window)
  • stopped: The user had been composing but now has stopped. The user has been composing but has not interacted with the message input interface for a short period of time (e.g., 30 seconds)

Send the 'is typing' status:

var opponentId = 78; // for 1-1 chats
// var conversationJid = ..; // for group chat

ConnectyCube.chat.sendIsTypingStatus(opponentId);

ConnectyCube.chat.sendIsStopTypingStatus(opponentId);

...

ConnectyCube.chat.onMessageTypingListener = function(isTyping, userId, dialogId) {

}

Attachments

Chat attachments are supported with the cloud storage API. In order to send a chat attachment you need to upload the file to ConnectyCube cloud storage and obtain a link to the file (file UID). Then you need to include this UID into chat message and send it.

// for example, a file from HTML form input field
var inputFile = $('input[type=file]')[0].files[0];

var fileParams = { name: inputFile.name, file: inputFile, type: inputFile.type, size: inputFile.size, public: false };
ConnectyCube.storage.createAndUpload(fileParams, function(error, result) {
    if (!error) {
        var fileUID = result.uid;

        // prepare a message
        var message = {
            type: dialog.type === 3 ? 'chat' : 'groupchat',
            body: 'attachment',
            extension: {
                save_to_history: 1,
                dialog_id: dialog._id,
                attachments: [{ uid: fileUID, type: 'photo' }]
            }
        };

        // send the message
        // ...
    }
});

If you are running Node.js environment, the following code snippet can be used to access a file:

const fs = require('fs');

var imagePath = __dirname + '/dog.jpg';

fs.stat(imagePath, function(error, stats) {
    fs.readFile(srcIMG, function(error, data) {
        if (error) {
            throw error;
        } else {
            var fileParams = {
                file: data,
                name: 'image.jpg',
                type: 'image/jpeg',
                size: stats.size
            };

            // upload
            // ...
        }
    });
});

The same flow is supported on the receiver's side. When you receive a message, you need to get the file UID and then download the file from the cloud storage.

ConnectyCube.chat.onMessageListener = function(userId, message) {
    if (message.extension.hasOwnProperty('attachments')) {
        if (message.extension.attachments.length > 0) {
            var fileUID = message.extension.attachments[0].uid;
            var fileUrl = ConnectyCube.storage.privateUrl(fileUID);
            var imageHTML = "<img src='" + fileUrl + "' alt='photo'/>";
        }
    }
};

Delete chat messages

The following snippet is used to remove chat message:

var messageIds = ['55fd42369575c12c2e234c64'].join(',');
var params = {};
ConnectyCube.chat.message.delete(messageIds, params, function(error, result) {});

This request will remove the messages from current user history only, without affecting the history of other users.

Unread messages count

You can request total unread messages count and unread count for particular conversation:

var params = { dialogs_ids: ['5356c64ab35c12bd3b108a41'] };

ConnectyCube.chat.message.unreadCount(params, function(error, result) {});

Chat alerts

When you send a chat message and the recipient/recipients is offline, then automatic push notification will be fired.

In order to receive push notifications you need to subscribe for it. Please refer to Push Notifications guide.

To configure push template which users receive - go to Dashboard Console, Chat Alerts page

Note that currently push notifications are supported on mobile environment only.

Contact list

The Contact List API is rather straightforward. User A sends a request to become "friends" with user B. User B accepts the friend request. And now user A and B appear in each other's roster.

Access to the Contact list

You can access the contact list on your login to chat - the contact list object will be returned in callback.

Also, the following function gives you an access to contact list:

ConnectyCube.chat.contactlist.get(function(contactlist) {});

Add user to your contact list

To add a user to the contact list use the following method:

var userId = 34;
ConnectyCube.chat.contactlist.add(userId, function() {});

Note

Maximum number of contacts is 300.

Other user will receive a request to be added to the contact list - the onSubscribeListener callback will be called:

ConnectyCube.chat.onSubscribeListener = function(userId) {};

Confirm the contact request

To confirm the request use the following method:

ConnectyCube.chat.contactlist.confirm(userId, function() {});

A user will be informed that you have accepted the contact request by onConfirmSubscribeListener callback:

ConnectyCube.chat.onConfirmSubscribeListener = function(userId) {};

Reject the contact request

To reject the request use the following method:

ConnectyCube.chat.contactlist.reject(userId, function() {});

A user will be informed that you have declined the contact request by onRejectSubscribeListener callback:

ConnectyCube.chat.onRejectSubscribeListener = function(userId) {};

Remove user from the contact list

To remove a previously added user from the contact list use the following method:

ConnectyCube.chat.contactlist.remove(userId, function() {});

Contact list updates

You can also track contact list updates in real time by using delegates:

ConnectyCube.chat.onContactListListener = function(userId, type) {
    // type - if a user left the chat, type will be 'unavailable'.
    // Otherwise - 'available'.
};

Privacy (black) list

Privacy list API allows enabling or disabling communication with other users in a chat. You can create, modify, or delete privacy lists, define a default list.

The user can have multiple privacy lists, but only one can be active.

Create privacy list

A privacy list must have at least one element in order to be created.

You can choose a type of blocked logic. There are 2 types:

  • Block in one way. When you blocked a user, but you can send messages to him.
  • Block in two ways. When you blocked a user and you also can't send messages to him.
var users = [
    { user_id: 34, action: 'deny' },
    { user_id: 48, action: 'deny', mutualBlock: true }, // it means you can't write to user
    { user_id: 18, action: 'allow' }
];
var list = { name: 'myList', items: users };

ConnectyCube.chat.privacylist.create(list, function(error) {});

In order to be used the privacy list should be not only set, but also activated(set as default).

Activate privacy list

In order to activate rules from a privacy list you should set it as default:

ConnectyCube.chat.privacylist.setAsDefault('myList', function(error) {});

Update privacy list

There is a rule you should follow to update a privacy list:

  • If you want to update or set new privacy list instead of current one, you should decline current default list first.
ConnectyCube.chat.privacylist.setAsDefault(null, function(error) {
    if (!error) {
        var users = [{ user_id: 34, action: 'allow' }];
        var list = { name: 'myList', items: users };

        ConnectyCube.chat.privacylist.update(list, function(error) {
            if (!error) {
                ConnectyCube.chat.privacylist.setAsDefault('myList', function(error) {});
            }
        });
    }
});

Retrieve privacy list names

To get a list of all your privacy lists' names use the following request:

ConnectyCube.chat.privacylist.getNames(function(error, response) {
    if (!error) {
        var names = response.names;
    }
});

Retrieve privacy list with name

To get the privacy list by name you should use the following method:

ConnectyCube.chat.privacylist.getList('myList', function(error, response) {
    if (!error) {
        var name = response.name;
        var items = response.items;
    }
});

Remove privacy list

To delete a list you can call a method below or you can edit a list and set items to nil.

ConnectyCube.chat.privacylist.delete('myList', function(error) {});

Blocked user attempts to communicate with user

Blocked users will be receiving an error when trying to chat with a user in a 1-1 chat and will be receiving nothing in a group chat:

ConnectyCube.chat.onMessageErrorListener = function(messageId, error) {};