SAPUI5 WebSocket Chat with WhatsApp

Standard

Intro

I would like to show you how to create a WebSocket chat application to send and receive a WhatsApp message from the SAPUI5 web browser with the open source Yowsup.

c1.jpgc2.jpg

c3.PNG

How it works?

c4.jpg

Firstly, client will establish the connection to the server via the websocket address: ws://localhost:8080/fd6/websocket and register the following event listeners:

onerror: When a WebSocket encounters a problem, the “onerror” event handler is called.

onopen: When a WebSocket in the open state, the “onopen” event handler is called.

onmessage: When a WebSocket receives new data from the server, the “onmessage” event handler is called.

  1. var webSocket = new WebSocket(‘ws://localhost:8080/fd6/websocket’);
  2.   webSocket.onerror = function(event) {
  3.   onError(event)
  4.   };
  5.   webSocket.onopen = function(event) {
  6.   onOpen(event)
  7.   };
  8.   webSocket.onmessage = function(event) {
  9.   onMessage(event)
  10.   };

Once the connection to the server is established, it can send and receive the WhatsApp message with the following steps:

Send Message to WhatsApp

Step 1

When user sends a message from the browser, the function sendMsg() will send the message to the server: webSocket.send(msg);

  1. function sendMsg() {
  2.   var msg = oMsg.getValue();
  3.   if (msg == “”)
  4.   notify(‘Info’‘Please enter a message’‘information’);
  5.   else {
  6.   webSocket.send(msg);
  7.   oMsg.setValue();
  8.   oMsg.focus();
  9.   lastMsg = oModel.oData.chat;
  10.   if (lastMsg.length > 0)
  11.   lastMsg += “\r\n”;
  12.   oModel.setData({
  13.   chat : lastMsg + “You:” + msg
  14.   }, true);
  15.   $(‘#chatBox’).scrollTop($(‘#chatBox’)[0].scrollHeight);
  16.   }
  17.   return false;
  18.   }

Step 2

Method goInteractive in the python Yowsup code listens for the incoming message from the server: message = self.ws.recv() and send the message to the WhatsApp: msgId = self.methodsInterface.call(“message_send”, (jid, message))

  1. def goInteractive(self, jid):
  2.   print(“Starting Interactive chat with %s” % jid)
  3.   jid = “%s@s.whatsapp.net” % jid
  4.   print(self.getPrompt())
  5.   while True:
  6.   message = self.ws.recv()
  7.   if not len(message):
  8.   continue
  9.   if not self.runCommand(message.strip()):
  10.   msgId = self.methodsInterface.call(“message_send”, (jid, message))
  11.   self.sentCache[msgId] = [int(time.time()), message]
  12.   self.done = True

Receive Message from WhatsApp

Step 3

If there is any incoming message from WhatsApp, method onMessageReceived is called. It will send the message to the server: self.ws.send(messageContent)

  1. def onMessageReceived(self, messageId, jid, messageContent, timestamp, wantsReceipt, pushName, isBroadcast):
  2.   if jid[:jid.index(‘@’)] != self.phoneNumber:
  3.   return
  4.   formattedDate = datetime.datetime.fromtimestamp(timestamp).strftime(‘%d-%m-%Y %H:%M’)
  5.   print(“%s [%s]:%s”%(jid, formattedDate, messageContent))
  6.   if wantsReceipt and self.sendReceipts:
  7.   self.methodsInterface.call(“message_ack”, (jid, messageId))
  8.   print(self.getPrompt())
  9.   self.ws.send(messageContent)

Step 4

Finally, the function onMessage will print out the  incoming message from the server to the client browser.

  1. function onMessage(event) {
  2.   msg = event.data
  3.   lastMsg = oModel.oData.chat;
  4.   if (lastMsg.length > 0)
  5.   lastMsg += “\r\n”;
  6.   oModel.setData({
  7.   chat : lastMsg + “WhatsApp:” + msg
  8.   }, true);
  9.   $(‘#chatBox’).scrollTop($(‘#chatBox’)[0].scrollHeight);
  10.   notify(‘WhatsApp’, msg, ‘information’);
  11.   }

To display the message, I am using noty – a jQuery Notification Plugin:

  1. function notify(title, text, type) {
  2.   // [alert|success|error|warning|information|confirm]
  3.   noty({
  4.   text : text,
  5.   template : ‘<div class=”noty_message”><b>’
  6.   + title
  7.   + ‘:</b> <span class=”noty_text”></span><div class=”noty_close”></div></div>’,
  8.   layout : “center”,
  9.   type : type,
  10.   timeout : 4000
  11.   });
  12.   }

It’s pretty easy to use and implement the WebSocket in SAPUI5. Thanks for reading my blog and let me know if you have any comments/questions. Enjoy chatting !

Source Code:

I have attached the complete source code fd6.war (rename fd6.war.txt to fd6.war) and the modified Yowsup python code in the GitHub:

ferrygun/WebSocketChat · GitHub

References:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s