# PubNub Integration

Our goal at [Red5](https://red5.net) has always been to give developers the tools they need to deliver real-time streaming without complexity, bottlenecks, or hidden limitations. The Red5 integration with [PubNub](https://www.pubnub.com/) represents a major step toward that mission, combining sub-250 ms video streaming with sub-100 ms data delivery to power chat, reactions, synchronized metadata, and other interactive features at global scale.

The intent of this document is to describe the integration points within our HTML SDK in which you can take advantage of PubNub and its services.

> Read more about our thoughts and goals regarding PubNub Integration [here](https://www.red5.net/blog/red5-cloud-integrates-pubnub-to-deliver-interactivity-intelligence-global-scalability-for-real-time-streaming/).

# PubNubClient

The Red5 HTML SDK provides a basic `PubNubClient` to establish a connection to PubNub services for message communication. Its interface is very similar to that of the `WHIPClient` and `WHEPClient` provided in the SDK - both of which also provide easy init parameters and hooks for include PubNub intergation.

This document details the use of `PubNubClient` itself and may provide clearer details of the integration with the publisher and subscriber clients.

> To learn more about how to include PubNub integration for a `WHIPClient` and `WHEPClient`, please review [WHIPClient - PubNub](./whip-client.md#pubnub-integration) and [WHEPClient - PubNub](./whep-client.md#pubnub-integration), respectively.

* [Usage](#usage)
* [Init Configuration](#init-configuration)
* [Events](#events)

# Usage

A `PubNubClient` can be used singularly without taking advantage of the streaming capabilities of the `WHIPClient` and `WHEPClient` clients of the SDK.

```js
// import { PubNubClient } from red5pro-webrtc-sdk
// OR, if loaded from CDN
const { PubNubClient } = red5prosdk
...
const config = {
  publishKey: 'pub-c-XXXX',
  subscribeKey: 'sub-c-XXXX',
  userId: 'user-1234',
  channelId: 'red5',
  authToken: 'XXXX='
}
const pubnubClient = new PubNubClient()
pubnub.on('*', (event) => {
  const { type, data } = event
  console.log(`[PubNub]:: ${type}`, data)
})
await pubnub.init(pubnubConfig)
await pubnub.subscribe(channelId)
```

## Messaging API

The following methods relate to the Message API of the `PubNubClient` that integrates with the PubNub service.

### subscribe(channelId: string)

Request to subscribe to messages on the given channel. In most cases, this will be the same as the `channelId` provided in the `init()` configuration, as that is used to generate a valid token in the system.

### publishMessage(channelId: string, message: any)

Request to deliver a message on the target channel. In most cases, this will be the same as the `channelId` provided in the `init()` configuration, as that is used to generate a valid token in the system.

### unsubscribe(channelId: string)

Request to stop receiving messages on the given channel.

### destroy()

Request to shut down the PubNub client integration and any channel subscriptions.

> To respond to message-associated events, please visit the [Events](#events) section.

# Init Configuration

When using the `init()` call of a `PubNubClient`, the following initialization properties are available:

| Property | Required | Default | Description |
| :--- | :---: | :---: | :--- |
| `pubnub` | [x] | `window.PubNub` | Reference to the [PubNub](https://www.npmjs.com/package/pubnub) library to utilize. |
| `publishKey` | [x] | _None_ | The registered publish key from PubNub. This can be found in your [Red5 Cloud](https://cloud.red5.net) deployment. |
| `subscribeKey` | [x] | _None_ | The registered subscribe key from PubNub. This can be found in your [Red5 Cloud](https://cloud.red5.net) deployment. |
| `userId` | [x] | Auto-generated if not provided. | The associated User ID for PubNub. |
| `channelId` | [x] | `red5` | Default Channel ID to subscribe to in PubNub messaging. |
| `expiryMinutes` | [-] | `120` | Default expiration of issued token associated with client. |
| `authToken` | [-] | _None_ | Optional authentication token issues from PubNub - if known. |
| `cloudEndpoint` | [-] | _None_ | Optional endpoint of Red5 Cloud deployment to attempt access of `authToken` from PubNub system. |
| `backendUrl` | [-] | _None_ | Optional full URL of service endpoint to access `authToken` from PubNub system. [See documentation on deploying your own service.](https://www.red5.net/docs/red5-cloud/development/sdks/backend-sdk/) |
| `logLevel` | [-] | `trace` | The default log level of the PubNub client. |

## Authentication

The `PubNubClient` requires an authentication token to connect to the PubNub system for messaging. If a valid token is generated by a means outside of the SDK, you can define the token on the `authToken` attribute of the ini configuration.

If the `authToken` is not known prior to initialization, there are two ways that can be used through the SDK to access and utilize the token for connection:

### cloudEndpoint

If you have a [Red5 Cloud](https://cloud.red5.net) account and deployment, you can provide the `cloudEndpoint` attribute pointing to your deployment (e.g., `userid-1234-abcd.cloud.red5.net`). The SDK will attempt to generate the authentication token using a service that may be available from your deployment.

### backendUrl

If the `authToken` is not known or your [Red5 Cloud](https://cloud.red5.net) deployment does not provide an means for retrieving the authentication token, we have released open sourced Backend SDKs which can be used to provide your own custom service in generating a authentication token to be used.

To learn more about the Backend SDKs and authentication token generation, [please refer to the documentation](https://www.red5.net/docs/red5-cloud/development/sdks/backend-sdk/).


> This init configuration is also the same used when enabling PubNub integration for WHIP/WHEP Clients. View documentation related to [WHIPClient](./whip-client.md#pubnub-integration) and [WHEPClient](./whep-client.md#pubnub-integration).

# Events

The following events are dispatched by the `PubNubClient` and enumerated on the `PubNubEventTypes` object:

| Access | Event Type | Meaning |
| :--- | :--- | :--- |
| `CONNECTED` | 'PubNub.Connected' | Dispatched when the PubNub client has successfully connected to the PubNub service. |
| `DISCONNECTED` | 'PubNub.Disconnected' | Dispatched when the PubNub client has disconnected from the PubNub service. |
| `SUBSCRIBE_SUCCESS` | 'PubNub.Subscribe.Success' | Dispatched when a channel subscription request has completed successfully. The `data` property contains details about the subscription. |
| `SUBSCRIBE_FAILURE` | 'PubNub.Subscribe.Failure' | Dispatched when a channel subscription request has failed. The `data` property contains error information. |
| `UNSUBSCRIBE_SUCCESS` | 'PubNub.Unsubscribe.Success' | Dispatched when a channel unsubscribe request has completed successfully. The `data` property contains details about the unsubscription. |
| `UNSUBSCRIBE_FAILURE` | 'PubNub.Unsubscribe.Failure' | Dispatched when a channel unsubscribe request has failed. The `data` property contains error information. |
| `MESSAGE_RECEIVED` | 'PubNub.Message.Received' | Dispatched when a message is received on a subscribed channel. The `data` property contains the message payload. |
| `MESSAGE_SEND_SUCCESS` | 'PubNub.Message.Send.Success' | Dispatched when a message has been successfully published to a channel. The `data` property contains confirmation details. |
| `MESSAGE_SEND_FAILURE` | 'PubNub.Message.Send.Failure' | Dispatched when a message publish request has failed. The `data` property contains error information. |
| `AUTH_TOKEN_GENERATED` | 'PubNub.AuthToken.Generated' | Dispatched when an authentication token has been successfully generated. The `data` property contains the token information. |
| `AUTH_TOKEN_GENERATION_ERROR` | 'PubNub.AuthToken.Generation.Error' | Dispatched when authentication token generation has failed. The `data` property contains error information. |
| `STATUS` | 'PubNub.Status' | Dispatched on general status notification. The `data` property contains the status. |
| `ERROR` | 'PubNub.Error' | Dispatched when a general error occurs in the PubNub client. The `data` property contains error details. |
