# AgentHub Client

A JavaScript library to access the AgentHub service, which is part of the Olos
Anywhere product. Add it to your frontend project to allow agents to establish
a connection with the server and receive events from the Olos platform.

### Installing

```bash
npm install @olostecnologia/agenthub-client
```

### Features

- Websocket connection: no continuous polling.
- Simple configuration: all you need is the AgentHub service URL and the agent's access token.
- Allow subscribing to individual events from Olos or all of them.
- Automatically tries to reconnect in case of network failure or service unavailable (\*).
- Emits the updated list of online agents if the user is an admin.
- Logs debug information to the browser's console (enable "verbose" to see them).

(\*) functionality provided by Phoenix's
[client](https://hexdocs.pm/phoenix/js/index.html), which is the core of this library.

### Usage

Import the `Connection` factory function and use it to create a new connection object:

```javascript
import { Connection } from "@olostecnologia/agenthub-client"
const conn = Connection()
```

Subscribe to events you are interested in. Example:

```javascript
conn.on("connected", (agentInfo) => {
  console.log("Agent connected", agentInfo)
})

conn.on("disconnected", () => {
  console.log("Agent disconnected")
})

conn.on("onlineUsers", renderOnlineUsers)

conn.on("ScreenPopVoice", (event) => {
  console.log("Displaying a voice screen pop:", event)
})

conn.on("ThirdParty", (event) => {
  console.log("Handling a 3rd party event:", event)
})
```

Connect to the AgentHub server passing a function that returns user's access token
and the AgentHub base URL:

```javascript
conn.connect(() => token, "https://agenthub.api.olos.live")
```

### Events

Instead of subscribing to individual events, you can subscribe to all
of them using the `any` wildcard. Example:

```javascript
conn.on("any", (event) => {
  switch (event.eventType) {
    case "ScreenPopVoice":
    // do something with the screenPopVoice event
    case "ThirdParty":
    // do something with the 3rd party event
    default:
    // log something like "unsupported event type: ${event.eventType}"
  }
})
```

The `connected`, `disconnected`, `onlineUsers` and `any` events are the only ones
generated by the client itself. All other events are named by the
Olos platform, like `ScreenPopVoice` and many others.

Example of an event from Olos:

```json
{
  "eventId": "1661794102499-0",
  "eventType": "ScreenPopVoice",
  "agentId": "9300f2b4-70f2-4a21-bcb5-e5d46e602c30",
  "campaignId": 22,
  "channelType": "Voice",
  "channel": "Outbound",
  "timestamp": 1657905963385,
  "eventData": {
    "someField": "some value",
    "anotherField": 1
  }
}
```

### User authentication

When connecting, you must provide a function that returns a valid access token.
In case of an unexpected disconnection, the client will keep trying to
reconnect automatically, calling the provided function to obtain the token.
It's your responsibility to make sure the token is valid and not expired, so
set a timeout to refresh it before it expires. You won't be able to connect
without a token or with an invalid one. This library will perform basic validation
but it won't check the token's signature. This is done by the server. No specific
reason will be given by the server in case the authentication fails.

The access token must be a valid RS256-signed JWT, with the claims as in
the following example. `sub` is the agent's id and `tid` is the tenant's id.

```json
{
  "sub": "52",
  "tid": "acme",
  "iss": "https://auth.api.olos.live",
  "iat": 1658751413,
  "exp": 2799231413,
  "username": "adams",
  "roles": ["agent"]
}
```

Please reach out to Olos support for details on how to integrate your
application with the authentication service in Olos to obtain a token
for your user.

### List of online users

If the connected user has the role "admin", the connection will emit
the event `onlineUsers` with the updated list of online users and
agents every time a user or agent connects or disconnects.

Example of user from the list:

```json
{
  "ref": "FxIaTI3YaVxIGAlk",
  "userId": "9300f2b4-70f2-4a21-bcb5-e5d46e602c30",
  "username": "adams",
  "onlineAt": 1662391541000,
  "ipAddress": "179.209.45.134"
}
```

where `ref` is an unique identifier that can be used as the id of an element in an HTML list.
Do not use the `userId` as the same user can be online in more than one device.

### Contributing

To update this library in `npm`, please change the version in the `package.json` and:

```bash
npm run prebuild
npm run build
npm publish --access public
```
