BBM 1
BBM 1
WITH BLACKBERRY
MESSENGER
ENTERPRISE SDK
Notice of Rights
All rights reserved. No part of this book may be reproduced, stored in a retrieval
system or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embodied in
critical articles or reviews.
Notice of Liability
The author and publisher have made every effort to ensure the accuracy of the
information herein. However, the information contained in this book is sold
without warranty, either express or implied. Neither the authors and SitePoint
Pty. Ltd., nor its dealers or distributors will be held liable for any damages to be
caused either directly or indirectly by the instructions contained in this book, or
by the software or hardware products described herein.
Trademark Notice
Rather than indicating every occurrence of a trademarked name as such, this
book uses the names only in an editorial fashion and to the benefit of the
trademark owner with no intention of infringement of the trademark.
Getting Started With BlackBerry Messenger Enterprise SDK iii
About SitePoint
SitePoint specializes in publishing fun, practical, and easy-to-understand content
for web professionals. Visit http://www.sitepoint.com/ to access our blogs,
books, newsletters, articles, and community forums. You’ll find a stack of
information on JavaScript, PHP, Ruby, mobile development, design, and more.
iv Getting Started With BlackBerry Messenger Enterprise SDK
Table of Contents
Preface ......................................................................................................................... vii
Architecture Overview .................................................................................................... vii
Features ...................................................................................................................................ix
Chapter 4: Chats............................................................................................58
Terminology.........................................................................................................................59
Chats .......................................................................................................................................59
Participants ..........................................................................................................................59
Messages ............................................................................................................................. 60
Synchronization .................................................................................................................83
vi Getting Started With BlackBerry Messenger Enterprise SDK
Data Channel...................................................................................................................... 99
Conclusion .........................................................................................................................116
Preface vii
Preface
The BBM Enterprise SDK provides a framework to develop real-time, end-to-end
secure messaging capabilities in your own product or service.
The BBM Enterprise SDK security model ensures that only the sender and
intended recipients can see each chat message sent, and ensures that
messages aren't modified in transit between the sender and recipient. The BBM
Enterprise SDK also provides the framework for other forms of collaboration and
communication, such as push notifications, secure voice and video calls, and file
sharing. You can even extend and create new types of real-time services and use
cases by defining your own custom application protocols and data types.
Architecture Overview
The BBM Enterprise SDK platform is divided into the following four parts:
The BBM Enterprise SDK does not manage user identities or the social network
relationships for the application. The user "accounts" within the BBM Enterprise
SDK represent users only within the SDK. Applications can re-use their existing
user accounts and social network by associating their application accounts to
the BBM Enterprise SDK accounts.
For more detailed and technical information on the Identity Provider or the User
Management Service see Identity Management and User Management Service.
The BBM Enterprise SDK provides secure messaging and encryption for chats,
Preface ix
voice calls, and video calls. While the BBM Enterprise SDK encrypts and signs
data before it leaves the endpoint, your application is responsible for distributing
security keys between your users.
Push Service
Features
The BBM Enterprise SDK offers many powerful features to help you build rich
applications easily.
The BBM Enterprise SDK works with your user identity and management
systems to provide strong authentication and authorization. The user accounts
in the BBM Enterprise SDK represent users in the SDK only. The SDK leverages
OAuth and OpenID Connect so it can easily authenticate and associate your
users with their BBM Enterprise SDK accounts.
End-To-End Encryption
The BBM Enterprise SDK was designed to comply with the following three
security principles:
Chat messages are digitally signed, so you're assured of who sends each
message in your application.
Chat messages are encrypted, so you're assured that only the intended
recipient can read the message.
Chat messages are subject to integrity signature checks, so you're assured
that the message isn't modified in transit.
Messaging Publish-Subscribe
In the BBM Enterprise SDK, chats are entities that can be created and
manipulated. A chat is a shared space that allows many endpoints to contribute
content in a series of individual chat messages. Typically, these messages
represent user-visible content, but they can also contain arbitrary machine-
readable information that your application can consume. Chat messages can be
both published by and subscribed to by many users and endpoints for real-time
delivery and updates.
The BBM Enterprise SDK controls access so that only authorized participants of
a chat can publish and/or subscribe to content. Chats have administrative rights
that can be assigned to other participants to control who can add more
participants or make other changes.
While it's typical to think of chats and their messages in terms of Instant
Messaging (IM), the APIs in the BBM Enterprise SDK are general purpose and
highly extensible. A chat does not need to represent an IM conversation.
Fundamentally, a chat is a shared space where you can publish custom content
to the subscribers in real time. You can use this to create anything from a shared
whiteboard to a fleet-tracking location service to whatever you can imagine.
Read more about different ways to use the BBM Enterprise SDK.
The BBM Enterprise SDK makes it easy for your application to offer a fully-
featured instant messaging experience with:
Participants post messages to the chat. When a message is posted to the chat, it
appears below all of the earlier messages already in the chat. This series of
messages is referred to as the message history. Each chat has its own message
history which is accessible only to participants of the chat.
Guaranteed Delivery
The BBM Enterprise SDK ensures that a chat message will get from its sender to
xii Getting Started With BlackBerry Messenger Enterprise SDK
the participants of the chat while still offering immediate delivery to online
endpoints. The SDK and infrastructure work together to reconcile their views of
a chat's message history and recover any messages that failed initial delivery.
When messages can't be posted to chats, senders know with clear and definitive
error reporting.
The BBM Enterprise SDK reports the delivery status of chat messages they are
first queued, then sent, then delivered, and read. External delivery status is
tracked separately for each participant in each chat across all endpoints.
Each message in a chat can optionally carry two different kinds of attachments.
The Chat Message References feature allows you to move beyond a linear view
of the chat history to create richer relationships between chat messages. For
example, you can use Chat Message References to implement any or all of the
following features.
Liking messages.
Adding reactions to messages.
Starting a sidebar conversation thread from a message.
Voting on messages.
Custom message status updates beyond the built in delivered and read.
These are just examples. You can implement many custom behaviors and
features using Chat Message References by setting up rich relationships
between content.
Connection Management
Offline Delivery
The BBM Enterprise SDK allows your application to have multiple instances
running and connected at the same time for the same user. This ability is
referred to as having Multiple Points of Presence, or MPoP.
Web Workers
The BBM Enterprise SDK for JavaScript can run as a background task inside a
xiv Getting Started With BlackBerry Messenger Enterprise SDK
Web Worker while your main web application stays in the foreground. This lets
your web application be responsive even while the SDK is busy.
Even when the BBM Enterprise SDK for JavaScript does not run in a Web Worker,
it still offloads expensive work such as network communication and
cryptography to asynchronous tasks that don't block the JavaScript main loop.
The BBM Enterprise SDK server supports push notifications to the BBM
Enterprise SDK mobile clients. When new chat messages and incoming calls are
pending delivery to the clients, the server can send a push notification with one
of the following mechanisms:
The BBM Enterprise servers initiate a push request directly to Apple's Push or
Google's GCM/FCM servers.
Your server can initiate push requests to Apple or Google servers.
With the BBM Enterprise SDK, you can create true peer-to-peer connections
that securely carry encrypted custom application data between two endpoints.
These high-bandwidth connections allow you to create secure, real-time, and
custom media streams or send application-specific protocol messages between
endpoints for any purpose.
Example Applications
The BBM Enterprise SDK includes some example applications covering all of the
supported BBM Enterprise SDK platforms that you can use to help build your
Preface xv
messaging solution. All of these examples are shipped as part of the SDK
package. Each example application includes a README file to outline features,
prerequisites and a walkthrough.
Usually, an application doesn't need to work with BBMDS directly. The SDK APIs
expose a higher-level interface for interacting with the BBM Enterprise SDK.
However, sometimes, applications may benefit from direct access or exposure
to the BBMDS that underpins these APIs.
See the online FAQ for information on how to enable logging and how to obtain
the log file contents, which will include BBMDS messages.
xvi Getting Started With BlackBerry Messenger Enterprise SDK
Detailed Documentation
The BBMDS Protocol Documentation details the syntax and semantics of the
BBMDS messages.
Conventions Used
You’ll notice that we’ve used certain typographic and layout styles throughout
this book to signify different types of information. Look out for the following
items.
Code Samples
Where existing code is required for context, rather than repeat all of it, ⋮ will be
displayed:
function animate() {
⋮
new_variable = "Hello";
}
Preface xvii
Some lines of code should be entered on one line, but we’ve had to wrap them
because of page constraints. An ➥ indicates a line break that exists for
formatting purposes only, and should be ignored:
URL.open("http://www.sitepoint.com/responsive-web-
➥design-real-user-testing/?responsive1");
xviii Getting Started With BlackBerry Messenger Enterprise SDK
Hey, You!
Notes are useful asides that are related—but not critical—to the topic
at hand. Think of them as extra tidbits of information.
Watch Out!
Warnings highlight any gotchas that are likely to trip you up along the
way.
Live Code
This example has a Live Codepen.io Demo you can play with.
Github
Chapter
Getting Started
1
20 Getting Started With BlackBerry Messenger Enterprise SDK
You can integrate the BBM Enterprise SDK into your Android, iOS, JavaScript
(Web or Node.js) application by following the steps outlined in the platform
specific guides below. You can download the SDK from the developer resources
page.
To use the BBM Enterprise SDK, you require a registered domain for your
application. The following onboarding steps gather the necessary information
for your BBM Enterprise SDK enabled application to connect to the BBM
Enterprise servers.
Each BBM Enterprise SDK Partner application will be assigned a private domain.
User account creation, authentication and instant messaging will only occur
within your application's domain. This means your application cannot send and
receive messages with BBM Enterprise SDK applications that use other
Getting Started 21
Requirements
Android Studio version 2.0 or later, with SDK API level 19 or higher
Java version 1.7 or later
Android 4.4 or later
1 Download and extract the latest version of the BBM Enterprise SDK on
2 To add a dependency on the BBM Enterprise SDK, see the sample code
below.
repositories {
flatDir {
dirs 'libs' // This indicates the location of bbm_sdk-release.aar
22 Getting Started With BlackBerry Messenger Enterprise SDK
}
}
dependencies {
compile 'com.google.guava:guava:18.0' // The guava library is required by
➥ the BBM Enterprise SDK
compile (name:'bbm_sdk-release', ext:'aar') // This indicates the dependency on
➥ the BBM Enterprise SDK
...
}
When you subscribe to use the BBM Enterprise SDK, your application is
assigned a registered domain.
2 To configure the BBM Enterprise SDK with your registered domain, see the
<application
<!-- Configure the BBM Enterprise SDK with the user domain -->
<meta-data android:name="com.bbm.sdk.UserDomain"
➥android:value="MY_USER_DOMAIN"/>
<application
<!--This is used to point the SDK to either the Production environment or the
Sandbox by default this is pointed to production. If you want to use the Sandbox
environment add the below to your manifest-->
<meta-data android:name="com.bbm.sdk.environment.sandbox" android:value="true"/>
To start the BBM Enterprise SDK, see the sample code below.
Requirements
The BBM Enterprise SDK contains a framework must be imported into your
project:
2 Copy the contents of the sdk and sdk-release folders to your Xcode
project folder.
in Xcode.
There are two versions of the framework included with the BBM
Enterprise SDK. The version in sdk includes an i386 and x86_64
simulator segment and as such, is not suitable for submissions to the
App Store. The version in sdk-release contains only the armv7 and
arm64 segments and is suitable for app store submission. When
building your App Store release submission, to ensure the correct
version is embedded in your IPA.
6 In the search text field in the upper right corner of the screen, type
7 On the left side of the screen, drag the directory in which you placed
Getting Started 25
1 In the search text field in the upper right corner of the screen, type
Bitcode.
Audio, AirPlay, and Picture in Picture - this allows your application to play
audio alerts when a user receives voice or video calls (each user must grant
permission for the app to use the microphone prior to using it for the first
time.
Voice over IP - this allows your application to make and receive voice and
video calls.
PushKit
This will add the necessary background modes to your application's Info.plist.
<key>UIBackgroundModes</key>
<array>
<string>voip</string>
<string>audio</string>
<string>remote-notification</string>
</array>
To start the BBM Enterprise SDK, see the sample code below. For more info, see
the comments in the sample code below.
// Start BBM Enterprise SDK services by supplying your required unique BBM
//Enterprise domain,which is provided by the BBM Enterprise team when you
//sign up to use the SDK
[[BBMEnterpriseService service] startService:@"<Domain UUID>" environment:kBBM
➥Config_Sandbox completionBlock:^(BOOL success) {
// Update the UI once there is a response.
// Perform any appropriate actions here such as display existing chats
28 Getting Started With BlackBerry Messenger Enterprise SDK
The environment parameter will determine which servers the BBM Enterprise
SDK will connect to. When testing your application, you should specify
kBBMConfig_Sandbox as the environment. The application that you ship to
customers should specify kBBMConfig_Production as the environment.
If using the support code in your application please note the following:
This SDK is should be used instead of the BBM Enterprise Web SDK for web
development where development is done with Node.js tooling.
There are some differences between the BBM Enterprise SDK for JavaScript
(Node.js and Web) and the BBM Enterprise SDK for mobile (Android and iOS)
because it is intended to operate in either a web browser or a Node.js
application. These are the important differences:
The BBM Enterprise SDK for mobile devices persistently stores all chat
messages and metadata that they receive. The BBM Enterprise SDK for
Javascript caches messages and chat metadata in memory while running, but it
does not store anything persistently. It downloads chat metadata when first
launched, and then downloads messages for a chat on demand only.
The BBM Enterprise SDK for mobile devices will download all messages during
initial setup. The BBM Enterprise SDK for JavaScript does not, but instead
provides APIs to retrieve only some messages at a time from a specified chat.
The BBM Enterprise SDK for mobile devices automatically downloads any
attachment received, and stores the attachment persistently. The BBM
Enterprise SDK for JavaScript does not download attachments automatically.
30 Getting Started With BlackBerry Messenger Enterprise SDK
Unlike with the BBM Enterprise SDK for mobile devices, the BBM Enterprise SDK
for JavaScript can be configured to act as if the user is subscribed to a subset of
the chats to which a user has been granted permission. When in this mode, any
message from a chat not on the allowed list is dropped, including invitations to
new chats which are not on the list. The list can be reconfigured at any time to
add chats to which the user already has permission.
Prerequisites
1 Download and extract the latest version of the BBM Enterprise SDK to
npm init
Then instantiate the BBM Enterprise SDK by passing the domain, environment,
userId, description, getToken function and getKeyProvider function, and
optionally the nickname and messageStorageFactory.
// A description of the client. This will be used to describe this endpoint when
// using endpoint management functionality. This should never be empty. The
// description can be a maximum of 2000 Unicode Code Points.
description: 'node ' + process.version
// A storage factory may be chosen based on how the client wants to be notified
// of changes to the message list. The default Immutable storage factory is ideal
// for clients that want to receive messages in immutable list and calculate
// differences from a previous list to see what has changed. The SpliceWatcher
// factory is ideal for clients that want to be notified about what has changed
// through a series of splice calls.
messageStorageFactory: BBMEnterprise.StorageFactory.SpliceWatcher
})
This SDK should be used when you want to be able to drop an SDK into a web
page with the inclusion of a <script> tag. Do not use this SDK with Node-based
tooling to process JavaScript modules into a web app. For these tools, use BBM
Enterprise SDK for Node.js, which provides the same functionality in an
isomorphic node package.
There are some differences between the BBM Enterprise SDK for JavaScript
(Node.js and Web) and the BBM Enterprise SDK for mobile (Android and iOS)
because it is intended to operate in either a web browser or a Node.js
application. These are the important differences:
The BBM Enterprise SDK for mobile devices persistently stores all chat
messages and metadata that they receive. The BBM Enterprise SDK for
Javascript caches messages and chat metadata in memory while running, but it
does not store anything persistently. It downloads chat metadata when first
launched, and then downloads messages for a chat on demand only.
The BBM Enterprise SDK for mobile devices will download all messages during
initial setup. The BBM Enterprise SDK for JavaScript does not, but instead
provides APIs to retrieve only some messages at a time from a specified chat.
The BBM Enterprise SDK for mobile devices automatically downloads any
attachment received, and stores the attachment persistently. The BBM
Enterprise SDK for JavaScript does not download attachments automatically.
Instead, it provides a download function which will retrieve the attachment
attached to a message. The attachments are not cached when they are
downloaded. The client can download the attachment multiple times, but this
could cause a lot of network traffic.
Unlike with the BBM Enterprise SDK for mobile devices, the BBM Enterprise SDK
for JavaScript can be configured to act as if the user is subscribed to a subset of
the chats to which a user has been granted permission. When in this mode, any
message from a chat not on the allowed list is dropped, including invitations to
new chats which are not on the list. The list can be reconfigured at any time to
add chats to which the user already has permission.
Prerequisites
A supported browser
In general, all browsers that support these can run BBM Enterprise SDK for web.
BBMEnterprise.validateBrowser()
Safari and Microsoft Edge are not supported because they do not include the
P-521 ECC algorithms in WebCrypto. Other than this limitation, the BBM
Enterprise SDK will work on Safari 9 or Edge 16.16299. Although an integrator of
the SDK can add full WebCrypto support to Safari by including a WebCrypto
polyfill prior to the bbm_sdk_web.js script tag, this is strongly not recommended
because the polyfill will reduce the security of the system.
The SDK may be run in a web worker in any supported browser as well as in
Safari (Safari is subject to the same caveat as when not running in a WebWorker).
For Microsoft Edge, there is the additional problem that there is no source of
cryptographically strong random numbers available inside the WebWorker in
Edge. As such, providing a polyfill for WebCrypto getRandomValues API will
probably require passing at least a random number generator seed into the web
worker from outside.
1 Download and extract the latest version of the BBM Enterprise SDK to
36 Getting Started With BlackBerry Messenger Enterprise SDK
<script src="path/to/bbm_sdk_web.js"></script>
This provides access to the global BBMEnterprise object, which can be used to
access BBMEnterprise SDK functionality.
In your application, initialize the BBM Enterprise SDK by passing the domain,
environment, userId, description, getToken function and getKeyProvider
function, and optionally the nickname and messageStorageFactory.
domain: 'domain'
// This is the identity of the user to log in as, as provided by the identity
// provider module.
userId: 'identifier'
// A description of the client. This will be used to describe this endpoint when
// using endpoint management functionality. This should never be empty. The
// description can be a maximum of 2000 Unicode Code Points.
description: navigator.userAgent
// A storage factory may be chosen based on how the client wants to be notified
// of changesto the message list. The default Immutable storage factory is ideal
// for clients thatwant to receive messages in immutable list and calculate
// differences from a previous list to see what has changed. The SpliceWatcher
// factory is ideal for clients that want to be notified about what has changed
// through a series of splice calls.
messageStorageFactory: BBMEnterprise.StorageFactory.SpliceWatcher
})
Chapter
Identity
Management
2
40 Getting Started With BlackBerry Messenger Enterprise SDK
The BBM Enterprise SDK does not manage user identities or contact
relationships for applications. The user accounts in the BBM Enterprise SDK
represent users in the SDK only. The SDK leverages OAuth and OpenID Connect
so it can easily authenticate and associate users to their BBM Enterprise SDK
accounts.
How It Works
To sign in to the application, the user must authenticate with the identity
provider. Next, the application must obtain an OAuth access token or an OpenID
Connect ID token from the identity provider and pass it to the BBM Enterprise
SDK along with the user ID. The BBM Enterprise infrastructure uses the token to
authenticate the user with your identity provider. The BBM Enterprise SDK client
and infrastructure can then communicate using an internal token. The process
repeats when the internal token expires.
The BBM Enterprise SDK supports both OAuth access tokens and OpenID
Connect JWT tokens to authenticate the user with your identity provider. The
information required for the BBM Enterprise SDK to perform the validation is
provided when you register a domain for your application.
OAuth 2.0
For OAuth access tokens, the BBM Enterprise infrastructure must first access
the Token Info service to validate the client_id of the access token. The BBM
Enterprise infrastructure can then access the User Info service to validate the
user ID.
The BBM Enterprise infrastructure validates that the access tokens provided by
the application are generated by the application's OAuth provider specifically for
the application. This is done by invoking the OAuth provider's Token Info Web
service endpoint to retrieve the client_id of the access token and matching it
42 Getting Started With BlackBerry Messenger Enterprise SDK
BlackBerry recommends following the RFC 7662 Oauth 2.0 Token Introspection
when implementing the Token Info Web service. Additionally, the BBM
Enterprise infrastructure can integrate with a token services that accepts HTTP
GET with an access token parameter and returns the client ID in a JSON
response.
In addition to the service URL, the following configuration items on the Token
Info service are used by the BBM Enterprise infrastructure to invoke the service
and process the response.
The BBM Enterprise infrastructure validates that the access token provided by
the application belongs to the user. This is done by invoking the User Info Web
Identity Management 43
service endpoint to retrieve the user ID of the access token and matching it with
the user ID provided by the application.
In addition to the service URL, the User ID field: must also be specified when you
configure the User Info service. The User ID field: is the name of the field that
contains the user ID in the JSON response. If the JSON response is composite, a
field path in the format <parent_field>.<child_field>.<user_id_field> can be
used.
OpenID Connect
The BBM Enterprise SDK accepts both JWT based ID tokens and access tokens
issued by an OpenID Connect identity provider. Access tokens are
recommended if the application can be registered as an OAuth resource with
explicit scopes the user can grant access to.
The BBM Enterprise infrastructure validates the signature of the JWT tokens
with the public key published by the identity provider. Furthermore, the usage of
the token is validated by its audience, issuer and scopes.
To use JWT tokens, the following configuration is required when registering the
domain for your application.
JWKS URI: The URI of the JWT token signature public keys from the identity
provider.
Issuer Claim Name: The name of the claim for the token issuer. For example,
44 Getting Started With BlackBerry Messenger Enterprise SDK
"iss".
Issuer: The issuer of the claim accepted to access.
User ID Claim Name: The name of the claim for the user ID. For example,
"sub". The claim value is used by the BBM Enterprise SDK as the user ID and it
needs to match the user ID provided by the application.
Expiration Claim Name: The name of the claim for the expiration time. For
example, "exp".
Client ID Claim Name: The name of the claim that carries the client ID(s) the
token is issued for. For example, "aud".
Client IDs: The list of client ID values that are accepted by the BBM Enterprise
infrastructure. A token is accepted when one of the client IDs from the token
belongs to the configured client IDs.
Scope Claim Name: The name of the claim for the access scope. For example,
"scope" or "scp".
Scopes: The list of scope values that are accepted by the BBM Enterprise
infrastructure.
Azure Active Directory supports JSON Web Tokens (JWT). Your app needs to
pass the JWT access token along with the user ID to the BBM Enterprise SDK so
that the user is authenticated against your Azure Active Directory. Your app can
parse the JWT access token returned from the Azure authentication service to
get the Active Directory user ID and other information.
Identity Management 45
In Microsoft Azure, each access token must be used for a specific resource. The
scope parameter sent in the authentication request can contain multiple
permissions, but all the permissions must be for the same resource. The access
token that is used for the BBM Enterprise SDK must not be used for other
resources such as Microsoft Graph API.
To use Azure Active Directory for authenticating a user with the BBM Enterprise
SDK, follow the steps in the section below to register a Web API with a scope
defining the permission to use BBM Enterprise SDK. This allows the BBM
Enterprise servers to validate the access token that your app received from the
Azure Active Directory authentication service.
Assumption
We're assuming your app will use Azure Active Directory v2.0
authentication API
App Registration
Make note of the Application Id since that will be needed for other steps.
If developing for the BBM Enterprise JavaScript SDK, add a Web Platform
and enter the path to your redirect page that your application will send as the
46 Getting Started With BlackBerry Messenger Enterprise SDK
Add a new scope. We recommend using Messaging.All . This must match the
scope you entered in your BBM Enterprise SDK domain's configuration. It
must also match the scope parameter sent in the request from the app to
authenticate with the Azure authorize server.
Identity Management 47
The BBM Enterprise infrastructure can authenticate a user with Google Sign-In.
If your users already sign into your app using Google Sign-In, you can easily
extend the implementation to allow for access and Identity Management with
the BBM Enterprise infrastructure. This example creates a Firebase project to
enable authentication with Google accounts. If your application is not using
Firebase Database for User Management or Cloud Key Storage you can create a
Google API project.
"Authentication" page from the sidebar. Open the "Sign-In Method" tab and
toggle the enable switch for the "Google" Sign-in provider.
Copy the Web client ID value, we will use it later to configure your BBM
Enterprise SDK domain.
Open the project settings by clicking the settings cog in the top left corner.
Identity Management 49
Add a new app matching the platform of your BBM Enterprise SDK enabled
application.
https://www.googleapis.com/oauth2/v3/tokeninfo
https://www.googleapis.com/oauth2/v3/tokeninfo
Copy the client-id value we saved earlier into the OAuth Client ID's field.
If you have added an Android application you will need to add the client_id
( client_type 3 ) value from the google-services.json file to the OAuth Client
IDs list.
"oauth_client": [
{
"client_id": "12345678901-umrpbv07n96ck79u5uw1ow04vt4dwza.apps.
➥googleusercontent.com",
"client_type": 3
},
User Management Service 51
Chapter
User
Management
Service 3
52 Getting Started With BlackBerry Messenger Enterprise SDK
The BBM Enterprise SDK does not manage user identities or contact
relationships for applications. The user accounts in the BBM Enterprise SDK
represent users in the SDK only. Your application can reuse existing user
accounts and social networks by associating those application accounts with
BBM Enterprise SDK accounts.
When creating the association between your application user and the regId, your
application will need be able to verify that such an association is genuine. The
BBM Enterprise infrastructure issues a registration token as part of the
User Management Service 53
Typically, your application would store these account associations behind a cloud
service accessible to all your application endpoints, and the cloud server that has
the access rights to create those association records would verify the
registration token. Verifying the registration token in an application client
endpoint is not recommended. In order to trust client-based verification, you
would to have complete trust in the integrity of the client before using its result.
The regId assigned to a given application user will not change when your
application registers another endpoint for that user with the BBM Enterprise
SDK.
To facilitate the different needs your application may have, the BBM Enterprise
SDK does not manage your user identities. Your application finds contacts or
other user relationships in ways that make sense to you.
For example, to start a chat with a user, your application first locates the target
user in its user account records. Within that record, your application obtains the
associated regId identifier that was securely recorded for that target user when
they first registered their account with the BBM Enterprise SDK. Your application
then asks the SDK to start a chat with that regId.
All authorized users can read each entry in the bbmsdk/identity/users table.
Each user may create and edit their own entry in the table which is stored at
bbmsdk/identity/users/$uid. The users table is maintained separately from the
cloud keys. However, cloud keys and users can be stored in the same Firebase
database.
The following rules may be installed into a project's Realtime Database via the
project's Firebase console, which is located at
https://console.firebase.google.com/.
"rules": {
"bbmsdk" : {
"identity": {
//User records can be written by the record creator and read by all
//authenticated users
"users" : {
".read": "auth != null",
"$uid": {
".write": "auth != null && auth.uid == $uid"
}
}
}
}
}
56 Getting Started With BlackBerry Messenger Enterprise SDK
Sample data
avatarUrl : a url where their avatar can be obtained. This must be accessible by
all users.
email
name
regId : their unique registration id assigned by the BBM Enterprise SDK.
"bbmsdk" : {
"identity": {
"UID_1" : {
"avatarUrl" : "https://avatar.com/testavatar.png",
"email" : "[email protected]",
"name" : "John Smith",
"regId" : "123456789000"
},
"UID_2" : {
"avatarUrl" : "https://avatar.com/testavatar2.png",
"email" : "[email protected]",
"name" : "Jane Doe",
"regId" : "123456789001"
}
}
}
In Microsoft Azure, each access token must be used for a specific resource. Your
User Management Service 57
app has to authenticate against Azure with a scope containing all Microsoft
Graph API permissions to access Active Directory user data. It cannot reuse the
access token granted for the BBM Enterprise SDK.
The Microsoft Graph API allows an app to access the data of Active Directory
users, and to write custom application data for each user using custom
extensions. In the BBM Enterprise SDK examples, a user's registration ID (regId)
is automatically stored against the user's data in Azure Active Directory. This
allows your app to easily integrate against a corporate directory to facilitate user
lookup, and start secure chat, voice, and video communications using the BBM
Enterprise SDK. Your app can also leverage Microsoft Graph API to manage a
contact list by utilizing user groups or other criteria.
Note: These instructions assume your app will use Azure Active Directory v2.0
authentication API.
From the Microsoft Application Registration Portal, access the Microsoft Graph
Permissions section and add the following:
User.ReadWrite: Required to view the local users data and write the BBM
Enterprise SDK regId to their user entry in Active Directory.
User.ReadBasic.All: Required to view all users in the Active Directory.
Chapter
Chats
4
Chats 59
A central feature of the BBM Enterprise SDK is the ability to allow applications to
create chats and share rich messaging experiences. The following section
highlights many of the features of those chats.
Terminology
The BBM Enterprise SDK consists of an identity and its endpoints. An identity is
a user and the endpoints are the identity's client applications that are using the
BBM Enterprise SDK. For more information on identities and endpoints, see
Multiple Points of Presence.
Chats
In the BBM Enterprise SDK, chats are entities that can be created and
manipulated. A chat is a shared space that allows many endpoints to contribute
content in a series of individual messages. Typically, these messages represent
user-visible content, but they can also contain arbitrary information that the
application can consume. The example applications included with the SDK
demonstrate the different ways that messages can be used in chats.
Chats have properties. For example, chats have a subject that can be set and
seen by participants. Chats also have fields that allow applications to attach local
data that is visible only to the local endpoint and fields that allow messages to
reference each other.
Participants
The identities in a chat are called participants. Each participant in a chat has
access to all of the messages and metadata in the chat. This means that if one
participant posts a message to the chat, the message is delivered to all of the
other participants on each of their endpoints. Different chats can have different
participants.
Some participants are administrators and have additional capabilities in the chat.
60 Getting Started With BlackBerry Messenger Enterprise SDK
Chats can have as few as one participant, but when a chat loses the last
participant, the chat is deleted.
Because participants can enter and leave chats, participants have a state. When
a participant leaves a chat, the participant's messages aren't deleted. Instead,
the participant's state is updated to indicate that they are no longer in the chat.
Messages
Participants post messages to the chat. When a message is posted to the chat, it
appears below all of the earlier messages already in the chat. This series of
messages is referred to as the message history. Each chat has its own message
history which is accessible only to participants of the chat.
The author of a chat message is referred to as its sender and the act of adding a
message to a chat is referred to as posting the message to the chat.
The application can give each message a type tag to specify how to interpret its
content and metadata on the sending and receiving endpoints.
Messages have many metadata fields, including fields that allow the application
to attach large files or binary payloads, and fields that allow the application to
attach local data visible only to the local endpoint.
Other metadata includes the sender, the time the message was posted, and
information about how other participants have interacted with the message. For
example, every message reports which participants have received the message
and which participants have marked the message as read.
Messages can also be recalled to remove them from receiving endpoints. Or,
messages can be privately deleted so that they are no longer visible to the acting
participant, but remain visible to everyone else.
Chats 61
Normal chats can be between any number of participants, and allow some
participants to be granted administrative capabilities. The same participants
can participate in any number of normal chats.
One-to-one chats exist between two identities. The BBM Enterprise SDK
makes sure that only a single one-to-one chat can exist between the two
identities. When a participant creates a one-to-one chat, the other participant
must be specified when the chat is created, and other participants cannot be
added later. When one of the participants leaves the chat, the other
participant also leaves automatically. At that point, a new one-to-one chat can
be created between the pair of participants.
Participants can leave a chat at any time. When the last participant leaves a chat,
it is destroyed even within the BBM Enterprise infrastructure.
62 Getting Started With BlackBerry Messenger Enterprise SDK
Chat Administration
The creator of a chat is automatically an administrator of that chat. Chat
administrators have a few additional capabilities that regular participants do not
have. Administrators can:
When a chat is created, its invitation policy is set by its creator to either allow all
participants to invite others or to allow only administrators to invite others. This
policy cannot be changed while the chat exists. When a chat has an
administrators-only invitation policy but no administrators, then no more
participants can be added to the chat.
Administrators also have the power to destroy chats by removing all other
participants and then leaving the chat.
Other than its size, the BBM Enterprise SDK places no restrictions on the
Chats 63
All attachments are protected using BBM Enterprise SDK Protect mechanisms.
Attachments can only be received and read by participants of the chat that have
access to the message they are attached to.
Both attachment types preserve their file names (without any directory parts),
subject to some portability and security filtering.
Chat messages also have a data field that can carry arbitrary applications-
specified JSON content. This data is also embedded directly into the chat
message, but it is not considered an attachment in the same sense that a thumb
or file attachment is. In the BBM Enterprise SDK API, attachments are generally
managed as if they are binary files, whereas the data field is presented as a
JSON object property of the chat message.
Thumb Attachments
As its name suggests, a thumb attachment is useful for carrying a small
thumbnail image, such as the small version of a picture. To use a thumb
attachment in this way, your application generates a small image file (such as a
JPEG) with a small resolution and reasonable encoding quality.
On Android and iOS, your application provides the BBM Enterprise SDK with
the path name of a file to be added to the chat message as a thumb
attachment.
In JavaScript, your application provides the thumb attachment data directly.
When a chat message is received, the BBM Enterprise SDK extracts any thumb
attachment.
64 Getting Started With BlackBerry Messenger Enterprise SDK
A thumb attachment must be no larger than 56320 bytes (55 KB). Its total size is
also subject to a cumulative size limit when combined with the size of the chat
message's data object (encoded as JSON in UTF-8) and the size of the chat
message's content field (in UTF-8). These three fields combined must not
exceed 71680 bytes (70 KB).
Thumb attachments would not be a good place to put file type icons. Each
thumb attachment is directly embedded into the delivered chat message and will
be received by and consume storage space on all endpoints of all users in the
chat. So, for file type icons such as "spreadsheet", "document", and
"presentation", an app would be better to know those icons intrinsically and just
display them on each endpoint (perhaps based on hints in the customizable
data JSON object).
File Attachments
A file attachment is the recommended way for applications to send large
content such as documents, full-sized images, or other custom binary payloads
to the participants of a chat.
On Android and iOS, your application provides the BBM Enterprise SDK with
the path name of a file to be added to the chat message as a file attachment.
In JavaScript, your application provides the file attachment data directly.
Chats 65
When a chat message is received, the BBM Enterprise SDK will indicate whether
it has a file attachment. If it does, your application can ask the SDK to download
it either right away or later.
In the BBM Enterprise SDK for Android and iOS, both thumb and file
attachments can be detached from their chat message in order to free space on
an endpoint.
The Chat Message References feature allows you to move beyond this linear
view of the chat history to create richer relationships between chat messages.
For example, you can use Chat Message References to implement any or all of
the following features.
These are just examples. You can implement many custom behaviors and
features using Chat Message References by setting up rich relationships
between content.
When your application sends a chat message, it can add a ref property that
contains a list of outgoing references. Each reference in that list consists of:
Note that the reference's tag here is separate from the chat message's tag .
The two strings are not related and do not need to use the same values.
A source chat message can refer to many different messages as long as each
reference has a unique tag value. Each reference is represented by an element
in the source chat message's ref list.
The target chat messages referred to by a source chat message's ref list know
Chats 67
that they are the target of a reference. These incoming references are indicated
on a chat message with the refBy property. It contains a list of incoming
references, and each incoming reference has:
Your application can look at a target chat message and instantly determine
whether it's been referred to by some later message in the chat, and know the
most recent such reference, and whether there are other references between
those two messages. This gives you a lot of power to efficiently draw chat
messages in very different scenarios, as shown in the examples below.
The application can also retrieve the full list of source chat messages that
reference the target chat message with a specific tag .
The values and meanings of the tag strings are controlled by you, the
application developer. You can impose any meaning that you want on your tags
and the references they create.
For example, say you want to implement chat message quoting. In this feature,
when a user responds to a chat message, they can quote the content of that
original message. When a chat message is quoted in this way, its display is
updated to show the number of times it has been quoted.
To implement this feature, you decide to use a Chat Message References tag
value of Quote to mean that the target chat message has been quoted by the
source chat message.
68 Getting Started With BlackBerry Messenger Enterprise SDK
Assume that the user wants to quote the following existing chat message.
messageId 123
Once the user indicates which existing chat message they want to quote, and
they've entered the content of the quoting message, your application sends a
new chat message that contains a single ref . Assuming that this new chat
message ends up with a message id of 130, it will contain the following fields.
messageId 130
ref[0].tag Quote
ref[0].messageId 123
This new quoting chat message is the source chat message in the Chat Message
References relationship.
Note that the quoting messages does not contain the content of the message
that is being quoted; the messages only reference each other. Both the quoted
or quoting message can contain rich content, custom data, thumb or file
attachments, and even other references with other tag values. In this example,
we presume the new quoting message has only the single outgoing reference,
the user's response text, and nothing more, but your application can allow users
to quote and respond with any type of content.
On the sending endpoint and on all receiving endpoints for all participants of the
chat, the quoted chat message (with id 123) gains a refBy list. The quoted
Chats 69
messageId 123
refBy[0].tag Quote
refBy[0].newestRef 130
refBy[0].count 1
This indicates that there is an incoming reference referring to this chat message
of type Quote . There is currently only one such reference, and the newest
reference is from chat message 130. Note that the quoted message only gains a
refBy entry and its other fields did not change.
In both the sender and receiver, you decide how you want to draw these chat
messages. In this example, the goal is to show a quote counter on the original
chat message and to draw the new quoting message so that it displays the
content of both the quoted and quoting message.
To draw the quoted message, your application needs to know how many refBy
references there are with the tag Quote . Because refBy is a direct property on
the quoted chat messages, your application makes this drawing decision without
needing any additional data. When there's an incoming Quote reference, you
simply use its count to draw the counter.
To draw the quoting message, your application needs the quoting message's
normal content plus the content of the quoted message so it can include both in
the display. When a chat message has a ref with a tag of Quote , you know it
needs to be drawn as a quoting message. Your application finds the content of
the quoted message by asking the BBM Enterprise SDK for chat message
identified by the ref messageId and then uses the content, attachments, and
70 Getting Started With BlackBerry Messenger Enterprise SDK
other properties of both messages to draw the quoting message however you
want.
As more quoting messages arrive referencing the same quoted message, the
BBM Enterprise SDK increments the count on chat message 123 and reports
the resulting property changes to your application. Your application reacts by
updating its display of the quoted message and drawing the additional quoting
messages in the chat.
Note that the quoting references are created between chat messages sent by
different users. The BBM Enterprise SDK allows cross-user references within
the same chat because it enables simple implementations of features like this
one.
The BBM Enterprise SDK comes with a predefined tag of Quote to help you
build this feature.
4-1. Quoting
Check out the Rich Chat example app for more information on using Chat
Message References to implement message quoting.
corrected.
This example only considers the simple text content of chat messages, but Chat
Message References let you build an editing feature where all application-
settable properties of chat messages can be updated. For example, you can use
Chat Message References to let the user update a picture that's attached to a
chat message.
Presume the user has already sent a chat message with id 200 with the
following relevant chat message fields.
messageId 200
Unfortunately, the user made a mistake and misspelled "great" as "greet". Your
application lets the user indicate that they want to edit their message and
resend a new copy of it, to be displayed in place of the original. To implement
this, your application forms a new chat message with the following chat
message fields.
messageId 202
ref[0].tag Edit
ref[0].messageId 200
Remember, the new chat message's messageId field (with value 202) is assigned
by the BBM Enterprise SDK when it is given the message to send. But the
messageId field in the first ref element is set by your application to refer to the
72 Getting Started With BlackBerry Messenger Enterprise SDK
In the sender and all receivers, the BBM Enterprise SDK will update chat
message 200 so that it now has a refBy list. Its chat message fields will now be:
messageId 200
refBy[0].tag Edit
refBy[0].newestRef 202
refBy[0].count 1
Note that the content field of the original chat message is unchanged. You
haven't lost access to the original text, but, by using the refBy element with the
tag Edit , you have gained access to the revised text.
To draw these chat messages, your application notices the Edit reference on
the original chat message when the BBM Enterprise SDK automatically notifies
it of a property change. In this feature, the goal is to show the most recent
version of the chat message to the user, so your application follows the
newestRef on the original message to find the source of the editing reference,
chat message 202. That chat message has a content field with the revised text,
and your application uses that to draw chat message 200 instead of using the
content field in message 200.
The user can make multiple edits to the chat message. Consider what happens
when the user then sends a second edit for the original, such as:
Chats 73
messageId 203
ref[0].tag Edit
ref[0].messageId 200
The BBM Enterprise SDK automatically updates the properties of the original
chat message so that they are:
messageId 200
refBy[0].tag Edit
refBy[0].newestRef 203
refBy[0].count 2
Again, the content of chat message 200 is unchanged, but the newestRef still
refers to a message that does contain the content that needs to be drawn.
You can decide to hide all the Edit reference source chat messages. Or, you can
decide to show them and allow user interaction with them that takes the user
back to the original message. Or, you can draw them only if the original chat
message is off screen and interacting with them could scroll back to show the
edited message.
You can also find all of the edits that have been received for a chat message. This
mechanism will be demonstrated in the next example.
Chat Message References give you a lot of flexibility in how you implement and
74 Getting Started With BlackBerry Messenger Enterprise SDK
display features because you have all the necessary information about message
relationships available, efficiently.
The BBM Enterprise SDK comes with a predefined tag of Edit to help you
build this feature.
Here is an edit in progress that fixes the typo in the word "report":
Here is the edited message after the typo has been fixed:
Check out the Announcements example app for more information on using Chat
Message References to implement message editing.
Suppose you want to allow any arbitrarily chosen message in the chat to become
a "parent" chat message and have "child" chat messages be sent and drawn
under it. Plus, you want to let any "child" message itself become a "parent" for
further nested "child" messages. In other words, you want to allow completely
threaded conversations. You can do this with the BBM Enterprise SDK.
A target chat message can have zero or more incoming references, and these
correspond to the zero or more children that a parent message can have. A chat
message can be both a source and a target message for the same tag. These are
all the building blocks necessary to represent the tree of a threaded
conversation:
application to navigate from children to parents and from parents to their most
recent child. But to draw threaded conversations, your application must be able
to find all children efficiently.
The BBM Enterprise SDK offers an efficient API function to navigate from a
parent to all of its children (with the same tag ). This function takes the tag and
messageId of the parent, and returns full information about each of the child
messages, no matter how far away in the linear history those messages are.
You can decide how to draw threaded conversations. You might allow only one
level of nesting (i.e. sidebar conversations). Or, you might allow arbitrary nesting
but only draw a single level of children by default, requiring manual user
expansion of further nesting levels. Or, you might draw the entire tree of
conversations all the time. Or you could do something completely different.
Again, the choice is up to you.
The BBM Enterprise SDK comes with a predefined tag of Thread to help you
build this feature.
Chats 77
Check out the Threaded Chat example app for more information on using Chat
Message References to build a threaded conversation experience.
Key Points
Chat Message References are implemented by the BBM Enterprise SDK, but
what they mean is up to your application.
A single chat message can refer to multiple other chat messages, as long as
each reference has a unique tag .
A single chat message can be referred to by multiple other chat messages
with the same tag , and can be referred to by more than one tag .
78 Getting Started With BlackBerry Messenger Enterprise SDK
A single chat message can both refer to others and be referred to by others.
References can only be formed to messages in the same chat.
References can only be formed to messages that are known to exist when the
referring chat message is sent. References can be formed to outgoing chat
messages that have not yet been sent.
References can be formed to chat messages from any user. Your application
can enforce per- tag rules about which references it will process. For
example, your application can prohibit (and ignore) outgoing Edit references
from users that are not the author of the referenced chat message.
Push Notifications
The BBM Enterprise SDK server supports push notifications to the BBM
Enterprise SDK mobile clients. When new chat messages and incoming calls are
pending delivery to the clients, the server can send a push notification with one
of the following mechanisms:
For Android, you must provide BlackBerry with your application's FCM (GCM)
server keys to allow the BBM Enterprise servers to initiate push requests for
your application.
For iOS, you must provide BlackBerry with your Production VoIP Services
certificates from Apple to allow the BBM Enterprise servers to initiate Apple
push requests for your application.
Chats 79
If your server will be initiating the push requests to Apple's Push or Google's
GCM/FCM servers your server will have to implement a simple REST API for the
BBM Enterprise SDK servers to invoke when push delivery to one of your users is
required, using the User Identity token supplied by your Userinfo Endpoint. In
this mechanism, you do not need to share your push credentials with BlackBerry.
Chapter
Multiple Points
of Presence
5
Multiple Points of Presence 81
The BBM Enterprise SDK allows your application to have multiple instances
running and connected at the same time for the same user. This ability is
referred to as having Multiple Points of Presence, or MPoP.
The BBM Enterprise SDK MPoP feature works by managing two distinct aspects
of a user's representation within the system.
An endpoint is the client application that runs with the credentials, access,
and capabilities of that identity.
In MPoP, each identity can run multiple endpoints simultaneously. Each endpoint
can send and receive messages, start and leave chats, mark messages as read,
etc.
Persistent endpoints are created and exist for a long time. The Android and
iOS versions of the BBM Enterprise SDK are persistent endpoints. Typically,
this type of endpoint exists until the application is uninstalled. When running,
these endpoints are always either connected or waiting to connect to the
BBM Enterprise infrastructure. The endpoints proactively receive messages
and securely store them persistently in local storage.
Ephemeral endpoints are created for a short period of time and come and go
frequently, such as when a web page is loaded and then closed. The Web and
Node versions of the BBM Enterprise SDK are ephemeral endpoints.
Ephemeral endpoints lack persistent storage and often are concerned with
only a small subset of the chats and messages that are available to an identity.
Most importantly, they aren't expected to last for a long time like an installed
82 Getting Started With BlackBerry Messenger Enterprise SDK
Persistent endpoints can be used offline even when they aren't connected to the
infrastructure. Ephemeral endpoints do not have persistent data so there is only
limited functionality when no connection to the BBM Enterprise infrastructure is
available.
Endpoint Management
The BBM Enterprise SDK limits the number of endpoints of each type that an
identity can have connected to the infrastructure at the same time. The way that
these limits are enforced reflects the differences between the two types of
endpoints.
Persistent endpoints are expected to be entities that the end user is aware of.
For example, a user knows that they have a copy of your application running on
their Android phone and another copy on their iOS tablet. Your application can
use the Endpoint Management features of the BBM Enterprise SDK to list what
endpoints are registered, give each endpoint a name and description, or
deregister an endpoint from their identity.
When a persistent endpoint is created, it first registers with the BBM Enterprise
infrastructure. If it passes various security checks, it is allowed to connect. When
the infrastructure detects that the maximum number of persistent endpoints
has already been reached, your application must deregister one or more of the
existing persistent endpoints to make room for the new one. Alternatively, your
Multiple Points of Presence 83
Persistent endpoints have the ability to list and manage ephemeral endpoints.
Ephemeral endpoints do not have the ability to list or manage any types of
endpoints.
Synchronization
All endpoints of the same identity see the same data at the same time if they are
all connected to the infrastructure. When endpoints are offline for a short time
and then come back online, they synchronize by receiving messages and other
information from the infrastructure, like a single endpoint does when it
disconnects and then reconnects.
Some state information and data is local to an endpoint and is not synchronized
with other endpoints of the same identity. Sometimes this is because the data
only pertains to the endpoint, and sometimes this is because the state hasn't
propagated to other endpoints yet.
Chats created locally on an endpoint but not yet created on the server
Chats in the Defunct state
The list of hidden chats
Old chats and old messages that are no longer available from the
infrastructure's storage
Outgoing messages that have not been posted
Failed outgoing messages
Attachments that are not yet uploaded
Attachment upload and download progress
Which attachments are downloaded
Key Synchronization
All endpoints in an identity use the same identity keys and chat keys, and all
endpoints have access to the same user keys.
If your application fetches and stores keys as directed by the BBM Enterprise
SDK, all of these keys are automatically kept in sync through the Cloud Key
Storage mechanism.
Statistics Collection 85
Chapter
Statistics
Collection
6
86 Getting Started With BlackBerry Messenger Enterprise SDK
On Android and iOS devices, the BBM Enterprise SDK records statistics as it
operates. Applications can collect these stats from the SDK and export them via
any compatible statistics aggregation system. The SDK records stats that can be
export by applications for offline analysis and reporting.
Every stat has a name property that indicates what is being measured. Some
stats have a single scalar value, such as a counter, while others have multiple
values. The following subsections describe the different types of stats that the
BBM Enterprise SDK collects.
Counter
The simplest type of stat is the scalar integer. A scalar integer has a single count
value and must be a whole number.
This type of stat is usually used for recording how many times something has
happened, in which case it's referred to as a "counter".
Example Counter
The BBM Enterprise SDK does not currently record any pure counter stats, but
the counter stat forms the basis of some of the other stat types. For example, a
stat named addParticipant could count how many times the local endpoint has
added a participant to any chat. So, if the addParticipant stat had a count of
12 , that would mean that the local endpoint has added 12 participants to chats.
Aggregation of Counters
In the above example, summing all of the addParticipant stat count values
from all of a user's endpoints would compute how many times the user added a
participant from any endpoint.
Counter Histogram
This stat is a collection of counters that work like a histogram. In addition to its
name , this stat has a set of part and count pairs that record the label and value
for each histogram bucket (i.e. each "part") of the histogram.
Only buckets with non-zero count values will be included in the histogram.
The stat named msg is a counter histogram that has a part for each of the
message tags that have been sent by the local endpoint. The count associated
with each part counts the number of times a message with that tag has been
sent.
Consider the case where the msg stat has the following values:
part count
Picture 7
Text 102
File 4
This means that the local endpoint sent 7 messages that had a tag of Picture ,
102 messages with a tag of Text , and 4 messages with a tag of File .
88 Getting Started With BlackBerry Messenger Enterprise SDK
For this example stat, the set of part values that will be collected depends on
the set of tag values that the application uses when sending messages.
Using the example above, an application can aggregate the msg histogram to
learn how many different message types a user or set of users is sending.
Size Histogram
A size histogram records information about many instances of a single type of
measurement. Specifically, it is repeatedly measuring the size, in bytes, of a
certain class of thing, such as a file attachment.
Like a counter histogram, this stat has a name and a collection of buckets, each
with a part label and a count . However, with size histograms, each bucket
represents a size milestone.
The part label of each bucket is one of a fixed set of strings such as 4K or
128M . These labels identify the largest size measurement that will be counted in
the bucket. When a size measurement is made, the count of the one largest
bucket whose part is greater than or equal to that measurement is
incremented.
The predefined bucket part labels are described below. Note that the buckets
are somewhat logarithmic, and the first set of buckets cover a smaller size range
than the next set of buckets, and so on. This allows meaningful information to be
captured about a large range of sizes without discarding useful detail at each
particular scale.
Statistics Collection 89
For example, a measurement of 120 KB would be counted in the bucket with the
part label 128K , since it is the bucket for measurements > 64 KB but <= 128 KB.
A measurement of 85 MB would be recorded in the 96M bucket since 85 MB >
80 MB and 85 <= 96 MB.
Note that the kilobytes and megabytes use a traditional definition based on
1024.
Only buckets with non-zero count values will be included in the histogram.
There is an entire set of histograms that are named using the pattern of
msg.file.<tag> , where <tag> is the tag value used by the application when it
sent a message. Each of these histograms measures the different sizes of file
attachment that the local endpoint sent along with messages of the given tag .
90 Getting Started With BlackBerry Messenger Enterprise SDK
For example, the msg.file.Picture histogram measures how large all of the file
attachments are for the Picture -tagged messages sent by the endpoint.
Consider if its buckets were recorded as follows:
part count
256K 1
2M 12
3M 44
4M 36
8M 5
This histogram records a lot of useful information about messages sent with a
tag of Picture .
Firstly, because the 256K bucket has a count value of 1, we know that there was
only 1 attachment that was less than or equal to 256 KB in size.
But, we also know that there were no attachments sent that were less than 192
KB, because if there were, they'd be recorded in smaller buckets (such as the
192K bucket, the 128K bucket, and so on). We don't see any such counters in
those smaller buckets, so we can make this conclusion.
We know that there were 13 attachments that were less or equal to 2 MB in size:
12 in the 2M bucket and 1 in the 256K bucket. We also know that the 12
attachments in the 2M bucket were larger than 256 KB, and that they were all
larger than 1 MB. Otherwise, they would have been counted in other buckets.
We also know that there were 98 attachments sent in total for messages with a
tag of Picture . To compute this, we simply sum all of the bucket count values
in the whole msg.file.Picture histogram.
Statistics Collection 91
Like the previous stat types, instances of identically named size histograms can
be aggregated across endpoints and users. By summing each bucket with the
same part label, applications can form an aggregate view of the data.
As seen in the above example, this kind of histogram supports an additional kind
of aggregation. Applications can sum all of the buckets in a single instance of the
histogram to learn how many messages with a given tag had an attachment of
any size. This is how the total of 98 was obtained, above. Applications can also
sum all of the buckets in an aggregate of this type of histogram to get a total
count for the set of endpoints and users that the aggregate represents.
The example also showed that sometimes this type of histogram is used to
define a set of related histograms. For example, in the case of those stats with a
name pattern of msg.file.<tag> , applications can also aggregate all members
of this set to find the attachment sizes across all messages with all possible tags.
By aggregating across endpoints, users, buckets, and tags, applications can join
and split the data in various interesting ways to find different kinds of patterns
and behaviors.
Stat Collection
The BBM Enterprise SDK records stats automatically. Applications that want to
use the recorded stats must collect them via the SDK's API and then export
them using a mechanism of the application's choosing.
Periodically, such as once per day, the application on each endpoint should ask
the BBM Enterprise SDK for its current list of recorded stats. The SDK will return
all non-zero counters. The application then exports these values externally, and
once that export has succeeded, it tells the SDK, which in turn resets the
counters so that the next list of recorded stats will only include values that have
been recorded since the previous list was collected.
92 Getting Started With BlackBerry Messenger Enterprise SDK
Through this simple mechanism, stats also obtain a temporal aspect: the counter
values collected "belong to" that specific collection period. The stats remain
locked to that time period and can be analyzed later against other time periods.
Applications should capture user, endpoint, and temporal information when they
collect and export stats to allow richer analysis and reporting options.
See the API Reference for each individual OS for details of how applications can
perform stats collection.
Defined Stats
The following stats are recorded by the current version of the BBM Enterprise
SDK. Stats may be removed or added in future releases as the implementation
and behaviors of the SDK change.
Setup Stats
The setup stat is a counter histogram that has buckets labeled with one of the
following part strings.
part Description
The setup.err stat is a counter histogram that has buckets labeled with part
strings taken from the BBM Setup API error reasons. This list includes the
following:
Statistics Collection 93
part Description
TemporaryServerError There was a problem with one of the setup steps but it
is possible that a retry will succeed. See the API
documentation for more details.
CertificateError There was a problem with one of the setup steps due
to a certificate error. See the API documentation for
more details.
REST Stats
Each of the stats described in this section are counter histograms that have
buckets labeled with one of the following part strings.
94 Getting Started With BlackBerry Messenger Enterprise SDK
part Description
The REST counter histograms that use the above part values are as follows.
Statistics Collection 95
name Description
Message Stats
The msg stat is a counter histogram that has buckets labeled with a dynamic set
of part strings. Each part represents a tag from a chat message that was
sent by the endpoint, so any and all tag values used by the application can
96 Getting Started With BlackBerry Messenger Enterprise SDK
appear as a part .
The count for each part records the number of messages with that tag that
have been sent by the local endpoint.
There is an entire set of histograms that are named using the pattern of
msg.file.<tag> , where <tag> is actually the tag value used by the application
when it sent a message. Each of these histograms measures the different sizes
of file attachment that the local endpoint sent along with messages of the given
tag .
There is another set of histograms that are named using the pattern of
msg.thumb.<tag> that measures the sizes of thumb attachments on each
message sent by the local endpoint.
Chapter
Peer-to-Peer
Data Streams
7
98 Getting Started With BlackBerry Messenger Enterprise SDK
With the BBM Enterprise SDK, you can create true peer-to-peer connections
that securely carry encrypted custom application data between two endpoints.
These high-bandwidth connections allow you to create secure, real-time, and
custom media streams or send application-specific protocol messages between
endpoints for any purpose.
Data Connection
A data connection is a real-time secure connection created as the result of a
data-only call.
Much like a voice or video call, the connection starts with an outgoing request to
the callee carrying an optional meta data. Typically, the meta data contains
description of the data connection for the callee to decide whether or not to
accept the request.
After the incoming request is accepted by the callee, the data connection
makes final security handshakes before making full connectivity. After full
connectivity is made, data over the connection is encrypted using DTLS-SRTP
(see crypto for details) and is peer-to-peer only.
The connection is maintained and kept active while the network path between
the two endpoints remains reachable and there is data flowing. A timeout will
terminate the connection after a number of seconds of inactivity. The number of
seconds varies depending on the platform. If your application requires the
connection to remain active, a pinging mechanism that uses a side data channel
is needed.
Both endpoints of the connection can end the connection at any time. Typically,
if there is no final acknowledgement from the receiver, the recipient should end
the connection upon final data packet arrival.
An established connection could also drop due to network issues, in which case,
Peer-to-Peer Data Streams 99
the connection state will transition to disconnected and the failure reason is
saved.
Data Channel
A data channel sends and receives data of a particular type over a data
connection .
when the first packet of the data arrives. Any subsequent data sent over the
same channel will be received by the associated receiver identified by the unique
name.
Some high level types of channels are defined in the table below. Your
application can extend the stream type for more complex use cases as needed.
File
A File type data channel allows the sending and receiving of large data blobs.
This channel automatically terminates when the file is fully transmitted.
Data
A Data type data channel allows the sending and receiving of data blobs. This
channel automatically terminates when the data blob is fully transmitted.
Stream
A Stream type data channel allows the sending and receiving of arbitrary data of
an unknown total size. Data is immediately sent without further buffering, and
the channel stays open until the data connection terminates.
Security 101
Chapter
Security
8
102 Getting Started With BlackBerry Messenger Enterprise SDK
The BBM Enterprise SDK provides secure messaging and encryption for chats,
voice calls, and video calls. While the BBM Enterprise SDK encrypts and signs
data before it leaves the endpoint, your application is responsible for distributing
security keys.
The BBM Enterprise SDK includes APIs to facilitate exporting keys out of the
BBM Enterprise SDK, and importing keys into the BBM Enterprise SDK.
To ensure that your application may use any combination of the SDKs to fulfill its
Security 103
needs, a common storage schema for the encryption, signing, and symmetric
keys must be maintained across all product lines. For example, both the Android
and iOS versions of an application using the BBM Enterprise SDK must be able to
exchange keys, and users must be able to switch between those two versions
without losing their keys.
Requirements
The cloud storage system must authenticate users that are using tokens or
credentials managed by your application
The cloud storage system must allow a user to read and write private data
The cloud storage system must allow a user to publish data that other users
can read only
Private data
The cloud storage solution must include restricted read and write access (private
data can only be read or written if the owner of that data is logged into the app).
The following private data must be stored:
104 Getting Started With BlackBerry Messenger Enterprise SDK
Public data
The cloud storage solution must include public read access (where public data
can only be read by authenticated users within the ecosystem), and restricted
write access (where private data can only be written if the owner of that data is
logged into the application). The following public data must be stored:
Your application should secure exported private key data with a per-user secret
before storing it in the cloud.
The example applications provided with the BBM Enterprise SDK protect all
private key with the following steps:
2 Use the management keys to encrypt and create a MAC for each private
key data value being stored (AES-256 CTR and HMAC SHA-256 are used in the
provided examples).
3 Store the encrypted bytes, nonce (initialization vector) and MAC for each
key and HMAC key from a user provided password. The example applications
5 Use the keys derived by the KDF to encrypt and create a MAC of the
6 Store the encrypted management key data created in step 5 in the cloud.
7 To recover the private key data use the KDF as in step 3 to re-create
derived keys. Use the derived keys to decrypt the management keys. The
management keys can be used to decrypt the BBM Enterprise SDK private key
data.
Cryptography
The BBM Enterprise SDK was designed to comply with the following three
security principles:
106 Getting Started With BlackBerry Messenger Enterprise SDK
Messages are digitally signed, so you're assured of who sends each message
in your application.
Messages are encrypted, so you're assured that only the intended recipient
can read the message.
Messages are subjected to integrity signature checks, so you're assured the
message isn't modified in transit.
The BBM Enterprise SDK will generate two private and public key pairs for each
user, using ECDSA secp521r1: one key pair for signing and one key pair for
encryption. The public signing and encryption keys are distributed to each user
that messages will be exchanged with via BBM SDK Protect - Cloud Key Storage.
All sent messages are encrypted using a per-message key, and signed by the
sender's private signing key. All received messages are verified using the
sender's public signing key, and decrypted using a per-message key. The per-
message keys are generated differently for Identity and Chat messages and are
described below.
The message counter is incremented for each message and the nonce is
randomly generated for each message. These values are sent in the plaintext
Security 107
The derived key is used to encrypt/decrypt the Identity message using AES CTR
mode.
Mathematical Notation
Chat messages are encrypted using a per-message key generated by both the
sender and recipient. The chat key is sent to the user as a protected identity
message, requesting that the user to join the chat. The chat key is shared via an
invite that is sent as a protected Identity message for the user to join the chat.
The chat key is combined with the message counter and nonce to make the
secret used to derive a 32-byte key using ANSI-X9.63-KDF.
The message counter is incremented for each message, while the nonce is
randomly generated for each message. These values are sent in the plaintext
portion of the protected message.
The derived key is used to encrypt/decrypt the Mailbox message using AES CTR
108 Getting Started With BlackBerry Messenger Enterprise SDK
mode.
Mathematical Notation
Signing
Before identity and chat messages are signed, the encrypted data is combined
with the message counter, nonce, and identity information. It is then signed with
the sender's private signing key, using ECDSA secp521r1 SHA-512. The
signature information is sent in the plaintext portion of the protected message,
to be verified by the recipient. The recipient combines the received encrypted
data, message counter and nonce, and identity information to verify it using
ECDSA secp521r1 SHA-512 with the sender's public signing key.
Mathematical Notation
The BBM Enterprise SDK provides end-to-end security for a real-time video,
voice and peer-to-peer streams, allowing users to place secure voice or video
Security 109
calls or share data. Encryption keys are exchanged using DTLS-SRTP and are
used to secure the SRTP stream of media or the SCTP stream of data.
Additionally, DTLS fingerprints are encrypted and signed using the identity keys
of both participants in the video, voice call or data sharing session, adding
another layer of security and identity verification. Subsequent encryption of the
real-time media stream and peer-to-peer stream follows SRTP specification,
using AES 128 in CTR mode or, in the most recent versions, AES 256 in GCM
mode as a cipher.
WebCrypto
There are open source third-party shim libraries that provide pure JavaScript
implementation of the WebCrypto interface and fill in any missing pieces that
the browser doesn't support natively, for greater cross browser support. We do
not include such a shim, do to the reduced security compared to a native
implementation.
Primitives
The following WebCrypto primitives are used by BBM Enterprise SDK for
JavaScript:
Sign
Verify
Encrypt
crypto.subtle.encrypt(
{
name: 'AES-CTR',
counter: buildInitVector(nonce),
length: 128
},
derivedKey, plaintext
);
Decrypt
crypto.subtle.decrypt(
Security 111
{
name: 'AES-CTR',
counter: buildInitVector(nonce),
length: 128
},
derivedKey, ciphertext
);
Diagrams
When a user sends a message, the BBM Enterprise SDK performs the following
actions:
1 Establishes a 256-bit AES message key from the session key and unique
keying material
2 Encrypts the message with the symmetric key using AES in CTR mode
5 Signs the hash with the sender’s private signing key (ECC-521) using
ECDSA
When a user receives a message, the BBM Enterprise SDK performs the
following actions:
3 Verifies the message signature using the sender’s public key and the
4 Derives the message key from the session key and the unencrypted keying
material
End-to-End View
Conclusion
This wraps up our getting started guide to the BlackBerry Messenger Enterprise
SDK. You can find more information in the official documentation, and be sure to
check out the example applications to get ideas for how to integrate the SDK
into your projects.