Chat SDK Development Guide
Contents
- Interacting with the server - how to make requests and receive responses
- Handing entities - Creating, modifying and deleting entities
- Custom Authentication Authenticate with Firebase using an existing app server
- Code Examples - How to perform common tasks
- UI Customization - How to customize the UI and network interactions
Architecture and getting started
The easiest way to get started is by understanding the core principles that are used in Chat SDK. Once you understand these principles and design patterns, it will make customization much easier.
High level Architecture
The Chat SDK is broken down into the following major parts:
- Core: This includes interface definitions and common services.
- CoreData: This contains the ORM which stores all the user, thread and message data
- UI: This component contains all the app's user interface
- NetworkAdapter: This component handles communication with the network.
Now that you know the basic structure, we're going to go into some detail about some important classes and design patterns that can be used to manipulate the Chat SDK.
Interacting With The Server
In this section an explanation will be provide of how to interact with the messaging server. Performing tasks like creating threads, sending messages, working with users.
Core Concepts
The client server interaction generally looks like this:
The user performs some action -> A request is made to the server -> The server responds -> The UI is updated
For example, if a user writes a message and clicks "send", the message needs to be sent to the server. Once that's done, it needs to be displayed in the chat view.
To perform these actions, you need to understand the Chat SDK service architecture.
- NetworkManager: A singleton that makes the services available to the whole app
- NetworkAdapter: A wrapper class that contains references to all the possible services
- Handler: A service that contains a group of related functions
- Function: An individual action that can be performed.
This can be illustrated with some simple examples:
Creating a public thread
To create a public thread, the UI calls the following:
iOS
[[BNetworkManager sharedManager].a.publicThread createPublicThreadWithName: name]
Here we have: Network Manager -> Adapter -> Handler -> Function
Or a more concise form:
[BChatSDK.publicThread createPublicThreadWithName: name]
Android
NetworkManager.shared().a.publicThread().createPublicThreadWithName(threadName)
Here we have: Network Manager -> Adapter -> Handler -> Function
Or the concise form:
ChatSDK.publicThread().createPublicThreadWithName(threadName)
Note:
The NM class is just a convenience class that contains static getter functions to make calls to the NetworkManager more concise. The NM class should always be used unless you want to set a new handler.
Takeaway
The most important point is that if you want to find out which services are available, you should start by looking at the handler classes. These are documented and their names give you a good idea as to what they do.
You can find a full list of handler classes in the BNetworkFacade protocol for iOS and the BaseNetworkAdapter class for Android.
Case Study
Imagine you wanted to find out how to send an image message. First you would look at the BNetworkFacade or the BaseNetworkAdapter and you would see the following property ImageMessageHandler. If you open that interface you would see the function sendMessageWithImage. Calling this would cause the image to be uploaded to the server and then the image message would be added to the thread.
Handling the response
After we've made a request to the server, we will need to wait some time for the server to respond. Generally speaking there are two ways to handle the response:
- Using the Promise or Observable returned by the function
- Listening for app level notifications
Promises and Observables
This document won't go into a full explanation of promises and observables because they are very common design patterns and there are plenty of excellent explanations available online. The basic idea is that the function will return an object which will allow you to register a callback to receive a notification when the function server response comes back.
Note
A common mistake when using Observables is to forget to call subscribe(). Unless you call subscribe(), the method won't actually be executed! For example, pushUser() will do nothing. You have to call pushUser().subscribe() and then the method will be executed.
In our example of creating a public thread:
iOS
[BChatSDK.publicThread createPublicThreadWithName:name].thenOnMain(^id(id<PThread> thread) {
// Success
return Nil;
}, ^id(NSError * error) {
// Failure
return error;
});
Android
ChatSDK.publicThread().createPublicThreadWithName(threadName)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new BiConsumer<Thread, Throwable>() {
@Override
public void accept(Thread thread, Throwable throwable) throws Exception {
if(throwable == null) {
// Success
}
else {
// Handle error
}
});
In each example, we can define a function that should be called if the request is successful and another that will be called if there is an error.
Note
You can use the observeOn function to tell the observable to execute the result on the main thread.
App level events
There are some events that don't happen as a result of a function that we have called. For example, if another user sends us a message. These events are handled slightly differently in iOS and Android:
iOS
In iOS these events are handled by notifications. You can find a full list in the BNetworkFacade.h file. For example, if we wanted to receive notifications whenever a new message is received:
[_notificationList add:[[NSNotificationCenter defaultCenter] addObserverForName:bNotificationMessageAdded object:Nil queue:Nil usingBlock:^(NSNotification * notification) {
dispatch_async(dispatch_get_main_queue(), ^{
id<PMessage> messageModel = notification.userInfo[bNotificationMessageAddedKeyMessage];
});
}]];
A couple of key points:
-
All notifications are dispatched on a background thread so if you want to update the UI, you will need to use GSD to run your code on the main thread.
-
Sometimes the notification will contain a payload that's stored in the userInfo dictionary. In the example above, you can access the message. You can see what will be available by looking at the BNetworkFacade. Below the name of the notification, there will be one or more keys that can be used to get the user info objects.
Android
In Android events are sent through an event bus using a PublishSubject. You can access the event bus using the following:
ChatSDK.events().source()
or
ChatSDK.events().sourceOnMain()
When you subscribe to this source, you will receive a stream of NetworkEvent objects. You can also apply filters. For example:
ChatSDK.events().sourceOnMain()
.filter(NetworkEvent.filterType(EventType.MessageAdded, EventType.ThreadReadReceiptUpdated))
.filter(NetworkEvent.filterThreadEntityID(thread.getEntityID()))
.subscribe(...);
Here we are only listening to the event types: MessageAdded and ThreadReadReceiptUpdated for a particular thread.
To get a stream of all incoming messages, the following could be used:
Disposable d = ChatSDK.events().sourceOnMain()
.filter(NetworkEvent.filterType(EventType.MessageAdded))
.subscribe(new Consumer<NetworkEvent>() {
@Override
public void accept(NetworkEvent networkEvent) throws Exception {
Message message = networkEvent.message;
}
});
To stop listening we can use the disposable:
The Chat SDK also includes a helper class called DisposableList. You can add multiple disposables to this list and then call list.dispose() to dispose of them all at one time.
Note:
It's important to dispose of all of your observables when you destroy an activity. Otherwise, the observer will persist and may try to perform actions on an activity which no longer exists. This will cause the app to crash.
Handling Entities
Instant Messaging basics
In an instant messenger there are three core entities:
- User (
BUser, co.chatsdk.core.dao.User)
- Thread (
BThread, co.chatsdk.core.dao.Thread)
- Message (
BMessage, co.chatsdk.core.dao.Message)
Note:
In iOS, the entities are hidden behind protocol. For example, rather than dealing with a BUser object directly, we would always use the id<PUser> protocol. Because of platform differences, this isn't possible in Android so we use the database object directly.
User has a many-to-many relationship with thread and thread has a one-to-many relationship with message. We will go into more detail about how to create and request these entities later in this guide.
These entites exist both on the server and locally in the app's database. Both iOS and Android use an Object Relational Maping (ORM) to simplify data persistence. iOS uses CoreData and Android uses GreenDAO.
Common tasks are handled by the BStorageManager singleton iOS and co.chatsdk.core.session.StorageManager singleton in Android.
Creating a new Entity
iOS
id<PMessage> message = [BChatSDK.db createEntity:bMessageEntity];
Android
Message message = ChatSDK.db().createEntity(Message.class);
ChatSDK.db()
Saving an entity
iOS
message.type = @(bMessageTypeText);
[BChatSDK.db save];
Android
message.setMessageType(MessageType.Text);
message.update();
Fetching an entity using it's entity ID
iOS
id<PUser> user = [BChatSDK.db fetchEntityWithID:userEntityID withType:bUserEntity];
Android
User user = ChatSDK.db().fetchEntityWithEntityID(userEntityID, User.class);
There is also a useful fetchOrCreate method which will try to fetch an entity and if it doesn't exist, return a new entity.
Deleting entities
iOS
id<PUser> user = [BChatSDK.db fetchEntityWithID:userEntityID withType:bUserEntity];
[BChatSDK.db deleteEntity: user]
Android
User user = ChatSDK.db().fetchEntityWithEntityID(userEntityID, User.class);
DaoCore.deleteEntity(user);
Queries
More advanced queries are also possible.
iOS
Get the current user's contacts.
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"type = %@ AND owner = %@", @(bUserConnectionTypeContact), currentUser];
NSArray * entities = [BChatSDK.db fetchEntitiesWithName:bUserConnectionEntity withPredicate:predicate];
Android
List<ContactLink> contactLinks = DaoCore.fetchEntitiesWithProperty(ContactLink.class,
ContactLinkDao.Properties.LinkOwnerUserDaoId, currentUser.getId());
For more advanced queries it's recommended to look at the documentation for CoreData and GreenDAO.
Code Examples
In this section concrete examples will be provided of how to perform common tasks.
Authentication
Authentication is handled by the BAuthenticationHandler in iOS and the AuthenticationHandler in Android.
It is very important to authenticate your user before you load up any of the Chat SDK views. Failure to do this will cause the app to crash.
Authenticate a new user
To authenticate a user you need to pass an account details object to the authenticate method in the authentication handler.
iOS
BAccountDetails * accountDetails = [BAccountDetails username: @"some.email@domain.com" password:@"some password"];
[BChatSDK.auth authenticate: accountDetails].thenOnMain(...);
Android
AccountDetails details = AccountDetails.username("some.email@domain.com", "some password");
ChatSDK.auth().authenticate(details).subscribe(...);
Registering a new user
To register a new user, just use the Register type.
iOS
BAccountDetails * accountDetails = [BAccountDetails signUp: @"Joe" password:@"Joe123"];
[BChatSDK.auth authenticate: accountDetails].thenOnMain(...);
Android