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 Avaya Cloud 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 Avaya Cloud 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 Avaya Cloud Space using socket.io.

Note: Topic means Space.

2 Authentication

Avaya Cloud 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 seeAvaya Cloud 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 Avaya Cloud servers using the connectmethod along with the URL to the Avaya Cloud chat socket endpoint (https://spaces-socket.avayacloud.com/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.avayacloud.com/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 Avaya Cloud 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 Avaya Cloud 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 Avaya Cloud 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 Avaya Cloud 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 test or development 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 Avaya Cloud 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);
};

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

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 Avaya Cloud 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 Avaya Cloud 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.

8 Comment posts

To comment a post, you will need to emit a simple socket event:

const connectionPayload =
{
    query: "token=" + token + &tokenType='jwt'},
    transports: ['websocket']
}
const postComment = "Some comment text"

this.socketConnection = io.connect(this.socketURL, connectionPayload)

this.socketConnection.emit(
  "SEND_MESSAGE",
  {
      "category": "chat",
      "content": {
          "bodyText": postComment,
          "data": [],
          "mentions": []
      },
      "parentMsg": {
          "_id": "5f8ec55f15565b43f154e8a6"
      },
      "sender": {
          "_id": "5f04251caa4a347af9946e01",
          "type": "user"
      },
      "topicId": "5f32b87ffafba05a839154d9",
      "version": "1.1"
  }
)

For correct socket URL please refer to Socket.io guide :

Please note, that direct spaces don't have Posts and Tasks functionality.