Introducing a new way to review your PRs.

Read the announcement

capcom6 / android-sms-gateway

The SMS Gateway for Android™ app enables sending and receiving SMS messages through an API that can be accessed directly on the device or via a cloud server when direct device access is not possible.

View on GitHub

20 documents · Updated Nov 20, 2026

docs / cloud-gateway-integration

Cloud gateway integration

The cloud gateway integration connects the Android gateway to a cloud service so the device can register itself, receive work, apply cloud-owned settings, report message state, and upload received messages. It combines authenticated HTTP requests with a live server-sent event stream and uses local message, inbox, and webhook services to carry cloud data through the device.

Integration boundary

The gateway is an optional system boundary. When it is enabled, the application starts cloud registration, message pulling, inbox upload, settings and webhook synchronization, event handling, and push or live-event connectivity; when it is disabled, these paths do not act on cloud data. GatewayService coordinates this boundary while GatewayApi represents the cloud request surface. References: app/…/GatewayService.kt• L50-75, app/…/GatewayApi.kt• L29-46

The integration uses two cloud notification paths. Server-sent events (SSE) provide a long-lived stream for near-real-time commands, while Firebase Cloud Messaging (FCM) can deliver the same event types as push data. Both paths pass through the same event router, so the cloud command flow does not depend on which transport delivered the event. The routing boundary is described in event routing. References: app/…/SSEForegroundService.kt• L43-79, app/…/PushService.kt• L19-51, app/…/EventsRouter.kt• L16-55

Device identity

The device identity area establishes the cloud record and the credentials that all later gateway work uses. Registration creates that relationship, while updates keep its device details and public encryption key current.

Registration state

Device registration gives the cloud service a device record and an access token. The registration request describes the Android device, its push token when available, its active SIM cards, and the current public encryption key metadata. The returned identity and token are stored as the basis for later cloud calls.

Registration supports anonymous enrollment, enrollment with a one-time code, and enrollment with user credentials. If a stored access token exists, the system first tries to refresh the device record. An unauthorized result causes a new registration attempt. Network work retries through the registration worker rather than blocking the main application flow.

References: app/…/GatewayService.kt• L114-178 app/…/GatewayApi.kt• L48-76 app/…/GatewaySettings.kt• L16-45 app/…/RegistrationWorker.kt• L21-80

Device updates

The device record stays aligned with the phone as its push token, SIM information, or public encryption key changes. A successful update keeps the stored registration identity and reports registration success to the rest of the application. A local device-key rotation also starts registration work so the cloud receives the new public key metadata.

References: app/…/GatewayService.kt• L180-208 app/…/GatewayApi.kt• L79-85 app/…/EventsReceiver.kt• L189-197 app/…/PushService.kt• L23-25

Cloud communication

Cloud communication carries both request-and-response work and remote events. The HTTP API handles durable data exchange, while the SSE and push paths notify the device that new work is ready.

HTTP API

The cloud API is an authenticated JSON interface for device identity, message work, inbox uploads, settings, webhooks, and user account actions. The gateway uses the stored device token for normal calls and uses the configured cloud address as the service root.

The cloud address and private access token are configurable gateway values. Exported configuration includes the cloud address and event-channel choice, while the registration record remains the local source for the device token and identity.

References: app/…/GatewayApi.kt• L29-134 app/…/GatewaySettings.kt• L20-66

Server-sent event stream

The SSE stream keeps a foreground service connected to the cloud event endpoint. On connection it asks the message pull path to reconcile pending work; each received event is translated into an internal event and sent to the application event router. References: app/…/SSEForegroundService.kt• L23-81, app/…/SSEForegroundService.kt• L114-127

The stream is visible to the user as a foreground service and holds partial wake and Wi-Fi locks while it runs. A closed or failed stream reconnects with a growing delay unless the gateway is stopping. With SSE_ONLY, registration and token refresh keep the stream active; with the other channel, an available FCM token stops the SSE fallback, while its absence starts SSE.

References: app/…/SSEManager.kt• L18-35 app/…/SSEManager.kt• L89-117 app/…/GatewaySettings.kt• L11-14 app/…/SSEForegroundService.kt• L43-65 app/…/EventsReceiver.kt• L130-161 app/…/PushService.kt• L54-67

The cloud-to-device event path is shown below. It keeps transport concerns separate from the workers that perform the requested action.

flowchart LR
    Cloud[Cloud service] -->|SSE event| Stream[SSE connection]
    Cloud -->|Push data| Push[FCM push service]
    Stream --> Router[External event router]
    Push --> Router
    Router --> Bus[Application event bus]
    Bus --> Pull[Pull messages]
    Bus --> Settings[Update settings]
    Bus --> Webhooks[Update webhooks]
    Bus --> Cancel[Cancel local message]

References: app/…/SSEManager.kt• L37-85 app/…/PushService.kt• L27-41 app/…/EventsRouter.kt• L21-53

Cloud data synchronization

Message pulling

Message pulling reconciles cloud message work with the local message service. The gateway requests pending cloud messages in the configured FIFO or LIFO order, imports new messages as cloud-sourced send requests, and starts local state reporting for messages already known on the device.

The cloud message contract supports text, data, and multimedia message content. The gateway maps these forms into the local send model and keeps cloud options such as the target SIM, delivery report, schedule, validity period, priority, and encryption flag with the request. Text-only multimedia messages remain valid even when they have no attachment list.

The pull path also handles cloud cancellation. A cloud message in the Cancelling state is cancelled locally when it is still pending. If the message is not present locally, the gateway reports it as cancelled so the cloud does not wait for a state that the device cannot produce. If local delivery already started, the gateway leaves the existing outcome to state reporting. Periodic network work and event-triggered starts provide both recovery and prompt pickup.

Detailed command handling belongs in Gateway command workers. The message send and delivery lifecycle remains part of the message processing flow, with delivery details in outbound message delivery.

References: app/…/GatewayService.kt• L227-344 app/…/GatewayApi.kt• L87-99 app/…/GatewayApi.kt• L221-284 app/…/PullMessagesWorker.kt• L21-66 app/…/EventsReceiver.kt• L31-49 app/…/EventsReceiver.kt• L73-89

Inbox message uploads

Inbox message uploads move received SMS, data messages, and downloaded MMS content from the device to the cloud. The gateway prepares each item locally, protects message data before it enters the upload queue, and sends queued items through the cloud inbox endpoint.

The upload queue is durable and keeps a stable order for pending items. A network-bound worker sends the queue in batches and removes items only after the cloud accepts them. This lets message receipt continue while the network is unavailable and prevents a temporary cloud failure from blocking the receiver.

MMS header events wait for their downloaded content, while supported text, data, and downloaded MMS events become cloud inbox records. Attachment data travels with the record, and the cloud contract marks the uploaded fields as encrypted. Attachments that are too large to upload are omitted and logged, while the rest of the MMS record remains eligible for upload.

References: app/…/GatewayService.kt• L325-348 app/…/GatewayApi.kt• L102-108 app/…/InboxUploadService.kt• L29-115 app/…/InboxUploadWorker.kt• L71-149

Remote settings

Remote settings let the cloud service change supported application settings without a local UI action. A scheduled synchronization fetches the cloud settings map and passes it to the central settings service, which applies changes to the relevant setting groups and notifies the user when a change takes effect.

The settings path is a synchronization boundary rather than a second settings store. Each setting group decides which values it can import, and invalid values can stop that update so the cloud contract stays visible as an error. The wider settings model is described in configuration management.

References: app/…/SettingsUpdateWorker.kt• L19-69 app/…/SettingsService.kt• L14-63 app/…/GatewaySettings.kt• L69-107

Webhook synchronization

Cloud webhooks are copied into the local webhook service as cloud-sourced registrations. A daily sync replaces the cloud-owned set, which lets additions and removals made in the cloud take effect locally without changing webhooks from other sources.

Once synchronized, cloud webhook registrations use the same local event delivery path as other webhooks. The webhook service checks that the cloud gateway is enabled and that a device identity exists before it queues an event for delivery. The delivery path is described in webhook delivery.

References: app/…/WebhooksUpdateWorker.kt• L22-77 app/…/WebHooksService.kt• L48-77 app/…/WebHooksService.kt• L122-170

State reporting

State reporting sends the results of cloud-owned work back across the same integration boundary. Message state is the direct cloud contract, while device health helps explain whether the device can maintain that contract.

Message state

State reporting sends the local message state back to the cloud after a cloud-sourced message changes. The report includes the message state, each recipient state and error, and the recorded times for state changes, so the cloud can present the same delivery result as the device.

The gateway listens only for state changes from cloud or gateway sources. It schedules a network-bound report with retry backoff, which keeps local message processing independent from temporary cloud or network failure. Event collectors isolate errors from one gateway event type so a failed trigger does not stop the other gateway paths.

References: app/…/SendStateWorker.kt• L23-55 app/…/GatewayApi.kt• L94-99 app/…/EventsReceiver.kt• L51-71 app/…/SendStateWorker.kt• L63-80

Device health

Device health adds the network and device signals that explain whether the gateway can reach the cloud and continue work. The gateway page relies on that status at a high level. The transport checks, IP discovery, battery signals, and ping schedule are described in connection and device health.

References: app/…/GatewayService.kt• L370-378 app/…/EventsReceiver.kt• L73-89

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the cloud event names aligned across the SSE stream, FCM payloads, ExternalEventType, and EventsRouter. A name mismatch can discard a remote command before a worker starts.
  • Keep registration response fields aligned with the stored registrationInfo, because the device token authenticates message, inbox, settings, webhook, and state calls.
  • Keep registration and device-update key fields aligned with the device key record. A stale public key or key version can break cloud-side handling of protected data.
  • Keep cloud message fields and content variants aligned with local message identity and state reporting. A changed message ID or state meaning can create duplicate local work or leave cloud work unresolved.
  • Keep the Cancelling wire state separate from local processing states. Mapping it as a normal local state can prevent the device from resolving an asynchronous cloud cancellation.
  • Keep inbox message types, encrypted fields, attachment data, and duplicate keys aligned between the receiver queue and the /inbox API. A contract mismatch can silently lose received messages or suppress a valid retry.
  • Keep cloud webhook replacement scoped to EntitySource.Cloud so local and gateway webhook registrations are not removed by a cloud refresh.
  • Keep the selected notification channel consistent with both FCM registration and SSE startup. A channel change can otherwise leave the device without a command transport.

Important failure modes

TriggerConsequenceGuard
Stored device token is rejected by the cloudNormal cloud calls fail until the device registers againRegistration retries and treats an unauthorized update as a signal to register a new device record
SSE event has an unknown typeThe event is not routed to a workerKeep cloud event names in ExternalEventType; processing errors are logged
Network is unavailable during pull, inbox upload, or state reportingCloud work waits and state or received messages are not sent at that timeWork requires a connected network and retries with backoff
Cloud settings contain an invalid valueThe settings update fails instead of applying an unsafe valueSetting import validates supported values and reports the failing setting group
A cloud message has no supported content formThe pull attempt logs an error and does not enqueue that messageKeep cloud message content variants aligned with the gateway message model
A cloud message is cancelled after its local record is goneThe cloud could remain waiting for a cancellation resultThe gateway sends a cancelled state with cancelled recipients when no local message exists
A cloud cancellation arrives after local delivery has startedThe local message is not changed by the cancellation markerThe gateway treats the local state as authoritative and reports the resulting delivery state
An inbox upload batch contains an item that the cloud rejectsThe batch is split to isolate the item; a rejected single item is logged and removedBatch splitting protects the rest of the queue, but the inbox contract must accept all supported message types
A supported MMS attachment is too large to uploadThe attachment is omitted from the cloud recordThe upload service logs omitted attachment IDs and continues with the available message content
Gateway webhooks are synced while the gateway has no identityWebhook events cannot identify their device and are skippedEvent emission requires an enabled gateway and a stored device ID
FCM becomes available while the selected channel is not SSE_ONLYThe SSE fallback is stopped and live events use push deliveryDevice registration handling selects one active transport and keeps SSE_ONLY pinned to SSE
A device key rotation is not followed by registration workCloud-side protected message handling can use stale key metadataThe key rotation event schedules a network-bound registration update

Key files

FileWhy to read it
app/…/GatewayService.ktCentral view of registration, cloud calls, device key sharing, message import, inbox upload, cancellation, webhook access, settings access, and state reporting
app/…/GatewayApi.ktCloud request boundary and the data shapes shared with the service, including device key metadata, message states, and inbox records
app/…/SSEForegroundService.ktLive event connection, credential lookup, pending-message pull, and handoff into application events
app/…/SSEManager.ktReconnect behavior and SSE transport callbacks
app/…/PushService.ktFCM command delivery and token refresh registration
app/…/EventsRouter.ktTranslation from cloud event types to internal application events
app/…/EventsReceiver.ktConnections between gateway events and pull, sync, cancellation, registration, transport selection, and state work
app/…/RegistrationWorker.ktNetwork-bound device registration and update recovery
app/…/PullMessagesWorker.ktScheduled message reconciliation
app/…/SendStateWorker.ktCloud message-state reporting
app/…/SettingsUpdateWorker.ktRemote settings refresh
app/…/WebhooksUpdateWorker.ktCloud webhook refresh and source mapping
app/…/InboxUploadService.ktPreparation and encryption of received messages before they enter the cloud upload queue
app/…/InboxUploadWorker.ktNetwork-bound inbox batching, retry, failure isolation, and upload completion
app/…/InboxUploadRepository.ktDurable queue boundary for pending inbox uploads