[![npm version](https://badge.fury.io/js/%40tiledesk%2Ftiledesk-server.svg)](https://badge.fury.io/js/%40tiledesk%2Ftiledesk-server)

[![CircleCI](https://circleci.com/gh/Tiledesk/tiledesk-server.svg?style=svg)](https://circleci.com/gh/Tiledesk/tiledesk-server)


> ***🚀 Do you want to install Tiledesk on your server with just one click?***
> 
> ***Use [Docker Compose Tiledesk installation](https://github.com/Tiledesk/tiledesk-deployment/blob/master/docker-compose/README.md) guide***

# Introduction

Tiledesk-server is the server engine of Tiledesk. Tiledesk is an Open Source Live Chat platform with integrated Chatbots written in NodeJs and Express. Build your own customer support with a multi-channel platform for Web, Android and iOS. 

Designed to be open source since the beginning, we actively worked on it to create a totally new, first class customer service platform based on instant messaging.

What is Tiledesk today? It became the open source “conversational app development” platform that everyone needs 😌

You can use Tiledesk to increase sales for your website or for post-sales customer service. Every conversation can be automated using our first class native chatbot technology.
You can also connect your own applications using our APIs or Webhooks.
Moreover you can deploy entire visual applications inside a conversation. And your applications can converse with your chatbots or your end-users! We know this is cool 😎

Tiledesk is multichannel in a totally new way. You can write your chatbot scripts with images, buttons and other cool elements that your channels support. But you will configureyour chatbot replies only once. They will run on every channel, auto-adapting the responses to the target channel whatever it is, Whatsapp, Facebook Messenger, Telegram etc.

More info on Tiledesk website: https://www.tiledesk.com.

You can find technical documentation here: https://developer.tiledesk.com

# Prerequisites for Installation

* [Nodejs](https://www.npmjs.com/) and npm installed. Suggested versions are NodeJS 12.20.2 and NPM 6.14.11 
* [MongoDb](https://www.mongodb.com) installed

# Run Tiledesk with Docker Compose

Do you want to install all the Tiledesk components on your server with just one click?
Use [Docker Compose Tiledesk installation guide](https://github.com/Tiledesk/tiledesk-deployment/blob/master/docker-compose/README.md)

# Running Tiledesk Server

## Using Docker


### Configure .env file 
```
curl https://raw.githubusercontent.com/Tiledesk/tiledesk-server/master/.env.sample --output .env
nano .env #configure .env file properly
```

### Running
If you want to run tiledesk and mongo with docker run :

```
docker run --name tiledesk-mongo -d mongo
docker run -p 3000:3000 --env DATABASE_URI="mongodb://mongo/tiledesk-server" --env-file .env --link tiledesk-mongo:mongo tiledesk/tiledesk-server
```

Otherwise if you want to run tiledesk only with docker run :

```
docker run -p 3000:3000 --env DATABASE_URI="mongodb://YOUR_MONGO_INSTALLATION_ENDPOINT/tiledesk-server" --env-file .env tiledesk/tiledesk-server
```



## Run locally with npm

Steps to run with npm:

```
npm install -g @tiledesk/tiledesk-server mongodb-runner
mongodb-runner start
curl https://raw.githubusercontent.com/Tiledesk/tiledesk-server/master/.env.sample --output .env
nano .env #configure .env file properly
tiledesk-server  
```

If you want to load .env file from another path: `DOTENV_PATH=/MY/ABSOLUTE/PATH/.env tiledesk-server`

Note: If installation with -g fails due to permission problems (npm ERR! code 'EACCES'), please refer to this [link](https://docs.npmjs.com/getting-started/fixing-npm-permissions).

## Install from source code

* Clone this repo
* Install dependencies with `npm install`
* Configure the tiledesk .env file. You can see an example in the file .env.sample under the root folder. Rename it from .env.sample to .env and configure it properly. 
* Run the app with the command `npm start`.


## Deploy on Heroku

Deploy with button:

[![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/Tiledesk/tiledesk-server)

# Community? Questions? Support ?
If you need help or just want to hang out, come, say hi on our [<img width="15" alt="Tiledesk discord" src="https://seeklogo.com/images/D/discord-color-logo-E5E6DFEF80-seeklogo.com.png"> Discord](https://discord.gg/Q5A6Ewadmz) server.

# REST API

See the Tiledesk REST API [here](https://developer.tiledesk.com/apis/rest-api/introduction)

# Upgrading 
To see how to upgrade tiledesk-server see [here](./docs/upgrading.md) 

# Quota usage backup
Quota usage counters (requests, messages, email, tokens, agent_tokens, voice_duration) live in Redis (`quotes:<type>:<id_project>:<period>`). To survive a Redis wipe they are copied into the MongoDB collection `quota_usages`:

- **Dirty set**: an increment that must mark its counter sends `MULTI`, the `INCR`/`INCRBY`/`INCRBYFLOAT`, `SADD quotes:dirty <key>`, `EXEC` in one round trip; setting a threshold e-mail flag marks its counter too. While the watcher runs (see wipe detection), each process remembers the counters it marked (only after `EXEC` confirmed the `SADD`) and then sends just the plain increment, until it sees a new snapshot generation (`quotes:dirty:gen`). The memo is trusted only while the watcher's last generation read is younger than 1.5 x `QUOTA_SENTINEL_CHECK_SECONDS` (it is cleared on a read error): if the watcher stalls, every increment marks again. The set holds the distinct counters changed in one interval (about 90-110 bytes each in Redis) and is drained by every snapshot. With `QUOTA_SNAPSHOT_INTERVAL_MINUTES=0` or `QUOTES_ENABLED=false` nothing is marked and `start()` deletes `quotes:dirty` and `quotes:dirty:saving`.
- **Snapshot**: every `QUOTA_SNAPSHOT_INTERVAL_MINUTES` (default `60`, `0` disables; the first run is after min(5 minutes, interval) from the start) one server replica, chosen by the Redis lock `quotes:snapshot:lock`, renames `quotes:dirty` to `quotes:dirty:saving` (a saving set left by a crashed cycle is kept and the new changes are merged into it), waits until every process saw the new generation (2 x `QUOTA_SENTINEL_CHECK_SECONDS` + 1 s; 31 s when it is `0` on this replica; all replicas must use the same value), reads only those counters and their notify flags, and upserts them with `$max` on `value`: a lower Redis value (e.g. a wiped Redis not yet restored) never lowers the backup. The upsert is an update pipeline (MongoDB 4.2+): `updatedAt` changes only when the value or a flag expiry grows, so an unchanged counter is a no-op in MongoDB (no write, no oplog entry). The log shows the settle time and the work time separately. Changes made during the cycle go to the new `quotes:dirty`. Only the recent periods are saved (those started in the last 70 days: the current and the previous monthly period). The threshold e-mail flags (`<counter>:notify:<pct>`) are saved too, with their expiry, so the e-mails are not sent again after a restore. No keyspace `SCAN`, no read back of the backup; batches of 500 with a yield to the event loop in between. A failing batch is logged, the next ones are written and `quotes:dirty:saving` is kept for the next cycle. Skipped when `QUOTES_ENABLED=false`.
- **Full scan**: every `QUOTA_FULL_SCAN_INTERVAL_HOURS` (default `168`, `0` disables; also on the first cycle ever, `quotes:fullscan:last`) the cycle also `SCAN`s the keyspace and saves every counter, to catch the ones changed outside the normal path (manual Redis edits) or whose dirty mark was lost.
- **Wipe detection**: the sentinel key `quotes:sentinel` exists while Redis holds the counters. In each server process a timer checks it at boot and then every `QUOTA_SENTINEL_CHECK_SECONDS` (default `15`, `0` disables); the request path never checks it. If it is missing Redis was wiped: the process forgets which keys it had verified, one replica (lock `quotes:restore:lock`, 60 s, renewed after every batch) restores the counters of the current period and their notify flags, then sets the sentinel again (warn logs). A counter lower than its snapshot was recreated by usage counted after the wipe, so it becomes snapshot + that usage; a counter equal or higher is left as is.
- **Restore on miss**: when a counter is read or incremented and its Redis key does not exist, it is seeded from `quota_usages` (`SET NX`; while wipe detection runs, only if the sentinel exists) before the operation, so increments land on top of the restored value. Each key is checked at most once per process every `QUOTA_RESTORE_MEMO_TTL_SECONDS` (default `600`). If MongoDB is unreachable the counter starts from zero as before and no lookup is tried for 60 s.
- **Restore command**: `npm run quota-restore -- [--project <id>] [--period current|all] [--dry-run] [--force | --merge]`. By default only missing keys are created; `--force` sets each counter to max(Redis value, snapshot); `--merge` applies the wipe rule above. Non expired notify flags are restored too.
- **Reset command**: deleting or lowering a counter in Redis no longer resets it (the restore on miss and `$max` bring the old value back). Use `npm run quota-reset -- --project <id> --type <type> [--period current|M/D/YYYY] [--value N] [--dry-run]`: it sets the counter in Redis and in `quota_usages` (default `0`, bypassing `$max`) and clears its notify flags in both. If a snapshot is running it waits for it (up to the lock TTL, printing progress).

Both commands use the server env (`DATABASE_URI`/`MONGODB_URI`, `CACHE_REDIS_HOST`/`CACHE_REDIS_PORT`/`CACHE_REDIS_PASSWORD`).

Limits: usage counted after the last snapshot (at most one interval) is lost on a wipe, unless the counter's dirty mark was missed (a failed `MULTI`, eviction of `quotes:dirty` under an `allkeys-*` policy, pods of an older version during a rolling deploy, which do not mark, or a stalled watcher on a mismatched config): then the change is saved at the counter's next marked increment or by the next full scan, and never if the full scan is disabled. `noeviction` and `volatile-*` policies are safe (the set has no TTL). During a rolling deploy the full scan on the first cycle of the new version (and the weekly one) reconciles what old pods counted. The snapshot uses multi-key commands and Lua scripts on `quotes:*` keys that do not share a hash tag: on a Redis Cluster the keys would need a common hash tag. The wipe restore assumes a clean wipe (empty Redis): a Redis restored from an older RDB/AOF together with a lost sentinel, or a counter lowered by hand, can be double counted; a rollback to an older RDB/AOF that keeps the sentinel is not detected (the usage since that dump is under counted).

# Testing
Run unit test with `npm test` and integration test with `npm run test:int` 


