🎯 Project Overview
@FricPhone Server is an open-source platform that transforms Android smartphones into remotely-controlled USSD and SMS automation nodes. A lightweight Android app runs as a foreground service, long-polls a REST backend for tasks, executes USSD sequences (via Android Accessibility Service) or sends SMS (via SmsManager), and streams all activity in real time to Firebase Firestore.
This admin console provides real-time multi-phone monitoring, task simulation, configuration management, and full SMS/log search — all secured behind Google Firebase Authentication.
- 📱 Supports multi-SIM Android devices (slot-aware USSD & SMS dispatch)
- 🔄 Long-poll REST architecture — 28 s server hold, automatic reconnect
- 🔐 Optional Keycloak client_credentials authentication on all API calls
- 📨 Incoming SMS captured, stored in Room, synced to Firestore + REST server
- ☁️ Firebase Firestore real-time sync — live presence (lastSeen updated on every poll, reset to 0 on stop)
- 📊 Full-text search across SMS and activity logs from this console
- 🕓 Transaction history with SIM slot badge and color-coded status indicator per row
👤 Author
Christian Fodoup — Software Engineer & creator of @FricPhone Server.
Christian designed and built the full stack: the Android foreground service, the PHP REST backend, the Firebase Firestore integration, and this administration console.
🤖 Role of Claude.ai
This project was developed with the assistance of Claude.ai (by Anthropic), an AI coding assistant used as a collaborative engineering partner throughout the development process.
Claude.ai contributed to:
- Architecture design — auth layer (Keycloak), Room persistence, SMS sync pipeline
- Android Kotlin implementation — PollingService, UssdExecutor, SmsReceiver, SmsSyncManager
- PHP REST backend — long-poll engine, auto-registration, JSON file persistence
- This web administration console — real-time monitoring, simulation, config, search
- Code review, documentation, and refactoring sessions
Claude.ai is an AI assistant — all architectural decisions and product direction were made by the author. The source code is reviewed, tested, and owned by Christian Fodoup.
📄 License & Version
Version 1.2 · Open source · MIT License
See the GitHub repository for the full source code, build instructions, and contribution guidelines.
🎯 Overview
@FricPhone Server transforms Android phones into remotely-controlled USSD/SMS automation nodes via a REST API. The phone long-polls a remote server, executes multi-step USSD sessions (via Android Accessibility Service) or sends SMS (via SmsManager), then reports the results back to the server.
All activity is synced in real time to Firebase Firestore, enabling multi-phone monitoring from this console.
- Long-polling REST — phone waits up to 28 s for a task before returning 204
- Multi-step USSD execution via Android Accessibility Service
- SMS sending via SmsManager with status reporting
- Incoming SMS capture and sync (SmsReceiver → Room → Firestore + REST server)
- Optional Keycloak authentication (client_credentials) on all API requests
- Real-time multi-phone monitoring via Firestore onSnapshot
- Incremental inbox SMS import at startup
🏗️ Architecture
┌──────────────────────────────────────────────────────────────────┐
│ REST SERVER / BACKEND │
│ GET /api/poll/{phoneId} POST /api/response │
│ POST /api/smsReceive │
│ (+ /api/tasks, /api/phones, /api/events — simulation only) │
└──────────────────┬───────────────────────────┬───────────────────┘
│ Long-poll (28 s) │ Results / SMS
▼ │
┌──────────────────────────────────┐ │
│ ANDROID — PollingService │◄───────────┘
│ (Foreground Service) │
│ ┌───────────────────────────┐ │
│ │ UssdExecutor │───┼──► *123# → GSM Network
│ │ SmsExecutor │───┼──► SMS → Recipient
│ │ SmsSyncManager │───┼──► Firebase Firestore
│ │ SmsReceiver │◄──┼─── Incoming SMS
│ │ SmsImporter (startup) │ │
│ └───────────────────────────┘ │
└──────────────────────────────────┘
│ Real-time sync (onSnapshot)
▼
┌──────────────────────────────────┐
│ FIREBASE FIRESTORE │
│ phones/{phoneId} │
│ phones/{id}/logs │
│ phones/{id}/receivedSms │
└──────────────────────────────────┘
▲
│ onSnapshot
┌──────────────────────────────────┐
│ THIS CONSOLE (Web) │
│ Monitoring · Simulation │
└──────────────────────────────────┘⚙️ Setup Guide
Build and install
Clone the GitHub repo, open with Android Studio, place google-services.json in app-kotlin/, then build and install on the target phone.
Enable the service
Settings → Accessibility → USSD Phone Server → Enable. Required so the app can read USSD popups and respond to them automatically.
Create the project
Firebase Console → new project → enable Firestore and Authentication (Google provider). Download google-services.json.
Configuration document
Create phones/{androidId} with fields: serverUrl, pollInterval, keycloakUrl, realm, clientId, clientSecret, tokenLifetimeMinutes.
Deploy on Apache
Copy the backend/ folder to your Apache webroot. Edit firebase-config.js with your Firebase credentials. Enable mod_rewrite and mod_headers.
Launch the service
Open the Android app → Dashboard → Start. The phone auto-registers on first poll and appears in this console's monitoring view.
🗄️ Firestore Schema
phones/{phoneId} ← Main phone document (auto-created on first poll)
├── phoneName : String ← Display name (set by admin in Config tab)
├── diviseGroup : String ← Deployment group
├── imeis : String[] ← IMEI per SIM slot (Android 8+)
├── simCards : Map[] ← { slot, operatorName, iccid, displayName }
├── localPhoneName : String ← Device model name (Build.MODEL, e.g. "Pixel 7")
├── deviceId : String ← Manufacturer-assigned device ID (Build.SERIAL)
├── lastSeen : Number ← Epoch ms — updated on every poll (200/204);
│ 0 on graceful stop → Monitoring dot turns red
│ — Config read by the Android app —
├── serverUrl : String ← REST server URL (default: https://phone-server.afric.ca/)
├── pollInterval : Number ← Poll interval in seconds (default: 5)
├── keycloakUrl : String ← Keycloak URL (empty = auth disabled)
├── realm : String
├── clientId : String
├── clientSecret : String
└── tokenLifetimeMinutes: Number ← Token lifetime in minutes (default: 5)
phones/{phoneId}/logs/{autoId} ← Activity logs — TTL 7 days
├── level : String ← INFO | WARN | ERROR | DEBUG
├── message : String
├── timestamp : Number ← Epoch ms
└── expireAt : Timestamp ← timestamp + 7 days — used by Firestore TTL policy
phones/{phoneId}/receivedSms/{smsId} ← Incoming SMS — TTL 60 days
├── smsId : String ← UUID (live) or sys_{_id} (inbox import)
├── msg : String
├── receivedFrom : String
├── simSlot : Number ← 0-based SIM slot index
├── receivedDateTime : Number ← Epoch ms
├── phoneId : String
└── expireAt : Timestamp ← receivedDateTime + 60 days — Firestore TTL
phones/{phoneId}/transactions/{txnNo} ← Task results (USSD + SMS) — TTL 7 days
├── transactionNo : String ← Unique task identifier
├── phoneId : String
├── type : String ← "ussd" | "sms"
├── ussd : String ← USSD code dialed (type=ussd)
├── destinationPhone : String ← Recipient number (sms or ussd transfer)
├── amount : String ← Transaction amount (optional, informational)
├── simSlot : Number ← 0-based SIM slot used
├── stepMessages : String[] ← USSD screen text at each step
├── finalMessage : String ← Last USSD/SMS response text
├── status : String ← SUCCESS | ERROR | TIMEOUT | SENT
├── receivedAt : Number ← Epoch ms when task was received from server
├── processedAt : Number ← Epoch ms when result was sent back
└── expireAt : Timestamp ← processedAt + 7 days — Firestore TTL⏱️ Firestore TTL Policies
Each sub-collection has an expireAt Timestamp field. Configure a TTL policy per collection in the Firebase Console so documents are automatically deleted when expired — no cron job or app logic required.
Firebase Console → Firestore → TTL Policies → Add policy Collection group Field Retention ───────────────── ────────── ───────────────────────────── logs expireAt auto-delete after 7 days transactions expireAt auto-delete after 7 days receivedSms expireAt auto-delete after 60 days Steps: 1. Firebase Console → Firestore Database → Indexes → TTL Policies tab 2. Click "Add TTL policy" 3. Collection group: logs | Field: expireAt → Save 4. Collection group: transactions | Field: expireAt → Save 5. Collection group: receivedSms | Field: expireAt → Save Note: TTL deletion may lag up to 24 h after the expiry time (Firebase guarantee). Expired documents are no longer returned in queries even before physical deletion.
🔒 Recommended Firestore Rules
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Group configuration — read/write requires Google auth (admin console)
match /configuration/{groupId} {
allow read, write: if request.auth != null;
}
// Phone documents — written by Android app (no auth) and admin console (with auth)
match /phones/{phoneId} {
allow read: if request.auth != null;
allow write: if true;
}
// Phone sub-collections: logs, receivedSms, transactions
match /phones/{phoneId}/{sub=**} {
allow read: if request.auth != null;
allow write: if true;
}
}
}📦 Package Diagram
com.romellfudi.ussd
├── server
│ ├── api ← REST API client (Retrofit)
│ │ └── PhoneServerApi
│ ├── auth ← Keycloak authentication layer
│ │ ├── AuthManager · AuthInterceptor · AuthAuthenticator
│ │ ├── AuthApi · TokenResponse
│ ├── config ← Firebase remote configuration
│ │ └── FirebaseConfigManager
│ ├── db ← Room database (SMS persistence)
│ │ ├── AppDatabase · SmsDao · SmsEntity
│ │ └── SyncCheckpoint · SyncCheckpointDao
│ ├── engine ← USSD execution engine
│ │ └── UssdExecutor
│ ├── model ← DTOs and state models
│ │ ├── UssdTask · UssdResult · SmsReceiveRequest
│ │ ├── TransactionState · TransactionLogEntry
│ │ └── ActivityLogManager
│ ├── receiver ← Android BroadcastReceiver
│ │ └── SmsReceiver
│ ├── service ← Android Foreground Service
│ │ └── PollingService
│ ├── sms ← SMS utilities
│ │ ├── SmsExecutor · SmsSyncManager · SmsImporter
│ ├── view ← Android UI Fragments
│ │ ├── DashboardFragment · LogFragment · SmsFragment
│ │ └── MainPagerAdapter
│ └── viewmodel ← MVVM ViewModels
│ ├── DashboardViewModel · SmsViewModel
└── ussdlibrary ← Android USSD accessibility library
└── USSDController · USSDServiceKT📚 Class Reference
server.api
| PhoneServerApi | Retrofit interface. poll(phoneId) — long-poll for next task; sendResult(result) — POST task outcome; smsReceive(request) — report incoming SMS. Read timeout 35 s (exceeds server hold time). |
server.auth
| AuthManager | Singleton. Keycloak client_credentials token lifecycle. init(), tryLogin(), refreshToken(), getValidToken() — auto-refreshes before expiry. Token persisted in SharedPreferences. |
| AuthInterceptor | OkHttp interceptor. Injects Authorization: Bearer <token> header on every request. Uses runBlocking to bridge suspend→sync (safe on IO threads). |
| AuthAuthenticator | OkHttp authenticator. Handles HTTP 401 by refreshing the token and retrying the original request. |
| AuthApi | Retrofit interface for the Keycloak token endpoint (POST /realms/{realm}/protocol/openid-connect/token). |
| TokenResponse | DTO: access_token, refresh_token, expires_in. |
server.config
| FirebaseConfigManager | Singleton. Real-time Firestore listener on phones/{phoneId}. Exposes config: LiveData<PhoneConfig> and configLoaded: LiveData<Boolean>. uploadPhoneDetails() merges hardware info (IMEI, SIM cards, serial). updateLastSeen() writes current epoch ms on each poll cycle — drives the Monitoring connectivity indicator. markOffline() sets lastSeen = 0 on graceful service stop so the dot turns red immediately. |
server.db
| AppDatabase | Room singleton database. Tables: sms_received, sync_checkpoint. |
| SmsEntity | Room entity for received SMS. Fields: smsId, msg, receivedFrom, simSlot, receivedDateTime, sentToServer, sentToFirebase. |
| SmsDao | DAO: insert(), getUnsentToServer(), getUnsentToFirebase(), markSentToServer(), markSentToFirebase(). |
| SyncCheckpoint | Stores the last inbox sync timestamp per source — prevents re-importing already-processed SMS on restarts. |
server.engine
| UssdExecutor | Executes multi-step USSD sessions via USSDController. Drives the Accessibility Service callback chain, replaces {pin} placeholders, and returns a UssdResult with all step messages. |
server.model
| UssdTask | Task dispatched by the server. Fields: transactionNo, phoneId, type (ussd|sms), ussd, stepList, pin, simSlot, destinationPhone, msg, amount, bypassDuplication (bool, default false — if true, skips destinationPhone+amount duplicate check; transactionNo check is always enforced). |
| UssdResult | Task outcome sent back to the server. Status: SUCCESS | ERROR | TIMEOUT | REJECTED_DUPLICATE. Includes stepMessages and finalMessage. |
| TransactionState | Sealed class: Idle | Running(task, currentStep, totalSteps, lastMessage) | Completed(result) | Failed(task, error). Drives the transaction card UI. |
| TransactionLogEntry | Lightweight history record (last 50). Fields: transactionNo, ussd, status, simSlot (0-based SIM index), timestamp. Rendered in the Dashboard history list with a colored left accent bar (green/red/orange per status) and a purple SIM badge pill ("SIM 1", "SIM 2"…). |
| ActivityLogManager | Singleton. Writes structured log entries (INFO/WARN/ERROR/DEBUG) to Firestore phones/{id}/logs on IO dispatcher. |
server.receiver · server.service · server.sms
| SmsReceiver | BroadcastReceiver for SMS_RECEIVED. Persists incoming SMS to Room, pushes to Firestore, triggers SmsSyncManager. |
| PollingService | Android foreground service. Starts auth, long-polls REST API, routes tasks to UssdExecutor or SmsExecutor, syncs idle SMS. Calls FirebaseConfigManager.updateLastSeen() on every 200/204 response and markOffline() in onDestroy() for real-time presence in the Monitoring panel. Exposes serverStatus, transactionState, transactionLog, lastPollTimestamp as LiveData. |
| SmsExecutor | Sends SMS via Android SmsManager for type="sms" tasks. Returns a UssdResult with status SENT or ERROR. |
| SmsSyncManager | Syncs pending Room SMS records to the REST server (POST /api/smsReceive) and to Firestore. Called on 204 (idle) and on connectivity restore. |
| SmsImporter | Incremental import of the device SMS inbox to Room at startup. Uses SyncCheckpoint to avoid re-importing messages already processed. |
server.view · server.viewmodel
| DashboardFragment | Main screen. Status indicators (server, accessibility, internet, Firebase). Start/Stop service buttons. Live transaction card with step progress. Transaction history list — each row shows a colored left accent bar (status), SIM badge pill, USSD code, and timestamp. |
| DashboardViewModel | Orchestrates phone identity (Android ID), network callback, Firestore config, accessibility check, and hardware detail upload (IMEI, SIM, serial). |
| LogFragment | Displays real-time Firestore activity logs for this phone. Supports level filtering. |
| SmsFragment | Paginated list of received SMS from the Room database via SmsViewModel. |
GET /api/poll/{phoneId}
Only the phoneId path parameter is required. No query parameters.{
"transactionNo": "TXN-20240215-001",
"type": "ussd",
"ussd": "*123#",
"stepList": ["1", "2", "PIN"],
"pin": "****",
"simSlot": 0,
"destinationPhone": "00221771234567", // optional — for money transfers
"amount": "5000", // optional — informational
"bypassDuplication": false, // optional — skips destinationPhone+amount dup check only
"phoneName": "Phone-F456", // admin-assigned display name
"phoneStatus": "active", // "active" | "blocked"
"simCards": [ // current SIM state (admin can set balances)
{ "slotNumber": 0, "name": "Orange", "phoneNumber": "+237691000001",
"mainBalance": "1 500 FCFA", "commissionBalance": "200 FCFA", "status": "active" },
{ "slotNumber": 1, "name": "MTN", "phoneNumber": "",
"mainBalance": "", "commissionBalance": "", "status": "active" }
]
}{
"transactionNo": "TXN-SMS-001",
"type": "sms",
"destinationPhone": "00221771234567",
"msg": "Your code is 1234",
"simSlot": 0,
"amount": "1000", // optional
"phoneName": "Phone-F456",
"phoneStatus": "active",
"simCards": [...]
}HTTP 204 No Content (phone metadata is still updated from query params)
{
"transactionNo": "TXN-20240215-001",
"phoneId": "abc123def456",
"type": "ussd",
"status": "SUCCESS",
"finalMessage": "Transaction successful. Balance: 1 000 FCFA"
}{
"transactionNo": "TXN-SMS-001",
"phoneId": "abc123def456",
"type": "sms",
"status": "SENT"
}{ "ok": true, "transactionNo": "TXN-20240215-001" }{
"phoneId": "abc123def456",
"smsId": "sys_12345",
"msg": "Your OTP code is 9182",
"receivedFrom": "+221771234567",
"simSlot": 0,
"receivedDateTime": 1739900000000
}{ "ok": true }{
"phoneId": "abc123def456", // required
"type": "ussd", // "ussd" | "sms"
"ussd": "*123#", // USSD string to dial
"stepList": ["1", "2"], // ordered responses to successive USSD prompts
"pin": "1234", // optional — injected in place of {pin} in stepList; masked in logs
"simSlot": 0, // 0-based SIM slot index
"destinationPhone": "00237691000001", // optional — recipient for money transfers
"amount": "5000", // optional — informational, not dialed
"bypassDuplication": false, // optional — if true, skips destinationPhone+amount dup check
"transactionNo": "TXN-TEST-001" // optional — auto-generated if omitted (reuse to test duplicates)
}{
"phoneId": "abc123def456", // required
"type": "sms",
"destinationPhone": "00237691000001", // required — SMS recipient
"msg": "Your code is 1234", // required — SMS body
"simSlot": 0,
"amount": "1000", // optional
"transactionNo": "TXN-SMS-001" // optional
}{ "ok": true, "transactionNo": "SIM-A3F9C21B" }[{
"phoneId": "abc123def456",
"phoneName": "Phone-F456", // admin-assigned display name
"localPhoneName": "Pixel 7", // device model (Build.MODEL), sent by the app on every poll
"diviseGroup": "AFRICREMIT",
"simSlots": 2, // updated automatically from device SIM data
"status": "CONNECTED", // "CONNECTED" | "DISCONNECTED" (computed from lastSeen < 90 s)
"phoneStatus": "active", // "active" | "blocked" — admin can set to block task execution
"lastSeen": 1739900000000,
"registeredAt": 1739800000000,
"simCards": [
{ "slotNumber": 0, "name": "Orange", "phoneNumber": "+237691000001",
"mainBalance": "1 500 FCFA", "commissionBalance": "200 FCFA", "status": "active" },
{ "slotNumber": 1, "name": "MTN", "phoneNumber": "",
"mainBalance": "", "commissionBalance": "", "status": "active" }
]
}]{ "ok": true, "deleted": "abc123def456" }[{
"phoneId": "abc123def456",
"level": "INFO",
"message": "Task delivered to phone: SIM-A3F9C21B",
"timestamp": 1739900000000
}]
The expireAt
field is automatically set by Firebase Cloud Functions when documents are created.
Use the button below to retroactively apply TTL to any existing documents that are missing it.