aws / amazon-chime-sdk-js

A JavaScript client library for integrating multi-party communications powered by the Amazon Chime service.
Apache License 2.0
710 stars 478 forks source link

Chime Messaging: Websocket is not defined #2177

Closed sikka-tanu closed 2 years ago

sikka-tanu commented 2 years ago

Hi, I am using amazon-chime-sdk-js for chime messaging and getting the following error while session start-

ERROR ReferenceError: WebSocket is not defined at DefaultWebSocketAdapter.create (/opt/node_modules/amazon-chime-sdk-js/build/websocketadapter/DefaultWebSocketAdapter.js:12:31) at DefaultMessagingSession.startConnecting (/opt/node_modules/amazon-chime-sdk-js/build/messagingsession/DefaultMessagingSession.js:103:24) at DefaultMessagingSession.start (/opt/node_modules/amazon-chime-sdk-js/build/messagingsession/DefaultMessagingSession.js:52:18) at MessagingService.setUpSession (/var/task/src/services/MessagingService.js:58:27) at processTicksAndRejections (internal/process/task_queues.js:97:5) at async Runtime.exports.createChatClient [as handler] (/var/task/src/handlers/chatClientHandler.js:18:9)

Code-

  1. const AWS = require('aws-sdk'); const Chime = require('aws-sdk/clients/chime'); const appConfig = require('../../../environments/config');

const ChatClient = { client: undefined, awsClient: undefined,

async setAWSConfig(awsCreds) {
    AWS.config.region = appConfig.region;
    AWS.config.credentials = new AWS.Credentials(
      awsCreds.AccessKeyId,
      awsCreds.SecretAccessKey,
      awsCreds.SessionToken
    );
    return new Promise((resolve) => {
      AWS.config.credentials.get(() => {
        resolve(AWS);
      });
    });
},

async setupChimeClient(awsCreds) {
    this.awsClient = await this.setAWSConfig(awsCreds);
    this.client = new Chime({
      region: appConfig.region,
    });

    //TODO: remove this??
    return {
        awsClient: this.awsClient,
        client: this.client
    };
},

}

module.exports = ChatClient;

  1. Set up session, add observers and start the session -

` const { ConsoleLogger, DefaultMessagingSession, LogLevel, MessagingSessionConfiguration } = require('amazon-chime-sdk-js');

const ChatClient = require('../providers/Chime/ChatClientProvider');

const {"v4": uuidv4} = require('uuid'); const message = require('../constants/message'); class MessagingService {

constructor(){ this.messagingSession; this.sessionId = uuidv4(); this._logger = new ConsoleLogger('Chat', LogLevel.INFO); this.messagingSession; }

messageObserver = { messagingSessionDidStart: () => { console.log('Messaging Connection started!'); }, messagingSessionDidStartConnecting: (_reconnecting) => { console.log('Messaging Connection connecting'); }, messagingSessionDidStop: (_event) => { console.log('Messaging Connection received DidStop event'); }, messagingSessionDidReceiveMessage: (message) => { console.log('Messaging Connection received message'); // steps to perform after msg is received }, };

async getSessionEndpoint() {
const response = await ChatClient.client.getMessagingSessionEndpoint().promise(); return response; }

async setUpSession(userArn){

const endpoint = await this.getSessionEndpoint();
const configuration = new MessagingSessionConfiguration(
    userArn, 
    this.sessionId, 
    endpoint.Endpoint.Url, 
    ChatClient.client,
    ChatClient.awsClient
);
this.messagingSession = new DefaultMessagingSession(configuration, this._logger);
this.messagingSession.addObserver(this.messageObserver);
this.messagingSession.start();

}

async sendChannelMessage(channelArn, userArn, messageContent){ console.log('send Channel Message called');

const response = await ChatClient.client.sendChannelMessage({
    ChannelArn: channelArn,
    ChimeBearer: userArn,   //TODO: fetch from user ID??
    Content: messageContent,
    Persistence: message.persistence, // Allowed types are PERSISTENT and NON_PERSISTENT
    Type: message.type, // Allowed types are STANDARD and CONTROL
}).promise();

const sentMessage = {
  response: response,
  CreatedTimestamp: new Date(),
  Sender: { Arn: userArn },
};
return sentMessage;

} }

`

The logs show ws url - Chat - opening connection to wss://node001.ue1.ws-messaging.chime.aws/connect?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ASIAXPAX5CS6IIQW3W6C%2F20220420%2Fus-east-1%2Fchime%2Faws4_request&X-Amz-Date=20220420T171824Z&X-Amz-Expires=10&X-Amz-Security-Token=FwoGZXIvYXdzEHMaDNX4DYKizNLGX1jVdiK0ARFxGUz2O%2FkJfiDRfmwzeZF5%2BSSc3dOWxreKNlxXZHzuJaQnUFwjOGGoq%2B4QSdv1LVUuL%2FG64Jv0sguyMonMsIsuYb9m8eQnMok17N%2B0rNHjc2LQKFtpZDzRz72XLYbZKWhxu4uVgKqz%2FrXCph%2BIzGhpZjUagnj3UyrkSroC%2F%2FSwQTXpyWM6w0Q9mAf3szrxKhHYgBvBKv9Oe5VkzEln%2Bi3BTd8ArCMZoyYg0N7TRfNCoByI4SjagIGTBjItYfLoUYQepaU%2FTYNpCtlI8ZMbI41lFUU7UMqG2a2ARlzfrXnjmAKLK8L1ts%2F6&X-Amz-SignedHeaders=host&X-Amzn-User-Agent=node-12&X-Amzn-Version=2.30.0&sessionId=37669e42-c8ff-4e29-ab02-822fd082f936&userArn=arn%3Aaws%3Achime%3Aus-east-1%3A513298732220%3Aapp-instance%2F7708c011-9841-4342-b34d-d7b245c7bb05%2Fuser%2F7&X-Amz-Signature=06a22773d1340f57832a0e6b72e66a085a4e42b95cf210585c48f5e2788e8117

I am not able to understand what I am doing wrong.

Documentation referred- https://github.com/aws-samples/amazon-chime-sdk

ltrung commented 2 years ago

Just to clarify what is your typescript version? Could you try to use typescript version 4.2.3 to see if this issue is fixed?

sikka-tanu commented 2 years ago

Hi @ltrung - I am not using typescript. I have created lambda functions in nodejs (runtime: nodejs14.x) for the chime operations (create channel, create user, create chat client and messaging session etc). Please let me know if I should add any other details.

ltrung commented 2 years ago

Got it. In that case, I think the WebSocket object is just not defined in node js then. amazon-chime-sdk-js is meant to work in a browser environment. Just curious why do you need to initialize a messaging session in a backend as it means to be a websocket on the client to receiving incoming messages. To create app instance, and channels, you can use the client-chime-sdk-messaging.

sikka-tanu commented 2 years ago

Hi @ltrung - yeah I moved the code to client side and it works fine. Thanks.