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.

Get started with SDK

Follow the Getting Started guide on how to connect ConnectyCube SDK and start building your first app.

Code samples

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

  • Chat code sample for React Native src code
  • Chat code sample for NativeScript src code
  • Chat code sample for Cordova/PhoneGap How To guide
  • Chat code sample for browser - request

Connect to chat

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

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

A user’s password for chat connection depends on what type of user authentication was applied for this particular user:

  • Standard login + password authentication: password is the same
  • Facebook / Twitter / Custom identity authentication: password is the same as ConnectyCube session token

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() {}

Dialogs

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

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

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

Create new dialog

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, dialog) {});

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, dialog) {});

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: 1 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, dialog) {});

List dialogs

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

var filters = {};

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

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

Update dialog

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 dialog 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 dialog

The following snippet is used to delete a dialog:

var dialogId = '5356c64ab35c12bd3b108a41';

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

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

You can also delete multiple dialogs in a single request.

Subscribe to public dialog

In order to be able to chat in public dialog, you need to subscribe to it:

const dialogId = '5356c64ab35c12bd3b108a41';

ConnectyCube.chat.dialog.subscribeToPublic(dialogId, (error, dialog) => {

});

Unsubscribe from public dialog

const dialogId = '5356c64ab35c12bd3b108a41';

ConnectyCube.chat.dialog.unsubscribeFromPublic(dialogId, (error) => {

});

Retrieve public dialog occupants

A public chat dialog can have many occupants. There is a separated API to retrieve a list of public dialog occupants:

const dialogId = '5356c64ab35c12bd3b108a41';

ConnectyCube.chat.dialog.getPublicOccupants(dialogId, (error, result) => {
    // result.items
});

Add / Remove admins

Options to add or remove admins from the dialog can be done by Super admin (dialog's creator) only. Options are supported in group chat, public or broadcast.

Up to 5 admins can be added to chat.

const dialogId = '5356c64ab35c12bd3b108a41';
const adminsUsersIds = [45, 89];

ConnectyCube.chat.dialog.addAdmins(dialogId, adminsUsersIds, (error, dialog) => {

});
const dialogId = '5356c64ab35c12bd3b108a41';
const adminsUsersIds = [45, 89];

ConnectyCube.chat.dialog.removeAdmins(dialogId, adminsUsersIds, (error, dialog) => {

});

Update notifications settings

A user can turn on/off push notifications for offline messages in a dialog. By default push notification are turned ON, so offline user receives push notifications for new messages in a chat.

const dialogId = '5356c64ab35c12bd3b108a41';
const enabled = false;

ConnectyCube.chat.dialog.updateNotificationsSettings(dialogId, enabled, (error, result) => {

});

Get notifications settings

Check a status of notifications setting - either it is ON or OFF for a particular chat.

Available responses: 1 - enabled, 0 - disabled.

const dialogId = '5356c64ab35c12bd3b108a41';

ConnectyCube.chat.dialog.getNotificationsSettings(dialogId, (error, result) => {

});

Chat history

Every chat dialog 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 dialog, 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 dialog 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 dialogJid = ..; // 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 dialog:

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

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

The following API is used to search for messages and chat dialogs:

var params = { ... };

ConnectyCube.chat.search(params, function(error, result) {

});

Please refer to Global search parameters for more info on how to form search params.

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.

Mark a client as Active/Inactive

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

Sometimes a client app can be in a background mode, but still online. In this case it's useful to let server know that a user wants to receive push noificattions while still is connected to chat.

For this particular case we have 2 handy methods: 'markInactive' and 'markActive':

ConnectyCube.chat.markInactive()
ConnectyCube.chat.markActive()

The common use case for these APIs is to call 'markInactive' when an app goes to background mode and to call 'markActive' when an app goes to foreground mode.

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) {};

Last activity

There is a way to get an info when a user was active last time, in seconds.

This is a modern approach for messengers apps, e.g. to display this info on a Contacts screen or on a User Profile screen.

const userId = 123234
ConnectyCube.chat.getLastUserActivity(userId);

ConnectyCube.chat.onLastUserActivityListener = function(userId, seconds) {

};

System messages

In a case you want to send a non text message data, e.g. some meta data about chat, some events or so - there is a system notifications API to do so:

const userId = 123234
ConnectyCube.chat.sendSystemMessage(userId, msg)

ConnectyCube.chat.onSystemMessageListener = function(msg) {

};