This tutorial will demonstrate how to send and receive messages in Avaya Spaces. For a more high-level overview, see the Socket.IO guide.

  1. Overview
  2. Authentication
  3. Create Socket Connection
  4. Setup Socket Listeners
  5. Send a message
  6. Share a file
  7. Send Direct Message

1 Overview

Think of a Zang Space as a chat room where each user can send and receive 3 different types of messages within it:

  • Chat
  • Post
  • Task

Websockets are used to send and receive messages efficiently among the various users and devices that may be members of a Zang Space. Using the Socket.io library we can implement websocket functionality with relative ease. In this tutorial, we will go through the process of sending and receiving messages to/from a Zang Space using socket.io.

Note: Topic means Space.

2 Authentication

Zang Space's socket API requires that connections be authenticated. The initial socket connection must be initiated by the client including a valid JSON Web Token (JWT) or OAUTH token in the payload. For information on how to obtain a user authentication token seeZang Authentication.

3 Create Socket Connection

Since Avaya Spaces uses sockets to communicate in a space, we must first setup a socket connection between our client device and Avaya Spaces. Start by including the socket.io javascript library. Details can be found here.

<script src="socket.io.js"></script>


Now that we have access to the socket.io library let's initialize a socket connection with the Zang servers using the connectmethod along with the URL to the Zang chat socket endpoint (https://spaces-socket.zang.io/chat) and our authentication token. Note: The token type can be tokenType=jwt or tokenType=oauth, depending on which token you are using.

var socketURL = "https://spacesapis-socket.zang.io/chat";
var connectionPayload = {
    query: "token=" + token + "&tokenType=jwt"
};
var socketConnection = io.connect(socketURL, connectionPayload);

At this point we have attempted to initiate a websocket connection with the Zang servers. Now the socketConnection object can be used to manipulate the client websocket connection. This will allow us to listen for messages transmitted from the Zang servers as well as send them. Next, confirm that the connection was successful by listening for theconnect event using the socket.io provided method on. If the connection was made successfully with the Zang servers, it will return a connect event through the socket connection.

socketConnection.on('connect', function() {
    console.log("Socket connection success!");
});
socketConnection.on('connect_error', function(error) {
    console.log('Socket connection error: ' + error);
});
socketConnection.on('error', function(error) {
    console.log('Socket error: ' + error);
});
socketConnection.on('disconnect', function() {
    console.log('Socket disconnected.');
});

Note: Additional events can be returned if the connection was not successful.

4 Setup Socket Listeners

Now that we can connect via sockets to the Zang servers, we will setup additional listeners on our socketConnection that will allow us to receive messages. For more information on the socket events used by Avaya Spaces see Socket Events. We will use the socket.io method on to setup listeners on our existing websocket connection.

socketConnection.on('MESSAGE_SENT', function(message) {
    console.log('Message received: ' + message);
});

Note: See related documentation for information on the object structure of a received message (Chat, Post, Task). Received messages can include links to file attachments among other things.

With this new listener, when a message is sent we will receive it and log its contents to the console. Unfortunately, we will not be receiving any messages yet. First we have to subscribe the current user and device to a space so that Avaya Spaces knows to send us messages related to the space we are interested in. To subscribe to a space we use the emit method from socket.io. This method sends an event along with a payload through our socketConnection to the Zang server. Let's bind our subscribe function to a button and have it emit SUBSCRIBE_CHANNEL along with a payload that includes the id of the space we are subscribing to.

var subscribeButton = document.getElementbyId('subscribeButton');
subscribeButton.onClick = function() {
    var spaceToSubscribe = {
        channel: {
          _id: '',
           type: 'topic'
        }
    };
    socketConnection.emit('SUBSCRIBE_CHANNEL', spaceToSubscribe);
}
socketConnection.on('CHANNEL_SUBSCRIBED', function() {
    console.log('Subscribe to space successful!');
});
socketConnection.on('SUBSCRIBE_CHANNEL_FAILED', function(error) {
    console.log('Failed to subscribe to space: ' + error);
});

Note: We can obtain the id of each space the current user is a member of using the following REST API endpoint /api/users/me/spaces.

Now we are subscribed to a space and we will receive any new messages in this space as a MESSAGE_SENT socket event. In addition, 2 new socket listeners were added to receive confirmation of our subscription success or failure.

5 Send a Message

To send a message to a Zang Space we must emit the SEND_MESSAGE event on our socketConnection. Let's create a button that sends a 'hello' message in our space.

var sendButton = document.getElementbyId('sendMessage');

sendButton.onClick = function() {
    var message = {
        content: {
            bodyText: 'hello'
        },
        sender: {
            _id: '',
            type: 'user'
        },
        category: 'chat',
        topicId: ''
    };
    socketConnection.emit('SEND_MESSAGE', message);
}
socketConnection.on('SEND_MESSAGE_FAILED', function(error)  {
    console.log('Send message failed: ');
    console.log(error);
});

Note: The category property corresponds to the type of message that is being sent (Chat, Post, Task). Additional properties are required when sending a Task or Post.

Note: topicId is the same as the id we used to subscribe to the space in step 4.

Note: Ensure you subscribe to the space before sending messages or other socket.io events to the space.

Note: The sender _id corresponds to the id of the current user and can be obtained through the REST API endpoint /api/users/me

The SEND_MESSAGE_FAILED socket listener was added to listen for errors when sending a message.

6 Share a File

A file can be included with a message for any of the 3 message categories. To include a file we must first upload it to the Zang servers and pass its information in thedata property of our message payload. Files should be uploaded to the URL provided in the response of the REST API call to/API/files/getuploadurl. This API call will return a JSON object that includes an array, each of which includes a URL and a fileKey property. The file should be uploaded to the URL and the fileKey should be included in the message payload as the fileId. To upload a file with our chat message our message payload should look like this:

var message = {
    content: {
        bodyText: 'hello',
        data: [
            {
                    fileId: '9ec91803-9a64-4294-aaa0-a171bd57e301',
                fileSize: 32553,
                    fileType: 'image',
                name: 'sample-1.jpg',
                provider: 'native',
                providerFileType: 'image/jpeg',
                thumbnailFile: '44e4e7ef-bae7-4605-b9df-485b880dd1b3'
            }
        ]
    },
    sender: {
        _id: '',
        type: 'user'
    },
    category: 'chat',
    topicId: ''
};

Note: For a full list of providerFileType see here

Note: For a description of each message object property see here

Next, by including this message payload and sending a message through our socketConnection like in step 5 a message with an image attachment will be sent to our Zang Space.

7 Send Direct Message

Direct messages work the same way as messages sent in a space. How a direct message works is a new space is created with the two users as members (if one does not already exist). To get the topicId of a direct space and send a message in the way specified in this tutorial make an API call to /api/spaces/direct/{userType}/{userId}. Once you have obtained the spaceID, subscribe to the space like you would with a group space. Once subscribed you can begin sending socket.io events to the direct space.

When using direct spaces, the other user will not be notified until a message is sent. Once a message has been sent, the receiving user will receive a MESSAGE_SENT. The topicId in the payload can be used to subscribe to further socket events related to the direct space.