Firebase Real time Chat and Event Streaming

Categories Mobile Applications

Hello Readers!

In our previous blog we had discussed about ‘iOS Chat App Development‘ using XMPP & QuickBlox with a road-map.

In this blog post, we are discussing about a famous & powerful platform ‘Firebase’, its key features, and how to use Firebase features to create Real time Chat App and Event Streaming.

So, Lets talk about ‘Firebase’ First;
 

What is Firebase?

  • As a powerful API, Firebase especially helps front-end developers to build real-time web apps by storing and synchronizing real-time data including user authentication, static hosting etc.
  • For iOS, it offers Objective-C or Swift SDKs, and for Android it provides Java. Also, Firebase helps to integrate with some of famous frameworks loke Ember, Angular, Ionic and ReactJS.
  • You can make use of some familiar tools like Javascript and JSON to update or save data and even listen any change in real-time data with few code lines.
  • Firebase stores data as a standard JSON that can be approachable from any platform. Moreover, Firebase has built in security and safety feature to secure your and your user data.
  • Although it is a paid service, but ‘Hacker Plan’ of Firebase is still available for Free.

Why to use Firebase?

Most of the backend concerns are taken care by Firebase and also these are dubbed as BaaS (Backend as a Service). As a real time API, Firebase uses web sockets for driving data to any of your application. So, it is not essentially required to refresh the browser to receive updates in real time and thereby making interactive app even more interactive. If any change in data occurs in a Firebase app, then it is also instantly updated across all devices update devices i.e. web or mobile. Also, all apps powered with Firebase can function offline. Whenever your app connectivity resumed, its data is synchronized instantly.
Above all, it is easy to build an app with Firebase having a basic HTML or Javascript knowledge.

 

Firebase Key features :

A Database of Realtime
Firebase database stores data as JSON and also synchronized it in realtime with every connection.

While creating any cross platform app using iOS, Android and Javascript SDKs, all the connections can share single database to automatically receive latest data updates.

Scales automatically with app

There is no need to worry even if your app is breakout. Firebase can well handle and scale your server code and supply with extra capacity.

Best in class safety features

In Firebase, all data transfer is generally performed over a secured 2048 bit SSL connection certificate.

At a granular level, validation and access for database is controlled with flexibility by using security rules language. You can easily verify and update all of your security data logic centralized in a single place.

Offline Function

Regardless of any Internet connectivity or network latency, Firebase app can also remain functional and responsive offline.

Local events are triggered instantly by Firebase database with all writes, before a server receive any of written data. Whenever connectivity is resumed, the connection will receive its missed changes and synchronize it latest server state.
 

Firebase-Chat Application

In Firebase, chat is the most essential use-case and helps you to design and build full featured chat app from scratch. It facilitates your chat app users to send messages or chat with other connected users through different listed public and private rooms. Also, users can see the list of active users in or across a room of a site. Moreover, user can search other users by their name or can also invite them to a chat room.

Before proceeding further to build a chat app following things you should know well:

  • Javascript

  • Basic EmberJS

Firebase Functioning
  • As a realtime data storage, allows user to build client side applications and also allows to make API calls to client’s service rather than writing user’s own sever.
  • User can store numbers, strings, booleans or child data as javascript. User can grab a reference to a location in their data.
Create EmberJS Array Proxies

Create & review an EmberJS array proxy. In your app you can use custom EmberJS arrays, to synchronize your data with firebase database.

Now, Let’s Create the Application!

Start with the easiest way to write real EmberJS applications with Ember App Kit.

In your terminal write:
npm install
After finishing it do

grunt server

Important: Installation of grunt-cli is essential. You can manually install it;

npm install -g grunt-cli

Create An Account for Firebase

Visit www.firebase.com and create your account. A new Firebase application can be created here under your system, and here you can sync your data.

Start with the Routes

As a best practice you can start with the EmberJS router. While creating your application, you can use index.hbs template without any worry for the router. This template by default called when emberJS opens. You can see all ‘html’ required by the page along with some commented items. Also, you can find a ready to use route file while opening your app-> routes -> index.js. Here, you can pass your custom array i.e. Embers ArrayProxy in to your controller.

Also, here you can create your reference like:-

export default Ember.Route.extend({

model: function() {

// code goes here

}

});

Create Custom ArrayProxy

You need to create a custom array to hold on to your Firebase reference and push/pull data to Firebase, although generally you would have to return EmberJS array consumed by the controller. In this way, when things change, you can store your data in sync with Firebase in your EmberJS application.

First, create a new folder lib in app -> lib

Then, in the lib folder create file messages.js. app/lib/messages.js.

And Finally, make a blank ArrayProxy using ECMA6 type models.

// app/lib/messages.js

export default Ember.ArrayProxy.extend({

// Custom code will go here

});

Now, all of your efforts should actually work.

On this array, create a property called “ref” as a reference url to your Firebase database.

After setting up “ref”, pull down some initial data from the Firebase servers by pulling down all of the messages. Then create a custom function that handles pushing data to Firebase.

// app/lib/messages.js

export default Ember.ArrayProxy.extend({

ref: null,

loadContent: function(){

var _this = this;

this.ref.on(‘value’, function(snapshot){

var messages = _.map(snapshot.val(), function(value, key){

value.id = key;

return value;

});

_this.set(‘content’, messages);

});

}.observes(‘ref’),

pushMessage: function(message){

this.ref.push(message);

}

});
First, you need to set ref to null, to reuse this array for many different refs.

Then, loadContent.

It mainly does two things, first pulling data from Firebase and secondly re-formatting that data into a form used by ‘ember.

var _this = this;

this.ref.on(‘value’, function(snapshot){

// deleted the code in here so you don’t get confused :p

});

In Firebase, you can do ref.on i.e. ‘value’, function(snapshot){};

At reference point, a snapshot of data will be returned with the ‘value’ event.

var messages = _.map(snapshot.val(), function(value, key){

value.id = key;

return value;

});

_this.set(‘content’, messages);

Finally, you can set the array proxies ‘content’, the values actually will be used by the Arrays.

Whenever ‘ref’ is changed, the observes (‘ref’) part will ensure that you pull the data down.

The pushMessage part is the last part of this array proxy.

pushMessage: function(message){

this.ref.push(message);

}

Firebase allows you to do ref.push (foo) to push data into their servers and your array should be able to handle this.

Important: Once you push the message to Firebase, your ref.on(‘value’, ….) code will detect that something was added and update the array with the proper content.

Back to Router

You have now your own custom array. You can make it work by putting it all together.

Open up app/router/index.js

You can use your new array here. Here, first you need to import your messages module you’ve created then use it.

// app/routes/index.js

import Messages from 'appkit/lib/messages';

export default Ember.Route.extend({

model: function() {

var messages = Messages.create({});

messages.set('ref', new Firebase("http://your-firebase-app.firebaseio.com/messages"));

return messages;

}

});

See! here you are creating a new array, then setting that array’s reference with your Firebase reference.

Finally, Connect the template and controller

Start with the template. Open up index.hbs

Delete the placeholder html input fields and uncomment the ember handlebars input helpers.

Your index.hbs file should now look something like this:

Mr. Chat

 

 

 

{{#each}}

    • {{username}} -> {{message}}

 

{{/each}}

 

 

{{input value=username type=”text” class=”form-control” id=”username” placeholder=”Username”}}

 

{{input value=message id=”message” name=”message” type=”text” class=”form-control” placeholder=”Message”}}

 

 

 

 

Now, to handle the ‘sendMessage‘ event, create the controller action.

Open up index.js in app/controllers/index.js and replace it with this:

var IndexController = Ember.ArrayController.extend({

actions:{

sendMessage: function(){

this.get(‘model’).pushMessage({‘username’: this.get(‘username’), ‘message’: this.get(‘message’)});

this.set(‘message’, ‘’);

}

}

});

export default IndexController;

Here, all of your work is grabbing previously created model i.e. your array proxy, and calling the pushMessage method.
You can grab the username and message data and push it to your application.Then you can clear everything.

Obviously there can be better ways to do this. The main annoying part to use this approach is to constantly add your Firebase domain name to routers. You can define your base domain name once as a solution. However, this is a nice quick way to get into Firebase.
 

Firebase-REST API Streaming

In Firebase database, Firebase REST endpoints support the EventSource / Server-Sent Events protocol to easily stream changes to one location.
You need to follow below mentioned steps to start streaming:

  1. First, set the client’s ‘Accept‘ header to text/event-stream

  2. Respect HTTP Redirects, specifically HTTP status code 307

  3. If location of the Firebase database need permission to read, include the ‘auth' query parameter.

In above response return, the server sends named events at the requested URL changes as the state of the data.

These messages structure conforms to the EventSource protocol i.e.

event: event namedata: JSON encoded data payload

The following events may be sent by the server:
put:
  • An object with two keys, the JSON-encoded data: path and data
  • The path points to a location relative to the request URL
  • All of the data at that location in its cache should be replaced by the user with the data given in the message.
patch:
  • An object with two keys, the JSON-encoded data: path and data
  • The path points to a location relative to the request URL
  • For each key, in the data, the user should replace the corresponding key in its cache with the data for that key in the message
keep-alive:
  • No action is required, the data for this event is null.
cancel:
  • The data for this event is null
  • This event will be sent if the Security and Firebase Rules cause a read at the requested location to no longer be allowed
auth_revoked:
  • The data for this event is a string indicating that a the credential has expired
  • This event will be sent when the supplied auth parameter is no longer valid
A set of events that the server may send are mentioned below as examples:
  1. // Set your entire cache to {"a": 1, "b": 2}

  2. event: put

  3. data: {"path": "/", "data": {"a": 1, "b": 2}}

  4. // Put the new data in your cache under the key 'c', so that the complete cache now looks like:

  5. // {"a": 1, "b": 2, "c": {"foo": true, "bar": false}}

  6. event: put

  7. data: {"path": "/c", "data": {"foo": true, "bar": false}}

  8. // For each key in the data, update (or add) the corresponding key in your cache at path /c,

  9. // for a final cache of: {"a": 1, "b": 2, "c": {"foo": 3, "bar": false, "baz": 4}}

  10. event: patch

  11. data: {"path": "/c", "data": {"foo": 3, "baz": 4}}

Hopefully, this post can serve as a good introduction to create a Firebase Real time Chat and Event Streaming.

For any query or more information feel free to reach us or email at [email protected].

If you want to share any of your suggestion or comments then please leave your words in the comments section below: