Skip to main content

SDK Setup Guide


Install the SDK

Octopus is available on Maven Central. Add the dependencies to your build.gradle file:

dependencies {
// Core SDK functionnalities
implementation("com.octopuscommunity:octopus-sdk:x.x.x")
// SDK UI Components (optional)
implementation("com.octopuscommunity:octopus-sdk-ui:x.x.x")
}

See the Octopus SDK GitHub Release section to get the latest published version.


Use the SDK

As early as possible in your code, you should initialize the OctopusSDK object.

This object is expecting two things:

  • the Octopus Community API key
  • the connection mode

You need to know the app managed fields (also called as associated fields) that your community is configured for.

As a reminder, every associated profile fields (nickname, picture and/or bio) of your users will be used in the Octopus Community profile of this user. The user will only be able to change it in your profile edition interface and the data will be synced to its community profile.
On the oposite, every dissociated profile fields will only be used as prefilled values during Octopus profile creation. After that, if a user changes its nickname in your app, it won't be reflected in Octopus Community, and the user will be able to change its community nickname in the community part.

At least one app managed field

If your community is having at least one associated field, you will have to create the SSO connection mode with the list of the associated fields.

Call the OctopusSDK initialization function in your Application's onCreate() block:

class YourApplication : Application() {

override fun onCreate() {
super.onCreate()

OctopusSDK.initialize(
context = this, // Application Context
apiKey = "YOUR_API_KEY",
connectionMode = ConnectionMode.SSO(
// The list of associated fields
appManagedFields = setOf(ProfileField.NICKNAME, ProfileField.PICTURE)
)
)
}
}

OR

No app managed fields

When there is no app managed fields (i.e. all fields are dissociated), the API is simpler since you only have to configure it in SSO connection mode.

Call the OctopusSDK initialization function in your Application's onCreate() block:

class YourApplication : Application() {

override fun onCreate() {
super.onCreate()

OctopusSDK.initialize(
context = this, // Application Context
apiKey = "YOUR_API_KEY",
connectionMode = ConnectionMode.SSO()
)
}
}

Your application is managing the connection status of the user and inform the Octopus SDK when the user is connected/disconnected

The connectUser API lets you pass the userId. This userId is the string that will identify your user for Octopus. It needs to be unique and always refer to the same user.

You can also pass profile information (nickname, bio, picture). These fields will be used differently depending of wether the field is associated (i.e. in the app managed fields that you provided during SDK initialization) or not:

  • if the field is associated, each time the connectUser function will be called, Octopus will update the field in the user's community profile with the data you provided. Hence, the field in the community profile of the user will always be the same value as in its app profile

  • if the field is not associated, the data you provided will only be used to fill the community profile until the user edits its community profile. Once its done, their community profile remains separate from yours, meaning any updates made to your profile will not be reflected in theirs, and vice versa.

This is why you should call the connectUser function as soon as the user profile changes.

Client User Token

For security reasons, to ensure that the connected user is legitimate, the API informing the SDK of a user’s connection includes a callback that provides a signed token for authentication. In other words, the SDK will request a token from you when needed to authenticate the user. Therefore, you must add a route like /generateOctopusSsoToken to your backend to generate this token. Follow the Generate a signed JWT for SSO guide for more information

Inform the SDK that your user is connected:

≥ 1.6.0
OctopusSDK.connectUser(
user = ClientUser(
userId = yourUserId, // Unique identifier of your user
profile = ClientUser.Profile(
nickname = yourUserNickname, // nickname is String?
bio = yourUserBio, // bio is String?
picture = yourUserPicture // A Remote URL or a Local Uri
)
),
tokenProvider = {
// Fetch asynchronously this user token (suspended callback)
// by calling your /generateOctopusSsoToken route
}
)
tip

Check the Community ViewModel Sample for a complete use case.

Deprecated < 1.6.0
OctopusSDK.connectUser(
user = ClientUser(
userId = yourUser.id,
profile = ClientUser.Profile(
nickname = yourUser.name,
bio = yourUser.bio,
picture = yourUser.picture,
// Age Information:
// - LegalAgeReached = Your user is more than 16 years old
// - Underaged = Your user is less than 16 years old
// - null = You don't know
ageInformation = AgeInformation.LegalAgeReached
)
),
tokenProvider = {
// Return asynchronously this user token (suspended callback)
// by calling your /generateOctopusSsoToken route
}
)
  • Inform the SDK that your user is disconnected:
OctopusSDK.disconnectUser()
  • Optional: Monitor whether the user is connected to the Octopus platform:
OctopusSDK.isUserConnected

Display the Octopus Community UI

Now that you have the SDK properly configured, you can add a button in your app that opens the Octopus Community UI.

  1. Add the OctopusHomeContent composable to your community screen.
OctopusTheme(...) { // Customize the Octopus Theme here
OctopusHomeContent(
modifier = Modifier.fillMaxSize(),
navController = navController, // Your main NavHostController
onNavigateToLogin = {
// This block will be called when OctopusSDK needs a logged-in user.
// You should launch your login process here.
// Example: navController.navigate(LoginRoute)
// Once the user is logged in, you need to call OctopusSDK.connectUser(...) to link
// them with Octopus
},
// Optional: If your community has at least one associated field:
onNavigateToProfileEdit = { profileField ->
// This block will be called when the user tries to modify some fields related
// to their profile.
// When this block is called, you should open your profile edition screen.
// Example: navController.navigate(ProfileScreen(focusNickname = fieldToEdit == ProfileField.NICKNAME))
// Once the user has edited their profile, you should call OctopusSDK.connectUser(...) to update the Octopus profile.
}
)
}
tip

Check the Community Screen Sample for basic usage.

  1. Declare other Octopus sub-screens in your main NavHost:
NavHost(...) { // Your main NavHost
octopusComposables(
navController = navController, // Your main NavHostController
onNavigateToLogin = { ... },
onNavigateToProfileEdit = { ... }
) { backStackEntry, content ->
// Customize the Octopus Theme possibly based on a specific Octopus Screen here
OctopusTheme(...) {
content()
}
}
}

This function registers multiple composable() destinations in your NavGraphBuilder for adding the Octopus SDK navigation flow to your app.

tip

Modify bottom safe area

According to your app, you might want to add a bottom padding to the Octopus UI content.

This can be done by using the contentPadding parameter of the OctopusHomeContent composable.

OctopusHomeContent(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(bottom = 10.dp) // This will add a 10dp padding at the bottom of the Octopus UI
// ...
)

To see a full example of how you can achieve that, you can check the Floating Bottom Navigation Bar Sample.


Modify the theme

The Octopus SDK lets you modify its theme so its UI looks more like yours.

You can modify:

  • the colors:

    Please pass colors without any transparency.

    • the primary colors (a main color, a low contrast and a high contrast variations of the main color). If you do not pass a custom value for it, black/white default values will be used.
    • the color of the elements (mostly texts) displayed over the primary color. If you do not pass a custom value for it, white/black default value will be used.
  • the fonts. You can customize the styles (title1, body2, caption1...) used in the sdk. If you do not pass a custom value for it, default value will be used.

  • the logo. This is an image displayed on the Octopus home page and profile creation view. If you do not pass a custom image for it, Octopus logo value will be used.

  • (⚠ Android only) the TopAppBar. You can customize the appearance, title, navigation icons, actions, and colors of the TopAppBar. If you do not pass a custom configuration for it, default TopAppBar will be used.

By default, Octopus will rely on your application's MaterialTheme.colorScheme, but you can customize the UI more precisely by surrounding composables with the OctopusTheme:

To do that, you can override the theme by passing it as an environment object:

octopusComposables(
navController = navController
) { backStackEntry, content ->
OctopusTheme(
colorScheme = if (isSystemInDarkTheme()) {
octopusDarkColorScheme(
primary = yourDarkPrimaryColor, // Default: MaterialTheme.colorScheme.primary
primaryLow = lowContrastVersionOfYourPrimaryColor, // Default: MaterialTheme.colorScheme.primaryContainer
primaryHigh = highContrastVersionOfYourPrimaryColor, // Default: MaterialTheme.colorScheme.inversePrimary
onPrimary = yourDarkOnPrimaryColor, // Default: MaterialTheme.colorScheme.onPrimary
background = yourDarkBackgroundColor // Default: MaterialTheme.colorScheme.background
// See the complete list in the sources documentation
)
} else {
octopusLightColorScheme(
primary = yourLightPrimaryColor, // Default: MaterialTheme.colorScheme.primary
primaryLow = lowContrastVersionOfYourPrimaryColor, // Default: MaterialTheme.colorScheme.primaryContainer
primaryHigh = highContrastVersionOfYourPrimaryColor, // Default: MaterialTheme.colorScheme.inversePrimary
onPrimary = yourLightOnPrimaryColor, // Default: MaterialTheme.colorScheme.onPrimary
background = yourLightBackgroundColor // Default: MaterialTheme.colorScheme.background
// See the complete list in the sources documentation
)
},
typography = OctopusTypographyDefaults.typography(
title1 = yourCustomTitle1Style, // Default: TextStyle(fontSize = 26.sp)
title2 = yourCustomTitle2Style // Default: TextStyle(fontSize = 22.sp)
// See the complete list in the sources documentation
),
images = OctopusImagesDefaults.images(
logo = painterResource(R.drawable.your_custom_logo) // Default: null
)
)
// ... Check the complete parameters list in the sources documentation
) {
content()
}
}
tip

Use the OctopusThemeGenerator to configure your Community theme with a live preview of the various Octopus screens.

All parameters of the theme have default values. Only override the ones that you want to customize. In the following example, you are creating an OctopusTheme with default colors, default fonts except for the title1, and a custom logo:

OctopusTheme(
typography = OctopusTypographyDefaults.typography(
title1 = TextStyle(fontFamily = FontFamily.SansSerif, fontSize = 24.sp)
),
images = OctopusImagesDefaults.images(
logo = painterResource(R.drawable.your_custom_logo)
)
) {
OctopusHomeContent(...)
}

Here is a summary of the impacts of the theme you choose: Light Mode Dark Mode

Here is a summary of the text styles used in the main screens of the SDK: Text Styles

Customize the TopAppBar

You can customize the appearance of the TopAppBar in the Octopus SDK screens by providing your own OctopusTopAppBar configuration when setting up the theme. We highly encourage you to choose a short text title (less than 18 characters).

OctopusTheme(
...
topAppBar = OctopusTopAppBarDefaults.topAppBar(
title = { text ->
OctopusTopAppBarTitle(
text = "Your TopAppBar Title", // Default: text
logo = painterResource(R.drawable.your_logo), // Default: OctopusTheme.images.logo
textStyle = yourTopAppBarTextStyle // Default: LocalTextStyle.current
)
},
colors = OctopusTopAppBarDefaults.colors(
containerColor = yourTopAppBarBackgroundColor, // Default: OctopusTheme.colorScheme.background
contentColor = yourTopAppBarContentColor // Default: OctopusTheme.colorScheme.gray900
),
navigationIcon = { type, onClick ->
IconButton(onClick = onClick) {
Icon(
imageVector = when (type) {
NavigationIconType.Back -> YourBackIcon
NavigationIconType.Close -> YourCloseIcon
},
contentDescription = when (type) {
NavigationIconType.Back -> "Navigate back"
NavigationIconType.Close -> "Close"
}
)
}
},
// ... Check the complete parameters list in the sources documentation
)
)
info

The OctopusTopAppBar will automatically use your theme's color scheme if no specific colors are provided, ensuring consistency across your app.

Advanced Screen-Based Theming (Android only)

For more complex theming scenarios, you can customize any aspect of the Octopus theme (colors, typography, images, TopAppBar) based on the current screen:

octopusComposables(
navController = navController
) { backStackEntry, content ->
OctopusTheme(
colorScheme = when {
// Post Details with branded theme
backStackEntry.destination.hasRoute<OctopusDestination.PostDetails>() -> {
octopusColorScheme().copy(
background = if (isSystemInDarkTheme()) Color.Black else Color.White
)
}
else -> octopusColorScheme()
},
topAppBar = when {
// Home screen with custom TopAppBar theme
backStackEntry.destination.hasRoute<OctopusDestination.Home>() -> {
OctopusTopAppBarDefaults.topAppBar(
title = { text ->
OctopusTopAppBarTitle(text = "My Community")
}
)
}
else -> OctopusTopAppBarDefaults.topAppBar()
}
) {
content()
}
}

Push Notifications ≥ 1.4.0

To increase user engagement, you can provide informations to the Octopus SDK so your users can receive push notifications when other users interact with them inside the community.

note

Octopus SDK is not asking for push notification permissions, we let you handle that part where it makes more sense in your app.

If your app does not support Push Notifications yet, you can follow the official Firebase documentation.

Our servers need your service account's private key file to be authorized to send notifications to your app on your behalf.

If you don't have this JSON file yet, follow this tutorial
  • In the Firebase console, open Settings > Service Accounts
  • Click Generate New Private Key, then confirm by clicking Generate Key.
  • Securely store the JSON file containing the key.

More information can be found in the official Firebase documentation

Please send the json file using the online form sent by the Octopus team.

warning

This JSON file is different from the one you are using to configure Firebase in your app (google-services.json)

Once your project is correctly set up for push notifications, you should forward the Firebase Cloud Messaging Token (FCM Token) to the Octopus SDK:

class MessagingService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
super.onNewToken(token)

// Register the new token with Octopus
OctopusSDK.registerNotificationsToken(token)
}
}
note
You are in charge of requesting the Notification permission and referencing your messaging service:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
if (checkSelfPermission(POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
// Request launcher for notification permission
registerForActivityResult(
contract = ActivityResultContracts.RequestPermission(),
callback = {
FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
if (task.isSuccessful) {
OctopusSDK.registerNotificationsToken(task.result)
}
}
}
).launch(POST_NOTIFICATIONS)
}
<service
android:name=".notifications.MessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>

When you receive a notification message, first check if it is an Octopus notification by calling:

override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)

val isOctopusNotification = remoteMessage.data.isOctopusNotification
if (isOctopusNotification) {
// ... Handle the Octopus notification here (see below)
}
}

If it's the case, display the Octopus notification using the Notification Manager:

val octopusNotification = OctopusSDK.getOctopusNotification(data = remoteMessage.data)
if (octopusNotification != null) {
notificationManager.notify(
octopusNotification.id,
Notification.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_notification)
.setColor(getColor(R.color.accent))
.setAutoCancel(true)
// Extension function to extract the title, text and deep link from the OctopusNotification
.setOctopusContent(
context = this,
activityClass = MainActivity::class,
octopusNotification = octopusNotification
).build()
)
}

Then you can display the notification's targeted Octopus UI from the octopusNotification.deepLink:

intent.data?.let { uri -> navController.navigate(deepLink = uri)}
note
  • The activityClass must be the one containing the compose content with the octopusNavigation() subgraph.
  • The setOctopusContent function is based on a deep link mechanism that will automatically launch the activity and navigate to the corresponding screen within the Octopus navigation graph.
  • You can also handle the content manually by using the OctopusNotification's title, body, and linkPath fields and configuring your own PendingIntent.

Not seen notifications ≥ 1.3.0

To increase user engagement, let your users know that they have new notifications from the Octopus notification center. Displaying a badge with the number of new notifications in your app can be a great way to suggest your users to look at what's new in the community again.

To do that, the Octopus SDK exposes a val notSeenNotificationsCount: Flow<Int> that you can collect:

OctopusSDK.notSeenNotificationsCount.collect {}

If you want to update this value with the latest count, simply call:

OctopusSDK.updateNotSeenNotificationsCount()

To see a full example of how you can achieve that, you can follow how it is done in the Samples, in the Octopus Sample app.


Analytics

Octopus Community provides analytics to help you better understand your users' behavior within the community. To improve the quality of these analytics, we offer features that allow you to provide additional information about your users.

Custom events ≥ 1.4.0

You can tell the SDK to register a custom event. This event can be merged into the reports we provide.

OctopusSDK.track(
event = TrackerEvent.Custom(
name = "Purchase",
properties = mapOf(
"price" to TrackerEvent.Custom.Property(
value = String.format(Locale.US, "%.2f", 1.99)
),
"currency" to TrackerEvent.Custom.Property(value = "EUR"),
"product_id" to TrackerEvent.Custom.Property(value = "product1")
)
)
)

Community Visibility ≥ 1.3.0

If you enable access to the community for only a subset of your users and want the analytics we provide to take this into account, you can inform the SDK accordingly.

This information is reset at each SDK launch so be sure to call the function everytime and as soon as possible after SDK init.

warning

This section is only usefull when the host app (i.e. your app) manages its own A/B testing logic. Call this if your app is running its own A/B test and you want Octopus to log whether a given user is in the "community-enabled" or "control" group. This is useful for reporting and engagement analytics, but does not change the SDK’s runtime behavior.

≥ 1.6.0
OctopusSDK.trackAccessToCommunity(hasAccess = canAccessCommunity)
Deprecated < 1.6.0
OctopusSDK.setHasAccessToCommunity(canAccessCommunity)

Octopus Events ≥ 1.9.0

As what the user does inside the Octopus UI is pretty opaque for you, we provide a way to register to be informed about events done by the user occuring inside Octopus.

If you have your own tracking service, you can use this publisher to listen to events that occured inside the Octopus UI part and feed your tracking service with them.

Here is the list of all events and their params that are emitted from the Octopus SDK

Content

postCreated

Sent when a post has been created by the current user.

Params:

  • postId: String — The id of the post.
  • content: PostContent — Content of the post. PostContent is a set of text, image and poll indicating the content of the post.
  • topicId: String — The id of the topic to which the post has been linked.
  • textLength: Int — The length of the text of this post.

commentCreated

Sent when a comment has been created by the current user.

Params:

  • commentId: String — The id of the comment.
  • postId: String — The id of the post in which the comment has been posted.
  • textLength: Int — The length of the text of this comment.

replyCreated

Sent when a reply has been created by the current user.

Params:

  • replyId: String — The id of the reply.
  • commentId: String — The id of the comment in which this reply has been posted.
  • textLength: Int — The length of the text of this reply.

contentDeleted

Sent when a post, a comment or a reply has been deleted by the current user.

Params:

  • contentId: String — The id of the content that has been deleted.
  • kind: ContentKind — The kind of content. Can be post, comment or reply.

reactionModified

Sent when a reaction is modified (added, deleted or changed) on a content by the current user.

Params:

  • previousReaction: ReactionKind? — The previous reaction. Can be null.
  • newReaction: ReactionKind? — The new reaction. If null, it means that the reaction has been deleted. ReactionKind is either heart, joy, mouthOpen, clap, cry or rage.
  • contentId: String — The id of the content.
  • contentKind: ContentKind — The kind of content. Can be post, comment or reply.

pollVoted

Sent when the current user votes for a poll.

Params:

  • contentId: String — The id of the content (i.e. the post).
  • optionId: String — The id of the option voted by the user.

contentReported

Sent when a content has been reported by the current user.

Params:

  • contentId: String — The id of the content.
  • reasons: [ReportReason] — The reasons of reporting this content.

Gamification

gamificationPointsGained

Sent when gamification points are gained. Please note that only the points triggered by an in-app action are reported live.

Params:

  • pointsGained: Int — The points that have been added.
  • action: GamificationPointsGainedAction — The action that led to gaining points.

gamificationPointsRemoved

Sent when gamification points are removed. Please note that only the points triggered by an in-app action are reported live. For example, if a post of this user gets moderated, you won't receive the information about points removed.

Params:

  • pointsRemoved: Int — The points that have been removed.
  • action: GamificationPointsRemovedAction — The action that led to losing points.

Navigation & UI

screenDisplayed

Sent when the user navigates to a given screen.

Params:

  • screen: Screen — The screen that has been displayed.

    Screen can be:

    • postsFeed — The posts feed (i.e. list of posts)

      Params:

      • feedId: String — The id of the feed that is displayed.
      • relatedTopicId: String? — The id to the topic that is related to this feed. Null if the feed is not representing a topic or is multi-topic (for example, the feed "For You").
    • postDetail — The post detail screen with the list of comments

      Params:

      • postId: String — The id of the post that is displayed.
    • commentDetail — The comment detail screen with the list of replies

      Params:

      • commentId: String — The id of the comment that is displayed.
    • createPost — The create post screen

    • profile — The user profile screen

    • otherUserProfile — The profile screen of another Octopus user

      Params:

      • profileId: String — The id of the profile that is displayed.
    • editProfile — The edit profile screen

    • reportContent — The report content screen

    • reportProfile — The report profile screen

    • validateNickname — The validate nickname screen (displayed after a user with a non-modified nickname has created a post)

    • settingsList — The settings screen

    • settingsAccount — The account settings screen. Only visible if the SDK is configured in Octopus authentication (not SSO)

    • settingsAbout — The about settings screen

    • reportExplanation — The report explanation screen

    • deleteAccount — The delete account screen. Only visible if the SDK is configured in Octopus authentication (not SSO)


notificationClicked

Sent when the user clicks on an internal notification (from the Octopus Notification Center).

Params:

  • notificationId: String — The id of the notification.
  • contentId: String? — The target content id. Can be null if the notification does not target a content.

postClicked

Sent when the user clicks on a post.

Params:

  • postId: String — The id of the post.
  • source: PostClickedSource — The source of the click. Can be feed (if the post was displayed in the posts feed) or profile (if the post was displayed in a user profile posts list).

translationButtonClicked

Sent when the user clicks on a translation button.

Params:

  • contentId: String — The id of the content.
  • viewTranslated: Bool — Whether the user wants to display the translated or the original content.
  • contentKind: ContentKind — The kind of content. Can be post, comment or reply.

commentButtonClicked

Sent when the user clicks the comment button of a post.

Params:

  • postId: String — The id of the post.

replyButtonClicked

Sent when the user clicks the reply button of a comment.

Params:

  • commentId: String — The id of the comment.

seeRepliesButtonClicked

Sent when the user clicks on the replies button of a comment.

Params:

  • commentId: String — The id of the comment.

Profile

profileModified

Sent when the profile is modified by the user.

Params:

  • nickname: ProfileFieldUpdate<NicknameUpdateContext> — The nickname update information. Either unchanged or changed.

  • bio: ProfileFieldUpdate<BioUpdateContext> — The bio update information. Either unchanged or changed.

    BioUpdateContext params:

    • bioLength: Int — The length of the bio.
  • picture: ProfileFieldUpdate<PictureUpdateContext> — The picture update information. Either unchanged or changed.

    PictureUpdateContext params:

    • hasPicture: Int — Whether the user has added a picture or deleted the existing one.

Session

sessionStarted

Sent when an Octopus UI session is started.

Params:

  • sessionId: String — The id of the session.

sessionStopped

Sent when an Octopus UI session is stopped (call either when the Octopus UI is closed or when the app is put in background).

Params:

  • sessionId: String — The id of the session.

Types

ContentKind

Can be post, comment or reply.


ReactionKind

Can be heart, joy, mouthOpen, clap, cry or rage.


PostContent

A set of text, image and poll indicating the content of the post.

Here is how to listen to these events:

// Listen to Octopus Events and convert into events for your analytics tool,
// for example here with Firebase Analytics
OctopusSDK.events.collect { event ->
when(event) {
is PostCreated -> {
FirebaseAnalytics.getInstance().logEvent(
name = "post_created",
params = Bundle().apply {
putString("topic", event.topicId)
putInt("text_length", event.textLength)
putBoolean("has_poll", event.content.contains(POLL)
putBoolean("has_image", event.content.contains(IMAGE)
}
)
}
else -> { //... }
}
}

Bridges ≥ 1.5.0

Octopus provides a way of linking a specific object in your app (e.g. a page, a product, any kind of content) to a dynamic post in the community, created automatically. We call this a bridge. To create a bridge, your content (an article, a product, etc.) must have a unique identifier. This ID will be used to link your content to the post. It will also allow users in the Octopus Community to directly view your content.

The bridge process involves four main steps:

Step 1: Prepare the post data Use the SDK to get (or create) the ID of the post related to your content. First get from the SDK the id of the post to display. The SDK will create the post if it is not already created. To do that, call the dedicated API and pass the required data:

  • Content id (called clientObjectId) that the post will be about
  • Text of the post. It must be between 10 and 5000 (3000 before the 1.8.0) characters.
  • Catchphrase (optional). It will be displayed below the title, in bold. You can use something like "What do you think about this?". It must be less than 84 characters and we recommand between 6 and 38 characters.
  • Image for the post (optional). You can either pass a remote image using an URL or a local image. The image must respect these requirements:
    • File size must be less than 50Mb
    • File format must be jpg or png
    • Image sides must be between 50px and 4000px, with a max ratio of 32:9 (bigger side / smaller side)
    • If you pass a remote image, the resource should be public
  • Text of the button that will invite your users to display your content (optionnal). You can use something like "Buy it" if your content is a purchasable product, or "Read the article" if it is a press article. When the button containing this text will be tapped, the SDK will ask you to display your content. If no text is provided, the button won't be displayed. It must be less than 28 characters, we recommand between 4 and 28 characters.
  • Topic id (optional). This is the id of the topic that you want the post to be labelled with. If not provided, the topic will be automatically set according to your community settings. You can retrieve the list of the available topics with the dedicated API (see below).
// Get cached topics
OctopusSDK.topics.collect { topics ->
// List of available topics
}

// Fetch latest topics from server
OctopusSDK.fetchTopics()
  • Signature (optional). For security reasons, to ensure that the request is coming from you, you can provide a signature. The need for the signature is based on your community settings, we highly encourage you to enable this security check by contacting us. Therefore, you must add a route like /generateBridgeSignature to your backend to generate this token based on the same algorithm as generating the token for users (sub is not required for this process).
val clientPost = ClientPost(
objectId = "recipe-129302938", // A unique identifier for your content
text = "The perfect Canelés", // Between 10 and 5000 chars
attachment = Image.Remote(url = imageUrl), // You can also pass Image.Local(uri)
topicId = foodRecipeId, // The id of the Octopus topic. Null if default.
catchPhrase = "Tried the canelés? Tell us how good they were!", // Less than 84 characters
viewObjectButtonText = "Read the recipe", // Less than 28 characters
signature = token
)

Step 2: Get the post ID

Calling the API with the previously created post data will return a post ID. With this ID, you can display the post using the Octopus UI. If the post is not created, this API will create it, otherwise it won't change its content.

val result = OctopusSDK.fetchOrCreateClientObjectRelatedPost(clientPost)
when (result) {
is OctopusResult.Success -> {
val post = result.data
val postId = post.id
// Navigate to the post or handle success
}
is OctopusResult.Error -> {
// Handle error
}
}

Step 3: Handle user interaction

Optionally, you can register a callback to be notified when a user wants to view your content from a bridge post. The SDK will provide the clientObjectId so you can open the appropriate content.

// In your NavHost setup
octopusComposables(
// ...
onNavigateToClientObject = { objectId ->
// Display the content that has the given objectId
}
)

Step 4: Display the post

Using the post id, you can display it directly after the user taps a button on your object page:

OctopusPostDetailsContent(
modifier = Modifier.fillMaxSize(),
postId = postId,
// ...
)

Optional: accessing live data about the post > 1.7.0

Additionaly to the post id, we also provide more information about the post. You can access and display the reaction count that all Octopus users did on the post, the number of comments and the number of views.

You can retrieve an object that references the post and that will be updated with the current value and as soon as you call the fetchOrCreateClientObjectRelatedPost function.

OctopusSDK.getClientObjectRelatedPostFlow(clientObjectId = "recipe-129302938")
.filterNotNull()
.collect { post ->
val reactions = post.reactions // Reactions is List<OctopusReactionCount> and OctopusReactionCount is a data class with a reaction and a count
val commentCount = post.commentCount
val viewCount = post.viewCount
}

Optional: reading the current user's reaction ≥ 1.9.1

You can read the current user's reaction on a bridge post from the post object. This is useful if you want to display the user's reaction in your own UI outside of Octopus.

OctopusSDK.getClientObjectRelatedPostFlow(clientObjectId = "recipe-129302938")
.filterNotNull()
.collect { post ->
val userReaction = post.userReactionKind // OctopusReactionKind? — null if the user has not reacted
}

Optional: setting a reaction on a bridge post ≥ 1.9.1

If you display bridge post data in your own UI, you can let users react to the post without entering the Octopus Community screen. Pass a reaction kind to set a reaction, or pass null/nil to remove it.

Available reaction kinds: heart ❤️, joy 😂, mouthOpen 😮, clap 👏, cry 😢, rage 😡.

// Set a reaction
OctopusSDK.setReaction(
reaction = OctopusReactionKind.Heart,
clientObjectRelatedPostId = "recipe-129302938"
)

// Remove the reaction
OctopusSDK.setReaction(reaction = null, clientObjectRelatedPostId = "recipe-129302938")

To see a full example of how you can achieve that, you can follow how it is done in the Samples:

in the Octopus Sample app. The MainViewModel is in charge of preparing the client post and getting the post.


Octopus A/B Testing ≥ 1.6.0

The A/B test feature lets you measure the impact of the community on your app usage by splitting your audience into two cohorts:

  • Test group: a portion of users (e.g., 30%) with full access to the community.
  • Control group: the remaining users (e.g., 70%) without access. For them, when they tap the community button, Octopus displays a screen: “The community is not available yet for you, please come back later.” In Octopus Analytics, you’ll then see clear comparisons between these two cohorts in terms of app session volume and retention.

Even if this A/B Test is totally internal, we let you know whether the user can access the community or not (i.e., in which group the user is).

We also let you override the group assigned to the connected user. This can be useful during your tests to check what will see the users of each group or even to provide or disable access to some given users.

Use this method when you need to guarantee that the user’s community access is enforced by Octopus, regardless of internal A/B testing rules.

Here is how to override the user community access:

OctopusSDK.overrideCommunityAccess(hasAccess = canAccessCommunity)

Here is how to know whether the current user has access to the community. It is a published value that is updated as soon as the user group changes. ≥ 1.6.1

OctopusSDK.hasAccessToCommunity.collect { hasAccessToCommunity ->
// Use the hasAccessToCommunity new value
}

To see a full example of how you can achieve that, you can follow how it is done in the Samples, in the Octopus Sample app.


Intercept URL openings ≥ 1.9.0

Users can open links from the SDK. These URLs can either be opened from a link tapped on a post/comment/reply content, or from a Post with CTA button tap. These links will be opened by default in the web browser. Octopus SDK lets you the ability to catch these URL opening and decide what to do with the URL. Either using it yourself to do whatever you want or let Octopus handle them. You could, for example, catch any URL opening your website and instead opening the correct page in your own app.

// Set the callback that will be called when a user tries to open a link inside the community.
// This link can come from a Post/Comment/Reply or when tapping on a Post with CTA button.
octopusComposables(
// ...
onNavigateToUrl = { url ->
val uri = url.toUri()
if(uri.host == "www.yourdomain.com" && uri.path == "/contact") {
// Open the contact page inside the app
...

// Link has been handled by app, let the Octopus SDK know that it should do nothing more
return HandledByApp
}

// Let the SDK handle the other links by returning `HandledByOctopus`
return HandledByOctopus
}
)

To see a full example of how you can achieve that, you can follow how it is done in the Samples, in the UrlHandler.


Override the language ≥ 1.9.0

On both iOS and Android, the system lets the user choose a language for their device and also lets them customize this language per app. Some apps do not use this standard way of handling the language. If you have a custom setting inside your app that does not set the system app language, you can call a function of Octopus in order to customize the language used (so Octopus does not use the system language but yours instead).

That being said, we recommend using the default system way of handling the locale, so system alerts and system screens (like the picture selection screen) are displayed in the desired language.

warning

No check can be done on the Locale you pass, so ensure it is a valid Locale. If the locale is not valid, it will fallback on the default language (english).

// Override the default (i.e. system or app based) locale
OctopusSDK.overrideDefaultLocale(Locale.FRENCH)

Follow the Samples

Want to see a code examples on how to use the SDK, no worries, we have that for you!

  1. First, clone the OctopusSDK project

    Android SDK

  2. Add those lines to the root project local.properties file:

    OCTOPUS_API_KEY=YOUR_API_KEY
    OCTOPUS_SSO_CLIENT_USER_TOKEN_SECRET=YOUR_USER_TOKEN_SECRET

    Replace YOUR_API_KEY with your own API key and YOUR_USER_TOKEN_SECRET with your own token secret.

  3. According to your desired UI integration mode choose the corresponding sample: