# Push notifications
Source: https://sovaria.in/docs/mobile-push

Send push notifications to your app users through FCM, APNs and web push with your own credentials: register tokens from the app, send from a function or your server.

## Do I need Firebase?

- **iOS: no.** Sovaria sends straight to Apple (APNs) with a key from your Apple Developer account.
- **Android: only the free messaging part.** On phones with Google Play services, Google delivers every push through Firebase Cloud Messaging (FCM), whoever sends it — OneSignal, Expo and others ask for the same credentials. Create a free Firebase project once, add your Android app (for `google-services.json`) and upload the project’s service account here. No other Firebase product is used and Google bills nothing.
- **Web: no.** Browsers get push with the project's own VAPID keys (see Web push below). Sites already using Firebase's JS SDK can register their FCM token instead; sends then carry FCM's `webpush` block (click link, urgency, expiry).

## Set up

1. **Add credentials** — Console › Authentication › Mobile › **Push notifications**: upload the Firebase service account JSON (Android, and iOS through Firebase) and/or an APNs `.p8` key (key id, team id, bundle id, sandbox or production). They are encrypted and never shown again.
2. **Register the token after sign-in**
```dart
final token = await FirebaseMessaging.instance.getToken();
await sovaria.push.register(token: token!, platform: Platform.isIOS ? 'ios' : 'android', topics: ['news']);
FirebaseMessaging.instance.onTokenRefresh.listen((t) => sovaria.push.register(token: t, platform: 'android'));
await sovaria.push.subscribeToTopic('deals');           // like FCM subscribeToTopic (Swift: subscribe(toTopic:))
```
3. **Send from a function**
```ts
// In a function: const sov = createClient()  (no secrets; each call has its own project key)
await sov.api.push.send({ message: {
  to: { user_ids: [order.user_id] },                // or device_ids, or topic: 'news'
  notification: { title: 'Order shipped', body: 'Arriving tomorrow' },
  data: { order_id: order.id },
} })
```
```http
POST /api/v1/projects/{project_id}/push/send
Authorization: Bearer <service role key>
{ "to": { "topic": "news" }, "notification": { "title": "Hi" }, "dry_run": true }
→ { "requested": 2771, "sent": 0, "failed": 0, "pruned": 0, "dry_run": true }
```

## Web push (browsers)

Chrome, Edge, Firefox and Safari 16.4+ (including web apps added to the iOS home screen). **Set up web push** in the console (or `sov push webpush-keys`) creates a VAPID key pair for the project; the private key is encrypted and never leaves Sovaria. Serve the SDK's service worker, then register after sign-in from a click (browsers require a user gesture).

JavaScript:
```ts
import { serviceWorkerSource } from '@sovaria/sdk'
// 1. Write serviceWorkerSource to public/sovaria-sw.js at build time (or importScripts it from your own worker).
// 2. After sign-in, on a click:
await sov.push.register({ topics: ['news'] })     // asks permission, subscribes, registers the browser
// Later: await sov.push.unregister()
```

Send:
```bash
sov push send --topic news --title "Sale" --body "20% off today" --link https://shop.example/sale
```

Each message is encrypted for that one browser (RFC 8291) and signed with the project's key (RFC 8292). `link` opens on click; `collapse_key` replaces an older notification. Subscriptions the browser drops (404/410) are removed automatically. Only subscriptions on known push services are accepted.

## How sends are delivered

- **Paced, never refused for speed.** Deliveries follow your plan's `push.sends_per_second` across every send of the organization (a token bucket shared by all Sovaria servers). When the second is full, the next batch waits for the next second instead of failing, so two campaigns at once both arrive.
- **Retried.** Temporary failures (HTTP 429, 5xx, network) are tried again up to 3 times with growing waits, honouring the provider's `Retry-After`. Permanent ones (an uninstalled app) are reported and the token is disabled.
- **Large sends are queued.** A send to more devices than the plan delivers in about 5 seconds returns at once with `status: queued` and runs as a durable job: it survives restarts and deploys, continues from the devices not yet done, and shows progress in Recent sends (`sov push sends`). Cancel it with `sov push cancel <id>`.

## Push notifications in the console

- **Stat tiles**: active devices by platform, notifications delivered this month against your plan, failures, and connected providers.
- **Firebase Cloud Messaging**: **Upload JSON** (Project settings › Service accounts › Generate new private key in Firebase). Once connected the card shows the Firebase project and service account; **Replace** uploads a new key, **Disconnect** stops Android sends.
- **APNs**: **Key ID** (filled in from `AuthKey_<KEYID>.p8` on upload), **Team ID**, **Bundle ID** and **Environment** — Sandbox for builds run from Xcode, Production for TestFlight and the App Store — then **Upload .p8**. Both keys are encrypted and never shown again.
- **Send a notification**: choose **Topic**, **Users** or **Devices**, a title and body; **More options** adds an image, data (JSON), priority, sound, badge, expiry, collapse key and Android channel. **Check audience** counts devices without sending; **Send** checks the audience, asks you to confirm the number, then sends. A send can’t be recalled.
- **Recent sends** lists every send with delivered and failed counts and error codes, including audience checks.

## Message fields

| Field | Meaning |
|---|---|
| `to` | `user_ids`, `device_ids` and/or `topic` (devices subscribed with `push.subscribe`). |
| `notification` | `title`, `body`, `image` (https). |
| `data` | String key/values your app receives. |
| `badge`, `sound`, `thread_id`, `android_channel_id` | Platform extras. |
| `priority`, `ttl_seconds`, `collapse_key` | `high` (default) or `normal`; how long to keep trying; replace an older push with the same key. |
| `link` | Web: the https URL (or path in your web app) opened when the notification is clicked. |
| `content_available` | Silent push that wakes the app (sent with APNs priority 5). |
| `dry_run` | Count the audience; nothing is sent and nothing is billed. |

- App users can only register and remove **their own** tokens; only console admins and server keys send.
- Tokens a provider reports as gone (uninstalled app) are disabled automatically.
- Each send is logged with counts and error codes — never the message content (Push notifications › Recent sends).
- Limits: `push.sends_month` (Free stops at the cap, paid plans bill overage), `push.max_recipients_per_send`, `push.sends_per_second` (paced, not refused), `push.devices_per_user`.
