init
This commit is contained in:
65 files changed
+5782
No files matched your search
@@ -0,0 +1,104 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.ksp)
|
||||
alias(libs.plugins.kotlin.compose)
|
||||
alias(libs.plugins.kotlin.serialization)
|
||||
}
|
||||
|
||||
abstract class GenerateOpenApiAsset : DefaultTask() {
|
||||
@get:InputFile
|
||||
abstract val inputFile: RegularFileProperty
|
||||
|
||||
@get:OutputDirectory
|
||||
abstract val outputDirectory: DirectoryProperty
|
||||
|
||||
@TaskAction
|
||||
fun generate() {
|
||||
val destination = outputDirectory.file("openapi.yaml").get().asFile
|
||||
destination.parentFile.mkdirs()
|
||||
inputFile.get().asFile.copyTo(destination, overwrite = true)
|
||||
}
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.androidsmsgateway"
|
||||
compileSdk {
|
||||
version = release(37)
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.androidsmsgateway"
|
||||
minSdk = 26
|
||||
targetSdk = 37
|
||||
versionCode = 1
|
||||
versionName = "0.1.0"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
buildConfig = true
|
||||
compose = true
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(platform(libs.androidx.compose.bom))
|
||||
implementation(libs.androidx.activity.compose)
|
||||
implementation(libs.androidx.compose.material3)
|
||||
implementation(libs.androidx.compose.material.icons.extended)
|
||||
implementation(libs.androidx.compose.ui)
|
||||
implementation(libs.androidx.compose.ui.tooling.preview)
|
||||
implementation(libs.androidx.core.ktx)
|
||||
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||
implementation(libs.androidx.lifecycle.viewmodel.compose)
|
||||
implementation(libs.androidx.room.ktx)
|
||||
implementation(libs.androidx.room.runtime)
|
||||
implementation(libs.kotlinx.coroutines.android)
|
||||
implementation(libs.kotlinx.serialization.json)
|
||||
implementation(libs.nanohttpd)
|
||||
implementation(libs.swagger.ui)
|
||||
|
||||
ksp(libs.androidx.room.compiler)
|
||||
|
||||
testImplementation(libs.junit)
|
||||
testImplementation(libs.kotlinx.coroutines.test)
|
||||
|
||||
androidTestImplementation(libs.androidx.test.espresso.core)
|
||||
androidTestImplementation(libs.androidx.test.junit)
|
||||
|
||||
debugImplementation(libs.androidx.compose.ui.tooling)
|
||||
}
|
||||
|
||||
ksp {
|
||||
arg("room.schemaLocation", "$projectDir/schemas")
|
||||
}
|
||||
|
||||
val generateOpenApiAsset = tasks.register<GenerateOpenApiAsset>("generateOpenApiAsset") {
|
||||
inputFile.set(rootProject.layout.projectDirectory.file("openapi.yaml"))
|
||||
outputDirectory.set(layout.buildDirectory.dir("generated/openapiAssets"))
|
||||
}
|
||||
|
||||
androidComponents {
|
||||
onVariants { variant ->
|
||||
variant.sources.assets?.addGeneratedSourceDirectory(
|
||||
generateOpenApiAsset,
|
||||
GenerateOpenApiAsset::outputDirectory,
|
||||
)
|
||||
}
|
||||
}
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
# Project-specific R8 rules belong here when release shrinking is enabled.
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"database": {
|
||||
"version": 1,
|
||||
"identityHash": "50a812bbacc079987084d208ae9a1a5a",
|
||||
"entities": [
|
||||
{
|
||||
"tableName": "incoming_sms",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `sender` TEXT NOT NULL, `message` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, `status` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "sender",
|
||||
"columnName": "sender",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "message",
|
||||
"columnName": "message",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "receivedAt",
|
||||
"columnName": "receivedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "status",
|
||||
"columnName": "status",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "createdAt",
|
||||
"columnName": "createdAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_incoming_sms_receivedAt",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"receivedAt"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_incoming_sms_receivedAt` ON `${TABLE_NAME}` (`receivedAt`)"
|
||||
},
|
||||
{
|
||||
"name": "index_incoming_sms_sender",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"sender"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_incoming_sms_sender` ON `${TABLE_NAME}` (`sender`)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "outgoing_sms",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `recipient` TEXT NOT NULL, `message` TEXT NOT NULL, `requestedAt` INTEGER NOT NULL, `status` TEXT NOT NULL, `errorCode` TEXT, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "recipient",
|
||||
"columnName": "recipient",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "message",
|
||||
"columnName": "message",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "requestedAt",
|
||||
"columnName": "requestedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "status",
|
||||
"columnName": "status",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "errorCode",
|
||||
"columnName": "errorCode",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "updatedAt",
|
||||
"columnName": "updatedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_outgoing_sms_requestedAt",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"requestedAt"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_outgoing_sms_requestedAt` ON `${TABLE_NAME}` (`requestedAt`)"
|
||||
},
|
||||
{
|
||||
"name": "index_outgoing_sms_recipient",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"recipient"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_outgoing_sms_recipient` ON `${TABLE_NAME}` (`recipient`)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "request_logs",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `timestamp` INTEGER NOT NULL, `method` TEXT NOT NULL, `path` TEXT NOT NULL, `statusCode` INTEGER NOT NULL, `clientIp` TEXT NOT NULL, `durationMs` INTEGER NOT NULL, `success` INTEGER NOT NULL)",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "timestamp",
|
||||
"columnName": "timestamp",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "method",
|
||||
"columnName": "method",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "path",
|
||||
"columnName": "path",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "statusCode",
|
||||
"columnName": "statusCode",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "clientIp",
|
||||
"columnName": "clientIp",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "durationMs",
|
||||
"columnName": "durationMs",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "success",
|
||||
"columnName": "success",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_request_logs_timestamp",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"timestamp"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_request_logs_timestamp` ON `${TABLE_NAME}` (`timestamp`)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "app_settings",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `deviceId` TEXT NOT NULL, `port` INTEGER NOT NULL, `bindAddress` TEXT NOT NULL, `serverEnabled` INTEGER NOT NULL, `startOnBoot` INTEGER NOT NULL, `authenticationEnabled` INTEGER NOT NULL, `apiKeyHash` TEXT NOT NULL, `allowlistEnabled` INTEGER NOT NULL, `allowedIps` TEXT NOT NULL, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "deviceId",
|
||||
"columnName": "deviceId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "port",
|
||||
"columnName": "port",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "bindAddress",
|
||||
"columnName": "bindAddress",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "serverEnabled",
|
||||
"columnName": "serverEnabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "startOnBoot",
|
||||
"columnName": "startOnBoot",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "authenticationEnabled",
|
||||
"columnName": "authenticationEnabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "apiKeyHash",
|
||||
"columnName": "apiKeyHash",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "allowlistEnabled",
|
||||
"columnName": "allowlistEnabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "allowedIps",
|
||||
"columnName": "allowedIps",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"setupQueries": [
|
||||
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '50a812bbacc079987084d208ae9a1a5a')"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.androidsmsgateway.data.local
|
||||
|
||||
import androidx.room.Room
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class GatewayDatabaseTest {
|
||||
private lateinit var database: GatewayDatabase
|
||||
private lateinit var dao: GatewayDao
|
||||
|
||||
@Before
|
||||
fun createDatabase() {
|
||||
database = Room.inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext(), GatewayDatabase::class.java)
|
||||
.allowMainThreadQueries()
|
||||
.build()
|
||||
dao = database.gatewayDao()
|
||||
}
|
||||
|
||||
@After
|
||||
fun closeDatabase() = database.close()
|
||||
|
||||
@Test
|
||||
fun incomingOutgoingSettingsAndLogsPersist() = runBlocking {
|
||||
dao.insertIncoming(IncomingSmsEntity("in-1", "+12025550123", "hello", 10, "RECEIVED", 10))
|
||||
dao.insertOutgoing(OutgoingSmsEntity("out-1", "+12025550124", "world", 20, "PENDING", updatedAt = 20))
|
||||
dao.saveSettings(AppSettingsEntity(deviceId = "device-1"))
|
||||
dao.insertRequestLog(RequestLogEntity(timestamp = 30, method = "GET", path = "/api/v1/health", statusCode = 200, clientIp = "127.0.0.1", durationMs = 2, success = true))
|
||||
|
||||
assertEquals("hello", dao.incomingById("in-1")?.message)
|
||||
assertEquals("world", dao.outgoingById("out-1")?.message)
|
||||
assertEquals("device-1", dao.settings()?.deviceId)
|
||||
assertEquals(1L, dao.observeRequestCount().first())
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package com.androidsmsgateway.server
|
||||
|
||||
import androidx.room.Room
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.androidsmsgateway.data.GatewayRepository
|
||||
import com.androidsmsgateway.data.SettingsRepository
|
||||
import com.androidsmsgateway.data.local.AppSettingsEntity
|
||||
import com.androidsmsgateway.data.local.GatewayDatabase
|
||||
import com.androidsmsgateway.domain.ServerSnapshot
|
||||
import com.androidsmsgateway.domain.ServerState
|
||||
import com.androidsmsgateway.sms.SmsSender
|
||||
import com.androidsmsgateway.sms.SmsSubmission
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.ServerSocket
|
||||
import java.net.URL
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.flow.first
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class GatewayHttpServerIntegrationTest {
|
||||
private lateinit var database: GatewayDatabase
|
||||
private var server: GatewayHttpServer? = null
|
||||
|
||||
@Before
|
||||
fun createDatabase() {
|
||||
database = Room.inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext(), GatewayDatabase::class.java).build()
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
server?.stop()
|
||||
database.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun healthEndpointRunsThroughEmbeddedTransportAndIsLogged() = runBlocking {
|
||||
val port = ServerSocket(0).use { it.localPort }
|
||||
val dao = database.gatewayDao()
|
||||
dao.saveSettings(
|
||||
AppSettingsEntity(
|
||||
deviceId = "integration-device",
|
||||
port = port,
|
||||
bindAddress = "127.0.0.1",
|
||||
authenticationEnabled = false,
|
||||
),
|
||||
)
|
||||
val gatewayRepository = GatewayRepository(dao)
|
||||
val router = ApiRouter(
|
||||
repository = gatewayRepository,
|
||||
settingsRepository = SettingsRepository(dao),
|
||||
smsSender = object : SmsSender {
|
||||
override suspend fun send(recipient: String, message: String) = SmsSubmission("fake-id", "pending")
|
||||
},
|
||||
serverSnapshot = { ServerSnapshot(ServerState.RUNNING, System.currentTimeMillis(), "127.0.0.1", port) },
|
||||
documentationProvider = PackagedApiDocumentationProvider(ApplicationProvider.getApplicationContext()),
|
||||
)
|
||||
server = GatewayHttpServer("127.0.0.1", port, router).also { it.start(5_000, false) }
|
||||
|
||||
val connection = URL("http://127.0.0.1:$port/api/v1/health").openConnection() as HttpURLConnection
|
||||
connection.connectTimeout = 3_000
|
||||
connection.readTimeout = 3_000
|
||||
assertEquals(200, connection.responseCode)
|
||||
val body = connection.inputStream.bufferedReader().use { it.readText() }
|
||||
assertTrue(body.contains("integration-device"))
|
||||
assertTrue(body.contains("\"status\":\"ok\""))
|
||||
assertEquals(1L, dao.observeRequestCount().first())
|
||||
|
||||
val docs = URL("http://127.0.0.1:$port/docs").openConnection() as HttpURLConnection
|
||||
assertEquals(200, docs.responseCode)
|
||||
assertTrue(docs.contentType.startsWith("text/html"))
|
||||
assertTrue(docs.inputStream.bufferedReader().use { it.readText() }.contains("swagger-ui"))
|
||||
assertEquals(2L, dao.observeRequestCount().first())
|
||||
|
||||
val contract = URL("http://127.0.0.1:$port/docs/openapi.yaml").openConnection() as HttpURLConnection
|
||||
assertEquals(200, contract.responseCode)
|
||||
assertTrue(contract.inputStream.bufferedReader().use { it.readText() }.startsWith("openapi: 3.1.0"))
|
||||
|
||||
val swaggerBundle = URL("http://127.0.0.1:$port/docs/swagger-ui-bundle.js").openConnection() as HttpURLConnection
|
||||
assertEquals(200, swaggerBundle.responseCode)
|
||||
assertTrue(swaggerBundle.inputStream.bufferedReader().use { it.readText() }.contains("SwaggerUIBundle"))
|
||||
assertEquals(4L, dao.observeRequestCount().first())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-feature android:name="android.hardware.telephony" android:required="true" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.SEND_SMS" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_SMS" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
|
||||
<application
|
||||
android:name=".GatewayApplication"
|
||||
android:allowBackup="false"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:fullBackupContent="@xml/backup_rules"
|
||||
android:icon="@drawable/ic_gateway"
|
||||
android:label="@string/app_name"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.AndroidSmsGateway">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<service
|
||||
android:name=".server.GatewayServerService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="specialUse">
|
||||
<property
|
||||
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||
android:value="embedded HTTP SMS gateway for user-managed backend connections" />
|
||||
</service>
|
||||
|
||||
<receiver
|
||||
android:name=".sms.IncomingSmsReceiver"
|
||||
android:exported="true"
|
||||
android:permission="android.permission.BROADCAST_SMS">
|
||||
<intent-filter>
|
||||
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<receiver
|
||||
android:name=".sms.SmsStatusReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<receiver
|
||||
android:name=".server.BootReceiver"
|
||||
android:enabled="true"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.androidsmsgateway
|
||||
|
||||
import android.app.Application
|
||||
import com.androidsmsgateway.di.AppContainer
|
||||
|
||||
class GatewayApplication : Application() {
|
||||
val container: AppContainer by lazy { AppContainer(this) }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.androidsmsgateway
|
||||
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
setContent {
|
||||
SmsGatewayApp()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package com.androidsmsgateway
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.outlined.ReceiptLong
|
||||
import androidx.compose.material.icons.outlined.Dashboard
|
||||
import androidx.compose.material.icons.outlined.Dns
|
||||
import androidx.compose.material.icons.outlined.Security
|
||||
import androidx.compose.material.icons.outlined.Sms
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.NavigationBar
|
||||
import androidx.compose.material3.NavigationBarItem
|
||||
import androidx.compose.material3.NavigationRail
|
||||
import androidx.compose.material3.NavigationRailItem
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import com.androidsmsgateway.ui.GatewayViewModel
|
||||
import com.androidsmsgateway.ui.components.BrandMark
|
||||
import com.androidsmsgateway.ui.screens.DashboardScreen
|
||||
import com.androidsmsgateway.ui.screens.LogsScreen
|
||||
import com.androidsmsgateway.ui.screens.MessagesScreen
|
||||
import com.androidsmsgateway.ui.screens.PermissionsScreen
|
||||
import com.androidsmsgateway.ui.screens.SecurityScreen
|
||||
import com.androidsmsgateway.ui.screens.ServerSettingsScreen
|
||||
import com.androidsmsgateway.ui.theme.GatewayTheme
|
||||
|
||||
private enum class Screen(val label: String, val icon: ImageVector) {
|
||||
DASHBOARD("Dashboard", Icons.Outlined.Dashboard),
|
||||
MESSAGES("Messages", Icons.Outlined.Sms),
|
||||
LOGS("Logs", Icons.AutoMirrored.Outlined.ReceiptLong),
|
||||
SERVER("Server", Icons.Outlined.Dns),
|
||||
SECURITY("Security", Icons.Outlined.Security),
|
||||
PERMISSIONS("Permissions", Icons.Outlined.Security),
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SmsGatewayApp(viewModel: GatewayViewModel = viewModel()) {
|
||||
val state by viewModel.state.collectAsState()
|
||||
var screenName by rememberSaveable { mutableStateOf(Screen.DASHBOARD.name) }
|
||||
val screen = Screen.valueOf(screenName)
|
||||
val snackbar = remember { SnackbarHostState() }
|
||||
|
||||
BackHandler(enabled = screen == Screen.PERMISSIONS) {
|
||||
screenName = Screen.SERVER.name
|
||||
}
|
||||
|
||||
LaunchedEffect(state.message) {
|
||||
state.message?.let {
|
||||
snackbar.showSnackbar(it)
|
||||
viewModel.clearMessage()
|
||||
}
|
||||
}
|
||||
|
||||
GatewayTheme {
|
||||
BoxWithConstraints(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background)) {
|
||||
val expanded = maxWidth >= 840.dp
|
||||
Scaffold(
|
||||
containerColor = MaterialTheme.colorScheme.background,
|
||||
snackbarHost = { SnackbarHost(snackbar) },
|
||||
bottomBar = {
|
||||
if (!expanded && screen != Screen.PERMISSIONS) {
|
||||
MobileNavigation(screen) { screenName = it.name }
|
||||
}
|
||||
},
|
||||
) { contentPadding ->
|
||||
Row(Modifier.fillMaxSize().padding(contentPadding)) {
|
||||
if (expanded && screen != Screen.PERMISSIONS) {
|
||||
TabletNavigation(screen) { screenName = it.name }
|
||||
}
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) {
|
||||
Box(Modifier.fillMaxSize().widthIn(max = 1180.dp)) {
|
||||
if (state.loading) {
|
||||
LoadingScreen()
|
||||
} else {
|
||||
when (screen) {
|
||||
Screen.DASHBOARD -> DashboardScreen(
|
||||
state = state,
|
||||
expanded = expanded,
|
||||
start = viewModel::startServer,
|
||||
stop = viewModel::stopServer,
|
||||
openSecurity = { screenName = Screen.SECURITY.name },
|
||||
openPermissions = { screenName = Screen.PERMISSIONS.name },
|
||||
)
|
||||
Screen.MESSAGES -> MessagesScreen(state)
|
||||
Screen.LOGS -> LogsScreen(state)
|
||||
Screen.SERVER -> ServerSettingsScreen(
|
||||
state = state,
|
||||
save = viewModel::saveServerSettings,
|
||||
permissions = { screenName = Screen.PERMISSIONS.name },
|
||||
)
|
||||
Screen.SECURITY -> SecurityScreen(state, viewModel)
|
||||
Screen.PERMISSIONS -> PermissionsScreen(onBack = { screenName = Screen.SERVER.name })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MobileNavigation(selected: Screen, onSelect: (Screen) -> Unit) {
|
||||
NavigationBar(containerColor = MaterialTheme.colorScheme.surface) {
|
||||
Screen.entries.filter { it != Screen.PERMISSIONS }.forEach { item ->
|
||||
NavigationBarItem(
|
||||
selected = selected == item,
|
||||
onClick = { onSelect(item) },
|
||||
icon = { Icon(item.icon, contentDescription = null) },
|
||||
label = {
|
||||
Text(
|
||||
text = item.label,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
maxLines = 1,
|
||||
softWrap = false,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TabletNavigation(selected: Screen, onSelect: (Screen) -> Unit) {
|
||||
NavigationRail(
|
||||
modifier = Modifier.fillMaxHeight(),
|
||||
containerColor = MaterialTheme.colorScheme.surface,
|
||||
header = { Box(Modifier.padding(vertical = 22.dp)) { BrandMark(Modifier.size(42.dp)) } },
|
||||
) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(7.dp)) {
|
||||
Screen.entries.filter { it != Screen.PERMISSIONS }.forEach { item ->
|
||||
NavigationRailItem(
|
||||
selected = selected == item,
|
||||
onClick = { onSelect(item) },
|
||||
icon = { Icon(item.icon, contentDescription = null) },
|
||||
label = { Text(item.label) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LoadingScreen() {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(16.dp)) {
|
||||
BrandMark(Modifier.size(52.dp))
|
||||
CircularProgressIndicator()
|
||||
Text("Preparing gateway", style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.androidsmsgateway.data
|
||||
|
||||
import com.androidsmsgateway.data.local.GatewayDao
|
||||
import com.androidsmsgateway.data.local.IncomingSmsEntity
|
||||
import com.androidsmsgateway.data.local.OutgoingSmsEntity
|
||||
import com.androidsmsgateway.data.local.RequestLogEntity
|
||||
|
||||
class GatewayRepository(private val dao: GatewayDao) {
|
||||
fun incomingMessages(limit: Int = 200) = dao.observeIncoming(limit)
|
||||
fun outgoingMessages(limit: Int = 200) = dao.observeOutgoing(limit)
|
||||
fun requestLogs(limit: Int = 500) = dao.observeRequestLogs(limit)
|
||||
fun incomingCount() = dao.observeIncomingCount()
|
||||
fun outgoingCount() = dao.observeOutgoingCount()
|
||||
fun requestCount() = dao.observeRequestCount()
|
||||
fun lastRequest() = dao.observeLastRequest()
|
||||
|
||||
suspend fun saveIncoming(message: IncomingSmsEntity) = dao.insertIncoming(message)
|
||||
suspend fun saveOutgoing(message: OutgoingSmsEntity) = dao.insertOutgoing(message)
|
||||
suspend fun updateOutgoing(message: OutgoingSmsEntity) = dao.updateOutgoing(message)
|
||||
suspend fun incomingById(id: String) = dao.incomingById(id)
|
||||
suspend fun outgoingById(id: String) = dao.outgoingById(id)
|
||||
suspend fun incomingPage(query: String, page: Int, size: Int) =
|
||||
dao.incomingPage(query, size, (page - 1) * size)
|
||||
suspend fun outgoingPage(query: String, page: Int, size: Int) =
|
||||
dao.outgoingPage(query, size, (page - 1) * size)
|
||||
suspend fun messagePage(direction: String, query: String, page: Int, size: Int) =
|
||||
dao.messagePage(direction, query, size, (page - 1) * size)
|
||||
|
||||
suspend fun logRequest(log: RequestLogEntity) {
|
||||
dao.insertRequestLog(log)
|
||||
dao.trimRequestLogs(10_000)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.androidsmsgateway.data
|
||||
|
||||
import com.androidsmsgateway.data.local.AppSettingsEntity
|
||||
import com.androidsmsgateway.data.local.GatewayDao
|
||||
import com.androidsmsgateway.domain.GatewaySettings
|
||||
import com.androidsmsgateway.domain.toDomain
|
||||
import java.util.UUID
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.filterNotNull
|
||||
import kotlinx.coroutines.flow.map
|
||||
|
||||
class SettingsRepository(private val dao: GatewayDao) {
|
||||
val settings: Flow<GatewaySettings> = dao.observeSettings().filterNotNull().map { it.toDomain() }
|
||||
|
||||
suspend fun ensureInitialized(): GatewaySettings {
|
||||
val existing = dao.settings()
|
||||
if (existing != null) return existing.toDomain()
|
||||
val created = AppSettingsEntity(deviceId = UUID.randomUUID().toString())
|
||||
dao.saveSettings(created)
|
||||
return created.toDomain()
|
||||
}
|
||||
|
||||
suspend fun current(): GatewaySettings = ensureInitialized()
|
||||
|
||||
suspend fun update(transform: (AppSettingsEntity) -> AppSettingsEntity): GatewaySettings {
|
||||
val current = dao.settings() ?: AppSettingsEntity(deviceId = UUID.randomUUID().toString())
|
||||
val updated = transform(current)
|
||||
dao.saveSettings(updated)
|
||||
return updated.toDomain()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.androidsmsgateway.data.local
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
@Entity(tableName = "incoming_sms", indices = [Index("receivedAt"), Index("sender")])
|
||||
data class IncomingSmsEntity(
|
||||
@PrimaryKey val id: String,
|
||||
val sender: String,
|
||||
val message: String,
|
||||
val receivedAt: Long,
|
||||
val status: String,
|
||||
val createdAt: Long,
|
||||
)
|
||||
|
||||
@Entity(tableName = "outgoing_sms", indices = [Index("requestedAt"), Index("recipient")])
|
||||
data class OutgoingSmsEntity(
|
||||
@PrimaryKey val id: String,
|
||||
val recipient: String,
|
||||
val message: String,
|
||||
val requestedAt: Long,
|
||||
val status: String,
|
||||
val errorCode: String? = null,
|
||||
val updatedAt: Long,
|
||||
)
|
||||
|
||||
@Entity(tableName = "request_logs", indices = [Index("timestamp")])
|
||||
data class RequestLogEntity(
|
||||
@PrimaryKey(autoGenerate = true) val id: Long = 0,
|
||||
val timestamp: Long,
|
||||
val method: String,
|
||||
val path: String,
|
||||
val statusCode: Int,
|
||||
val clientIp: String,
|
||||
val durationMs: Long,
|
||||
val success: Boolean,
|
||||
)
|
||||
|
||||
@Entity(tableName = "app_settings")
|
||||
data class AppSettingsEntity(
|
||||
@PrimaryKey val id: Int = SINGLETON_ID,
|
||||
val deviceId: String,
|
||||
val port: Int = DEFAULT_PORT,
|
||||
val bindAddress: String = DEFAULT_BIND_ADDRESS,
|
||||
val serverEnabled: Boolean = false,
|
||||
val startOnBoot: Boolean = false,
|
||||
val authenticationEnabled: Boolean = true,
|
||||
val apiKeyHash: String = "",
|
||||
val allowlistEnabled: Boolean = false,
|
||||
val allowedIps: String = "",
|
||||
) {
|
||||
companion object {
|
||||
const val SINGLETON_ID = 1
|
||||
const val DEFAULT_PORT = 8080
|
||||
const val DEFAULT_BIND_ADDRESS = "0.0.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
data class MessageRecord(
|
||||
val id: String,
|
||||
val direction: String,
|
||||
val address: String,
|
||||
val message: String,
|
||||
val timestamp: Long,
|
||||
val status: String,
|
||||
val errorCode: String?,
|
||||
)
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.androidsmsgateway.data.local
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Update
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
interface GatewayDao {
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertIncoming(message: IncomingSmsEntity)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertOutgoing(message: OutgoingSmsEntity)
|
||||
|
||||
@Update
|
||||
suspend fun updateOutgoing(message: OutgoingSmsEntity)
|
||||
|
||||
@Query("SELECT * FROM incoming_sms WHERE id = :id")
|
||||
suspend fun incomingById(id: String): IncomingSmsEntity?
|
||||
|
||||
@Query("SELECT * FROM outgoing_sms WHERE id = :id")
|
||||
suspend fun outgoingById(id: String): OutgoingSmsEntity?
|
||||
|
||||
@Query("SELECT * FROM incoming_sms WHERE (:query = '' OR sender LIKE '%' || :query || '%' OR message LIKE '%' || :query || '%') ORDER BY receivedAt DESC LIMIT :limit OFFSET :offset")
|
||||
suspend fun incomingPage(query: String, limit: Int, offset: Int): List<IncomingSmsEntity>
|
||||
|
||||
@Query("SELECT * FROM outgoing_sms WHERE (:query = '' OR recipient LIKE '%' || :query || '%' OR message LIKE '%' || :query || '%' OR status LIKE '%' || :query || '%') ORDER BY requestedAt DESC LIMIT :limit OFFSET :offset")
|
||||
suspend fun outgoingPage(query: String, limit: Int, offset: Int): List<OutgoingSmsEntity>
|
||||
|
||||
@Query("""
|
||||
SELECT * FROM (
|
||||
SELECT id, 'incoming' AS direction, sender AS address, message, receivedAt AS timestamp, status, NULL AS errorCode FROM incoming_sms
|
||||
UNION ALL
|
||||
SELECT id, 'outgoing' AS direction, recipient AS address, message, requestedAt AS timestamp, status, errorCode FROM outgoing_sms
|
||||
)
|
||||
WHERE (:direction = 'all' OR direction = :direction)
|
||||
AND (:query = '' OR address LIKE '%' || :query || '%' OR message LIKE '%' || :query || '%' OR status LIKE '%' || :query || '%')
|
||||
ORDER BY timestamp DESC
|
||||
LIMIT :limit OFFSET :offset
|
||||
""")
|
||||
suspend fun messagePage(direction: String, query: String, limit: Int, offset: Int): List<MessageRecord>
|
||||
|
||||
@Query("SELECT * FROM incoming_sms ORDER BY receivedAt DESC LIMIT :limit")
|
||||
fun observeIncoming(limit: Int): Flow<List<IncomingSmsEntity>>
|
||||
|
||||
@Query("SELECT * FROM outgoing_sms ORDER BY requestedAt DESC LIMIT :limit")
|
||||
fun observeOutgoing(limit: Int): Flow<List<OutgoingSmsEntity>>
|
||||
|
||||
@Query("SELECT COUNT(*) FROM incoming_sms")
|
||||
fun observeIncomingCount(): Flow<Long>
|
||||
|
||||
@Query("SELECT COUNT(*) FROM outgoing_sms")
|
||||
fun observeOutgoingCount(): Flow<Long>
|
||||
|
||||
@Insert
|
||||
suspend fun insertRequestLog(log: RequestLogEntity)
|
||||
|
||||
@Query("SELECT * FROM request_logs ORDER BY timestamp DESC LIMIT :limit")
|
||||
fun observeRequestLogs(limit: Int): Flow<List<RequestLogEntity>>
|
||||
|
||||
@Query("SELECT COUNT(*) FROM request_logs")
|
||||
fun observeRequestCount(): Flow<Long>
|
||||
|
||||
@Query("SELECT * FROM request_logs ORDER BY timestamp DESC LIMIT 1")
|
||||
fun observeLastRequest(): Flow<RequestLogEntity?>
|
||||
|
||||
@Query("DELETE FROM request_logs WHERE id NOT IN (SELECT id FROM request_logs ORDER BY timestamp DESC LIMIT :keep)")
|
||||
suspend fun trimRequestLogs(keep: Int)
|
||||
|
||||
@Query("SELECT * FROM app_settings WHERE id = 1")
|
||||
fun observeSettings(): Flow<AppSettingsEntity?>
|
||||
|
||||
@Query("SELECT * FROM app_settings WHERE id = 1")
|
||||
suspend fun settings(): AppSettingsEntity?
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun saveSettings(settings: AppSettingsEntity)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.androidsmsgateway.data.local
|
||||
|
||||
import androidx.room.Database
|
||||
import androidx.room.RoomDatabase
|
||||
|
||||
@Database(
|
||||
entities = [
|
||||
IncomingSmsEntity::class,
|
||||
OutgoingSmsEntity::class,
|
||||
RequestLogEntity::class,
|
||||
AppSettingsEntity::class,
|
||||
],
|
||||
version = 1,
|
||||
exportSchema = true,
|
||||
)
|
||||
abstract class GatewayDatabase : RoomDatabase() {
|
||||
abstract fun gatewayDao(): GatewayDao
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.androidsmsgateway.di
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.Room
|
||||
import com.androidsmsgateway.data.GatewayRepository
|
||||
import com.androidsmsgateway.data.SettingsRepository
|
||||
import com.androidsmsgateway.data.local.GatewayDatabase
|
||||
import com.androidsmsgateway.server.GatewayServerController
|
||||
import com.androidsmsgateway.sms.AndroidSmsSender
|
||||
|
||||
class AppContainer(context: Context) {
|
||||
val database: GatewayDatabase by lazy {
|
||||
Room.databaseBuilder(context, GatewayDatabase::class.java, "sms-gateway.db").build()
|
||||
}
|
||||
|
||||
val gatewayRepository: GatewayRepository by lazy { GatewayRepository(database.gatewayDao()) }
|
||||
val settingsRepository: SettingsRepository by lazy { SettingsRepository(database.gatewayDao()) }
|
||||
val smsSender by lazy { AndroidSmsSender(context.applicationContext, gatewayRepository) }
|
||||
val serverController by lazy { GatewayServerController(context.applicationContext, settingsRepository, gatewayRepository, smsSender) }
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.androidsmsgateway.domain
|
||||
|
||||
import com.androidsmsgateway.data.local.AppSettingsEntity
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
enum class MessageDirection { INCOMING, OUTGOING }
|
||||
enum class MessageStatus { RECEIVED, PENDING, SENT, FAILED }
|
||||
enum class ServerState { STOPPED, STARTING, RUNNING, STOPPING, ERROR }
|
||||
|
||||
data class ServerSnapshot(
|
||||
val state: ServerState = ServerState.STOPPED,
|
||||
val startedAt: Long? = null,
|
||||
val ipAddress: String = "Unavailable",
|
||||
val port: Int = AppSettingsEntity.DEFAULT_PORT,
|
||||
val lastError: String? = null,
|
||||
) {
|
||||
fun uptimeMillis(now: Long = System.currentTimeMillis()): Long =
|
||||
startedAt?.let { (now - it).coerceAtLeast(0) } ?: 0
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class ErrorBody(val code: String, val message: String)
|
||||
|
||||
@Serializable
|
||||
data class ErrorResponse(val success: Boolean = false, val error: ErrorBody)
|
||||
|
||||
@Serializable
|
||||
data class SuccessResponse<T>(val success: Boolean = true, val data: T)
|
||||
|
||||
data class GatewaySettings(
|
||||
val deviceId: String,
|
||||
val port: Int,
|
||||
val bindAddress: String,
|
||||
val serverEnabled: Boolean,
|
||||
val startOnBoot: Boolean,
|
||||
val authenticationEnabled: Boolean,
|
||||
val apiKeyHash: String,
|
||||
val allowlistEnabled: Boolean,
|
||||
val allowedIps: Set<String>,
|
||||
)
|
||||
|
||||
fun AppSettingsEntity.toDomain() = GatewaySettings(
|
||||
deviceId = deviceId,
|
||||
port = port,
|
||||
bindAddress = bindAddress,
|
||||
serverEnabled = serverEnabled,
|
||||
startOnBoot = startOnBoot,
|
||||
authenticationEnabled = authenticationEnabled,
|
||||
apiKeyHash = apiKeyHash,
|
||||
allowlistEnabled = allowlistEnabled,
|
||||
allowedIps = allowedIps.lineSequence().map(String::trim).filter(String::isNotEmpty).toSet(),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.androidsmsgateway.security
|
||||
|
||||
import com.androidsmsgateway.domain.GatewaySettings
|
||||
import java.net.InetAddress
|
||||
import java.security.MessageDigest
|
||||
|
||||
enum class AccessDecision { ALLOWED, IP_DENIED, MISSING_CREDENTIALS, INVALID_CREDENTIALS, NOT_CONFIGURED }
|
||||
|
||||
object SecurityPolicy {
|
||||
fun evaluate(settings: GatewaySettings, clientIp: String, headers: Map<String, String>): AccessDecision {
|
||||
val normalizedIp = normalizeIp(clientIp)
|
||||
if (settings.allowlistEnabled && normalizedIp !in settings.allowedIps.map(::normalizeIp)) {
|
||||
return AccessDecision.IP_DENIED
|
||||
}
|
||||
if (!settings.authenticationEnabled) return AccessDecision.ALLOWED
|
||||
if (settings.apiKeyHash.isBlank()) return AccessDecision.NOT_CONFIGURED
|
||||
|
||||
val authorization = headers.entries.firstOrNull { it.key.equals("authorization", true) }?.value
|
||||
val headerKey = headers.entries.firstOrNull { it.key.equals("x-api-key", true) }?.value
|
||||
val apiKey = authorization?.takeIf { it.startsWith("Bearer ", true) }?.substringAfter(' ') ?: headerKey
|
||||
if (apiKey.isNullOrBlank()) return AccessDecision.MISSING_CREDENTIALS
|
||||
return if (constantTimeEquals(settings.apiKeyHash, hashApiKey(apiKey))) {
|
||||
AccessDecision.ALLOWED
|
||||
} else {
|
||||
AccessDecision.INVALID_CREDENTIALS
|
||||
}
|
||||
}
|
||||
|
||||
fun hashApiKey(apiKey: String): String = MessageDigest.getInstance("SHA-256")
|
||||
.digest(apiKey.toByteArray(Charsets.UTF_8))
|
||||
.joinToString("") { "%02x".format(it) }
|
||||
|
||||
fun isValidIp(value: String): Boolean {
|
||||
val candidate = value.trim()
|
||||
if (candidate.isEmpty() || candidate.any { it !in "0123456789abcdefABCDEF:." }) return false
|
||||
return runCatching { InetAddress.getByName(candidate) }.isSuccess
|
||||
}
|
||||
|
||||
private fun normalizeIp(value: String): String = runCatching {
|
||||
InetAddress.getByName(value.substringBefore('%')).hostAddress
|
||||
}.getOrDefault(value.trim())
|
||||
|
||||
private fun constantTimeEquals(expected: String, actual: String): Boolean =
|
||||
MessageDigest.isEqual(expected.toByteArray(), actual.toByteArray())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.androidsmsgateway.server
|
||||
|
||||
import android.content.Context
|
||||
|
||||
interface ApiDocumentationProvider {
|
||||
fun openApi(): String
|
||||
fun indexHtml(): String
|
||||
fun initializerJavaScript(): String
|
||||
fun swaggerUiAsset(name: String): String
|
||||
}
|
||||
|
||||
class PackagedApiDocumentationProvider(private val context: Context) : ApiDocumentationProvider {
|
||||
override fun openApi(): String = context.assets.open("openapi.yaml").bufferedReader().use { it.readText() }
|
||||
|
||||
override fun indexHtml(): String = """
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="referrer" content="no-referrer">
|
||||
<title>Android SMS Gateway API</title>
|
||||
<link rel="stylesheet" href="/docs/swagger-ui.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="swagger-ui"></div>
|
||||
<script src="/docs/swagger-ui-bundle.js"></script>
|
||||
<script src="/docs/swagger-initializer.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
""".trimIndent()
|
||||
|
||||
override fun initializerJavaScript(): String = """
|
||||
window.onload = function () {
|
||||
window.ui = SwaggerUIBundle({
|
||||
url: "/docs/openapi.yaml",
|
||||
dom_id: "#swagger-ui",
|
||||
deepLinking: true,
|
||||
displayRequestDuration: true,
|
||||
filter: true,
|
||||
persistAuthorization: false,
|
||||
presets: [SwaggerUIBundle.presets.apis],
|
||||
layout: "BaseLayout"
|
||||
});
|
||||
};
|
||||
""".trimIndent()
|
||||
|
||||
override fun swaggerUiAsset(name: String): String {
|
||||
require(name in ALLOWED_ASSETS) { "Unsupported documentation asset" }
|
||||
val path = "META-INF/resources/webjars/swagger-ui/$SWAGGER_UI_VERSION/$name"
|
||||
val stream = javaClass.classLoader?.getResourceAsStream(path)
|
||||
?: error("Packaged Swagger UI asset is missing: $name")
|
||||
return stream.bufferedReader().use { it.readText() }
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val SWAGGER_UI_VERSION = "5.32.1"
|
||||
private val ALLOWED_ASSETS = setOf("swagger-ui.css", "swagger-ui-bundle.js")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.androidsmsgateway.server
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class ApiInfoResponse(
|
||||
val api_version: String = "v1",
|
||||
val gateway_version: String,
|
||||
val capabilities: List<String>,
|
||||
val endpoints: List<String>,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class HealthResponse(
|
||||
val status: String,
|
||||
val device_id: String,
|
||||
val app_version: String,
|
||||
val android_version: String,
|
||||
val device_model: String,
|
||||
val ip: String,
|
||||
val port: Int,
|
||||
val uptime: Long,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class SendSmsRequest(val to: String = "", val message: String = "")
|
||||
|
||||
@Serializable
|
||||
data class SendSmsResponse(
|
||||
val success: Boolean,
|
||||
val id: String,
|
||||
val status: String,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ApiMessage(
|
||||
val id: String,
|
||||
val direction: String,
|
||||
val sender: String? = null,
|
||||
val recipient: String? = null,
|
||||
val message: String,
|
||||
val timestamp: Long,
|
||||
val status: String,
|
||||
val error_code: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class MessagePage(
|
||||
val success: Boolean = true,
|
||||
val page: Int,
|
||||
val page_size: Int,
|
||||
val messages: List<ApiMessage>,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class StatusResponse(
|
||||
val success: Boolean = true,
|
||||
val server_status: String,
|
||||
val ip: String,
|
||||
val port: Int,
|
||||
val uptime: Long,
|
||||
val requests: Long,
|
||||
val sent_sms: Long,
|
||||
val received_sms: Long,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
package com.androidsmsgateway.server
|
||||
|
||||
import android.os.Build
|
||||
import com.androidsmsgateway.BuildConfig
|
||||
import com.androidsmsgateway.data.GatewayRepository
|
||||
import com.androidsmsgateway.data.SettingsRepository
|
||||
import com.androidsmsgateway.data.local.RequestLogEntity
|
||||
import com.androidsmsgateway.domain.ErrorBody
|
||||
import com.androidsmsgateway.domain.ErrorResponse
|
||||
import com.androidsmsgateway.domain.ServerSnapshot
|
||||
import com.androidsmsgateway.security.AccessDecision
|
||||
import com.androidsmsgateway.security.SecurityPolicy
|
||||
import com.androidsmsgateway.sms.SmsSender
|
||||
import com.androidsmsgateway.sms.SmsSubmissionException
|
||||
import fi.iki.elonen.NanoHTTPD
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.serialization.SerializationException
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
class ApiRouter(
|
||||
private val repository: GatewayRepository,
|
||||
private val settingsRepository: SettingsRepository,
|
||||
private val smsSender: SmsSender,
|
||||
private val serverSnapshot: () -> ServerSnapshot,
|
||||
private val documentationProvider: ApiDocumentationProvider,
|
||||
) {
|
||||
private val json = Json { ignoreUnknownKeys = false; explicitNulls = false; encodeDefaults = true }
|
||||
|
||||
suspend fun route(session: NanoHTTPD.IHTTPSession): ApiResult {
|
||||
val started = System.nanoTime()
|
||||
val method = session.method.name
|
||||
val path = session.uri.substringBefore('?')
|
||||
val clientIp = session.remoteIpAddress ?: "unknown"
|
||||
var result = ApiResult(500, error("INTERNAL_ERROR", "The request could not be completed"))
|
||||
try {
|
||||
if (path == DOCS_PATH || path.startsWith("$DOCS_PATH/")) {
|
||||
result = dispatch(session, path)
|
||||
return result
|
||||
}
|
||||
if (!path.startsWith("/api/v1")) {
|
||||
result = ApiResult(404, error("NOT_FOUND", "Endpoint not found"))
|
||||
return result
|
||||
}
|
||||
val settings = settingsRepository.current()
|
||||
result = when (SecurityPolicy.evaluate(settings, clientIp, session.headers)) {
|
||||
AccessDecision.ALLOWED -> dispatch(session, path)
|
||||
AccessDecision.IP_DENIED -> ApiResult(403, error("IP_NOT_ALLOWED", "Client IP is not allowed"))
|
||||
AccessDecision.MISSING_CREDENTIALS -> ApiResult(401, error("AUTHENTICATION_REQUIRED", "API credentials are required"))
|
||||
AccessDecision.INVALID_CREDENTIALS -> ApiResult(401, error("INVALID_API_KEY", "API credentials are invalid"))
|
||||
AccessDecision.NOT_CONFIGURED -> ApiResult(503, error("AUTHENTICATION_NOT_CONFIGURED", "Set an API key in the app before using the API"))
|
||||
}
|
||||
return result
|
||||
} catch (_: SerializationException) {
|
||||
result = ApiResult(400, error("INVALID_JSON", "Request body must be valid JSON"))
|
||||
return result
|
||||
} catch (exception: SmsSubmissionException) {
|
||||
result = ApiResult(503, error(exception.code, exception.message))
|
||||
return result
|
||||
} catch (_: Exception) {
|
||||
result = ApiResult(500, error("INTERNAL_ERROR", "The request could not be completed"))
|
||||
return result
|
||||
} finally {
|
||||
val durationMs = (System.nanoTime() - started) / 1_000_000
|
||||
runCatching {
|
||||
repository.logRequest(
|
||||
RequestLogEntity(
|
||||
timestamp = System.currentTimeMillis(),
|
||||
method = method,
|
||||
path = path.take(512),
|
||||
statusCode = result.status,
|
||||
clientIp = clientIp.take(128),
|
||||
durationMs = durationMs,
|
||||
success = result.status in 200..299,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun dispatch(session: NanoHTTPD.IHTTPSession, path: String): ApiResult {
|
||||
return when {
|
||||
session.method == NanoHTTPD.Method.GET && path in setOf(DOCS_PATH, "$DOCS_PATH/") ->
|
||||
ApiResult(
|
||||
200,
|
||||
documentationProvider.indexHtml(),
|
||||
"text/html; charset=utf-8",
|
||||
mapOf(
|
||||
"Content-Security-Policy" to "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:",
|
||||
"Referrer-Policy" to "no-referrer",
|
||||
),
|
||||
)
|
||||
session.method == NanoHTTPD.Method.GET && path == OPENAPI_PATH ->
|
||||
ApiResult(200, documentationProvider.openApi(), "application/yaml; charset=utf-8")
|
||||
session.method == NanoHTTPD.Method.GET && path == SWAGGER_CSS_PATH ->
|
||||
ApiResult(200, documentationProvider.swaggerUiAsset("swagger-ui.css"), "text/css; charset=utf-8")
|
||||
session.method == NanoHTTPD.Method.GET && path == SWAGGER_BUNDLE_PATH ->
|
||||
ApiResult(200, documentationProvider.swaggerUiAsset("swagger-ui-bundle.js"), "application/javascript; charset=utf-8")
|
||||
session.method == NanoHTTPD.Method.GET && path == SWAGGER_INITIALIZER_PATH ->
|
||||
ApiResult(200, documentationProvider.initializerJavaScript(), "application/javascript; charset=utf-8")
|
||||
session.method == NanoHTTPD.Method.GET && path == "/api/v1" -> apiInfo()
|
||||
session.method == NanoHTTPD.Method.GET && path == "/api/v1/health" -> health()
|
||||
session.method == NanoHTTPD.Method.GET && path == "/api/v1/status" -> status()
|
||||
session.method == NanoHTTPD.Method.POST && path == "/api/v1/sms/send" -> sendSms(session)
|
||||
session.method == NanoHTTPD.Method.GET && path == "/api/v1/sms/messages" -> listMessages(session)
|
||||
session.method == NanoHTTPD.Method.GET && path.startsWith("/api/v1/sms/messages/") ->
|
||||
messageDetails(path.substringAfterLast('/'))
|
||||
path in KNOWN_PATHS -> ApiResult(405, error("METHOD_NOT_ALLOWED", "HTTP method is not allowed for this endpoint"))
|
||||
else -> ApiResult(404, error("NOT_FOUND", "Endpoint not found"))
|
||||
}
|
||||
}
|
||||
|
||||
private fun apiInfo() = ApiResult(
|
||||
200,
|
||||
json.encodeToString(
|
||||
ApiInfoResponse(
|
||||
gateway_version = BuildConfig.VERSION_NAME,
|
||||
capabilities = listOf("health", "status", "send_sms", "receive_sms", "message_history", "api_key", "ip_allowlist"),
|
||||
endpoints = KNOWN_PATHS.sorted(),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
private suspend fun health(): ApiResult {
|
||||
val settings = settingsRepository.current()
|
||||
val snapshot = serverSnapshot()
|
||||
return ApiResult(
|
||||
200,
|
||||
json.encodeToString(
|
||||
HealthResponse(
|
||||
status = "ok",
|
||||
device_id = settings.deviceId,
|
||||
app_version = BuildConfig.VERSION_NAME,
|
||||
android_version = Build.VERSION.RELEASE,
|
||||
device_model = "${Build.MANUFACTURER} ${Build.MODEL}".trim(),
|
||||
ip = snapshot.ipAddress,
|
||||
port = snapshot.port,
|
||||
uptime = snapshot.uptimeMillis() / 1000,
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun status(): ApiResult {
|
||||
val snapshot = serverSnapshot()
|
||||
return ApiResult(
|
||||
200,
|
||||
json.encodeToString(
|
||||
StatusResponse(
|
||||
server_status = snapshot.state.name.lowercase(),
|
||||
ip = snapshot.ipAddress,
|
||||
port = snapshot.port,
|
||||
uptime = snapshot.uptimeMillis() / 1000,
|
||||
requests = repository.requestCount().first(),
|
||||
sent_sms = repository.outgoingCount().first(),
|
||||
received_sms = repository.incomingCount().first(),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun sendSms(session: NanoHTTPD.IHTTPSession): ApiResult {
|
||||
val length = session.headers["content-length"]?.toLongOrNull()
|
||||
if (length == null) return ApiResult(411, error("LENGTH_REQUIRED", "Content-Length is required"))
|
||||
if (length > MAX_BODY_BYTES) return ApiResult(413, error("PAYLOAD_TOO_LARGE", "Request body exceeds $MAX_BODY_BYTES bytes"))
|
||||
val files = mutableMapOf<String, String>()
|
||||
session.parseBody(files)
|
||||
val body = files["postData"] ?: ""
|
||||
if (body.toByteArray().size > MAX_BODY_BYTES) return ApiResult(413, error("PAYLOAD_TOO_LARGE", "Request body exceeds $MAX_BODY_BYTES bytes"))
|
||||
val request = json.decodeFromString<SendSmsRequest>(body)
|
||||
if (!PHONE_REGEX.matches(request.to.trim())) return ApiResult(422, error("INVALID_RECIPIENT", "Recipient phone number is invalid"))
|
||||
if (request.message.isBlank()) return ApiResult(422, error("EMPTY_MESSAGE", "Message must not be empty"))
|
||||
if (request.message.length > MAX_SMS_CHARACTERS) return ApiResult(422, error("MESSAGE_TOO_LONG", "MVP messages are limited to $MAX_SMS_CHARACTERS characters"))
|
||||
val submission = smsSender.send(request.to.trim(), request.message)
|
||||
return ApiResult(202, json.encodeToString(SendSmsResponse(true, submission.id, submission.status)))
|
||||
}
|
||||
|
||||
private suspend fun listMessages(session: NanoHTTPD.IHTTPSession): ApiResult {
|
||||
val page = session.parameters["page"]?.firstOrNull()?.toIntOrNull()?.coerceAtLeast(1) ?: 1
|
||||
val pageSize = session.parameters["page_size"]?.firstOrNull()?.toIntOrNull()?.coerceIn(1, 100) ?: 50
|
||||
val query = session.parameters["search"]?.firstOrNull()?.trim()?.take(200).orEmpty()
|
||||
val direction = session.parameters["direction"]?.firstOrNull()?.lowercase() ?: "all"
|
||||
if (direction !in setOf("all", "incoming", "outgoing")) return ApiResult(422, error("INVALID_DIRECTION", "Direction must be all, incoming, or outgoing"))
|
||||
|
||||
val messages = repository.messagePage(direction, query, page, pageSize).map {
|
||||
ApiMessage(
|
||||
id = it.id,
|
||||
direction = it.direction,
|
||||
sender = it.address.takeIf { _ -> it.direction == "incoming" },
|
||||
recipient = it.address.takeIf { _ -> it.direction == "outgoing" },
|
||||
message = it.message,
|
||||
timestamp = it.timestamp,
|
||||
status = it.status.lowercase(),
|
||||
error_code = it.errorCode,
|
||||
)
|
||||
}
|
||||
return ApiResult(200, json.encodeToString(MessagePage(page = page, page_size = pageSize, messages = messages)))
|
||||
}
|
||||
|
||||
private suspend fun messageDetails(id: String): ApiResult {
|
||||
if (id.length !in 1..100) return ApiResult(404, error("MESSAGE_NOT_FOUND", "Message was not found"))
|
||||
val incoming = repository.incomingById(id)
|
||||
val message = incoming?.let {
|
||||
ApiMessage(it.id, "incoming", sender = it.sender, message = it.message, timestamp = it.receivedAt, status = it.status.lowercase())
|
||||
} ?: repository.outgoingById(id)?.let {
|
||||
ApiMessage(it.id, "outgoing", recipient = it.recipient, message = it.message, timestamp = it.requestedAt, status = it.status.lowercase(), error_code = it.errorCode)
|
||||
} ?: return ApiResult(404, error("MESSAGE_NOT_FOUND", "Message was not found"))
|
||||
return ApiResult(200, json.encodeToString(message))
|
||||
}
|
||||
|
||||
private fun error(code: String, message: String): String = json.encodeToString(ErrorResponse(error = ErrorBody(code, message)))
|
||||
|
||||
companion object {
|
||||
const val MAX_BODY_BYTES = 16_384L
|
||||
const val MAX_SMS_CHARACTERS = 160
|
||||
val PHONE_REGEX = Regex("^\\+?[0-9]{3,20}$")
|
||||
const val DOCS_PATH = "/docs"
|
||||
const val OPENAPI_PATH = "/docs/openapi.yaml"
|
||||
const val SWAGGER_CSS_PATH = "/docs/swagger-ui.css"
|
||||
const val SWAGGER_BUNDLE_PATH = "/docs/swagger-ui-bundle.js"
|
||||
const val SWAGGER_INITIALIZER_PATH = "/docs/swagger-initializer.js"
|
||||
val KNOWN_PATHS = setOf(DOCS_PATH, OPENAPI_PATH, "/api/v1", "/api/v1/health", "/api/v1/status", "/api/v1/sms/send", "/api/v1/sms/messages")
|
||||
}
|
||||
}
|
||||
|
||||
data class ApiResult(
|
||||
val status: Int,
|
||||
val body: String,
|
||||
val contentType: String = "application/json; charset=utf-8",
|
||||
val headers: Map<String, String> = emptyMap(),
|
||||
)
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.androidsmsgateway.server
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.androidsmsgateway.GatewayApplication
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class BootReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.action != Intent.ACTION_BOOT_COMPLETED) return
|
||||
val pendingResult = goAsync()
|
||||
val settingsRepository = (context.applicationContext as GatewayApplication).container.settingsRepository
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
try {
|
||||
runCatching {
|
||||
val settings = settingsRepository.current()
|
||||
if (settings.startOnBoot && settings.serverEnabled) {
|
||||
ContextCompat.startForegroundService(
|
||||
context,
|
||||
Intent(context, GatewayServerService::class.java).setAction(GatewayServerService.ACTION_START),
|
||||
)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
pendingResult.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.androidsmsgateway.server
|
||||
|
||||
import fi.iki.elonen.NanoHTTPD
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.runBlocking
|
||||
|
||||
class GatewayHttpServer(
|
||||
bindAddress: String,
|
||||
port: Int,
|
||||
private val router: ApiRouter,
|
||||
) : NanoHTTPD(bindAddress, port) {
|
||||
override fun serve(session: IHTTPSession): Response {
|
||||
val result = runBlocking(Dispatchers.IO) { router.route(session) }
|
||||
val status = Response.Status.lookup(result.status) ?: Response.Status.INTERNAL_ERROR
|
||||
return newFixedLengthResponse(status, result.contentType, result.body).apply {
|
||||
addHeader("Cache-Control", "no-store")
|
||||
addHeader("X-Content-Type-Options", "nosniff")
|
||||
result.headers.forEach(::addHeader)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.androidsmsgateway.server
|
||||
|
||||
import android.content.Context
|
||||
import com.androidsmsgateway.data.GatewayRepository
|
||||
import com.androidsmsgateway.data.SettingsRepository
|
||||
import com.androidsmsgateway.domain.ServerSnapshot
|
||||
import com.androidsmsgateway.domain.ServerState
|
||||
import com.androidsmsgateway.sms.SmsSender
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
|
||||
class GatewayServerController(
|
||||
context: Context,
|
||||
private val settingsRepository: SettingsRepository,
|
||||
private val repository: GatewayRepository,
|
||||
private val smsSender: SmsSender,
|
||||
) {
|
||||
private val documentationProvider = PackagedApiDocumentationProvider(context.applicationContext)
|
||||
private val mutex = Mutex()
|
||||
private var server: GatewayHttpServer? = null
|
||||
private val mutableSnapshot = MutableStateFlow(ServerSnapshot())
|
||||
val snapshot: StateFlow<ServerSnapshot> = mutableSnapshot.asStateFlow()
|
||||
|
||||
suspend fun start(): Result<Unit> = mutex.withLock {
|
||||
if (server?.isAlive == true) return Result.success(Unit)
|
||||
runCatching {
|
||||
val settings = settingsRepository.current()
|
||||
require(settings.port in 1024..65535) { "Configured port is invalid" }
|
||||
mutableSnapshot.value = ServerSnapshot(ServerState.STARTING, port = settings.port, ipAddress = NetworkAddressProvider.currentIpv4())
|
||||
val router = ApiRouter(
|
||||
repository = repository,
|
||||
settingsRepository = settingsRepository,
|
||||
smsSender = smsSender,
|
||||
serverSnapshot = { mutableSnapshot.value },
|
||||
documentationProvider = documentationProvider,
|
||||
)
|
||||
GatewayHttpServer(settings.bindAddress, settings.port, router).also {
|
||||
it.start(10_000, false)
|
||||
server = it
|
||||
}
|
||||
mutableSnapshot.value = ServerSnapshot(
|
||||
state = ServerState.RUNNING,
|
||||
startedAt = System.currentTimeMillis(),
|
||||
ipAddress = NetworkAddressProvider.currentIpv4(),
|
||||
port = settings.port,
|
||||
)
|
||||
settingsRepository.update { it.copy(serverEnabled = true) }
|
||||
Unit
|
||||
}.onFailure { exception ->
|
||||
server = null
|
||||
mutableSnapshot.value = ServerSnapshot(
|
||||
state = ServerState.ERROR,
|
||||
port = mutableSnapshot.value.port,
|
||||
ipAddress = NetworkAddressProvider.currentIpv4(),
|
||||
lastError = exception.message ?: "Server failed to start",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun stop(): Result<Unit> = mutex.withLock {
|
||||
mutableSnapshot.value = mutableSnapshot.value.copy(state = ServerState.STOPPING)
|
||||
val stopResult = runCatching {
|
||||
server?.stop()
|
||||
Unit
|
||||
}
|
||||
server = null
|
||||
val settingsResult = runCatching { settingsRepository.update { settings -> settings.copy(serverEnabled = false) } }
|
||||
val failure = stopResult.exceptionOrNull() ?: settingsResult.exceptionOrNull()
|
||||
mutableSnapshot.value = ServerSnapshot(
|
||||
state = if (failure == null) ServerState.STOPPED else ServerState.ERROR,
|
||||
port = mutableSnapshot.value.port,
|
||||
ipAddress = NetworkAddressProvider.currentIpv4(),
|
||||
lastError = failure?.message,
|
||||
)
|
||||
failure?.let { Result.failure(it) } ?: Result.success(Unit)
|
||||
}
|
||||
|
||||
suspend fun restart(): Result<Unit> {
|
||||
stop()
|
||||
return start()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.androidsmsgateway.server
|
||||
|
||||
import android.Manifest
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.IBinder
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.androidsmsgateway.GatewayApplication
|
||||
import com.androidsmsgateway.MainActivity
|
||||
import com.androidsmsgateway.R
|
||||
import com.androidsmsgateway.domain.ServerState
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
|
||||
class GatewayServerService : Service() {
|
||||
private val serviceJob = SupervisorJob()
|
||||
private val scope = CoroutineScope(serviceJob + Dispatchers.IO)
|
||||
private val controller by lazy { (application as GatewayApplication).container.serverController }
|
||||
private var notificationJob: Job? = null
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
createNotificationChannel()
|
||||
startForeground(NOTIFICATION_ID, notification("Starting gateway…"))
|
||||
notificationJob = scope.launch {
|
||||
controller.snapshot.collectLatest { snapshot ->
|
||||
val text = when (snapshot.state) {
|
||||
ServerState.RUNNING -> "Listening on ${snapshot.ipAddress}:${snapshot.port}"
|
||||
ServerState.ERROR -> snapshot.lastError ?: "Gateway server error"
|
||||
else -> snapshot.state.name.lowercase().replaceFirstChar(Char::uppercase)
|
||||
}
|
||||
if (
|
||||
android.os.Build.VERSION.SDK_INT < 33 ||
|
||||
ContextCompat.checkSelfPermission(this@GatewayServerService, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
NotificationManagerCompat.from(this@GatewayServerService).notify(NOTIFICATION_ID, notification(text))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
scope.launch {
|
||||
when (intent?.action ?: ACTION_START) {
|
||||
ACTION_STOP -> {
|
||||
controller.stop()
|
||||
stopSelf()
|
||||
}
|
||||
ACTION_RESTART -> controller.restart()
|
||||
else -> controller.start()
|
||||
}
|
||||
}
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
notificationJob?.cancel()
|
||||
runBlocking(Dispatchers.IO) { controller.stop() }
|
||||
serviceJob.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
private fun notification(content: String) = NotificationCompat.Builder(this, CHANNEL_ID)
|
||||
.setSmallIcon(android.R.drawable.stat_notify_sync_noanim)
|
||||
.setContentTitle(getString(R.string.app_name))
|
||||
.setContentText(content)
|
||||
.setOngoing(true)
|
||||
.setSilent(true)
|
||||
.setContentIntent(
|
||||
PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
Intent(this, MainActivity::class.java),
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
),
|
||||
)
|
||||
.addAction(
|
||||
0,
|
||||
"Stop",
|
||||
PendingIntent.getService(
|
||||
this,
|
||||
1,
|
||||
Intent(this, GatewayServerService::class.java).setAction(ACTION_STOP),
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
),
|
||||
)
|
||||
.build()
|
||||
|
||||
private fun createNotificationChannel() {
|
||||
val channel = NotificationChannel(CHANNEL_ID, "Gateway server", NotificationManager.IMPORTANCE_LOW).apply {
|
||||
description = "Keeps the local SMS gateway server running"
|
||||
}
|
||||
getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val ACTION_START = "com.androidsmsgateway.server.START"
|
||||
const val ACTION_STOP = "com.androidsmsgateway.server.STOP"
|
||||
const val ACTION_RESTART = "com.androidsmsgateway.server.RESTART"
|
||||
private const val CHANNEL_ID = "gateway_server"
|
||||
private const val NOTIFICATION_ID = 1001
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.androidsmsgateway.server
|
||||
|
||||
import java.net.Inet4Address
|
||||
import java.net.NetworkInterface
|
||||
|
||||
object NetworkAddressProvider {
|
||||
fun currentIpv4(): String = runCatching {
|
||||
NetworkInterface.getNetworkInterfaces().toList()
|
||||
.flatMap { it.inetAddresses.toList() }
|
||||
.firstOrNull { it is Inet4Address && !it.isLoopbackAddress && !it.isLinkLocalAddress }
|
||||
?.hostAddress
|
||||
?: "Unavailable"
|
||||
}.getOrDefault("Unavailable")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.androidsmsgateway.sms
|
||||
|
||||
import android.Manifest
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.telephony.SmsManager
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.androidsmsgateway.data.GatewayRepository
|
||||
import com.androidsmsgateway.data.local.OutgoingSmsEntity
|
||||
import com.androidsmsgateway.domain.MessageStatus
|
||||
import java.util.UUID
|
||||
|
||||
class AndroidSmsSender(
|
||||
private val context: Context,
|
||||
private val repository: GatewayRepository,
|
||||
) : SmsSender {
|
||||
override suspend fun send(recipient: String, message: String): SmsSubmission {
|
||||
if (ContextCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
|
||||
throw SmsSubmissionException("SMS_PERMISSION_DENIED", "Send SMS permission is not granted")
|
||||
}
|
||||
|
||||
val id = UUID.randomUUID().toString()
|
||||
val now = System.currentTimeMillis()
|
||||
val outgoing = OutgoingSmsEntity(
|
||||
id = id,
|
||||
recipient = recipient,
|
||||
message = message,
|
||||
requestedAt = now,
|
||||
status = MessageStatus.PENDING.name,
|
||||
updatedAt = now,
|
||||
)
|
||||
repository.saveOutgoing(outgoing)
|
||||
|
||||
val sentIntent = Intent(context, SmsStatusReceiver::class.java).apply {
|
||||
action = SmsStatusReceiver.ACTION_SENT
|
||||
putExtra(SmsStatusReceiver.EXTRA_MESSAGE_ID, id)
|
||||
}
|
||||
val sentPendingIntent = PendingIntent.getBroadcast(
|
||||
context,
|
||||
id.hashCode(),
|
||||
sentIntent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
|
||||
try {
|
||||
smsManager().sendTextMessage(recipient, null, message, sentPendingIntent, null)
|
||||
} catch (exception: Exception) {
|
||||
repository.updateOutgoing(
|
||||
outgoing.copy(
|
||||
status = MessageStatus.FAILED.name,
|
||||
errorCode = "SMS_SEND_FAILED",
|
||||
updatedAt = System.currentTimeMillis(),
|
||||
),
|
||||
)
|
||||
throw SmsSubmissionException("SMS_SEND_FAILED", exception.message ?: "Android rejected the SMS request")
|
||||
}
|
||||
return SmsSubmission(id, MessageStatus.PENDING.name.lowercase())
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun smsManager(): SmsManager = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
context.getSystemService(SmsManager::class.java)
|
||||
} else {
|
||||
SmsManager.getDefault()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.androidsmsgateway.sms
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.provider.Telephony
|
||||
import com.androidsmsgateway.GatewayApplication
|
||||
import com.androidsmsgateway.data.local.IncomingSmsEntity
|
||||
import com.androidsmsgateway.domain.MessageStatus
|
||||
import java.util.UUID
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class IncomingSmsReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.action != Telephony.Sms.Intents.SMS_RECEIVED_ACTION) return
|
||||
val pendingResult = goAsync()
|
||||
val repository = (context.applicationContext as GatewayApplication).container.gatewayRepository
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
try {
|
||||
runCatching {
|
||||
val parts = runCatching { Telephony.Sms.Intents.getMessagesFromIntent(intent).toList() }.getOrDefault(emptyList())
|
||||
parts.groupBy { it.originatingAddress.orEmpty() }.forEach { (sender, messages) ->
|
||||
if (sender.isBlank()) return@forEach
|
||||
val receivedAt = messages.minOfOrNull { it.timestampMillis } ?: System.currentTimeMillis()
|
||||
val body = messages.joinToString("") { it.messageBody.orEmpty() }
|
||||
repository.saveIncoming(
|
||||
IncomingSmsEntity(
|
||||
id = UUID.randomUUID().toString(),
|
||||
sender = sender,
|
||||
message = body,
|
||||
receivedAt = receivedAt,
|
||||
status = MessageStatus.RECEIVED.name,
|
||||
createdAt = System.currentTimeMillis(),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
pendingResult.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.androidsmsgateway.sms
|
||||
|
||||
data class SmsSubmission(val id: String, val status: String)
|
||||
|
||||
interface SmsSender {
|
||||
suspend fun send(recipient: String, message: String): SmsSubmission
|
||||
}
|
||||
|
||||
class SmsSubmissionException(val code: String, override val message: String) : Exception(message)
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.androidsmsgateway.sms
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.telephony.SmsManager
|
||||
import com.androidsmsgateway.GatewayApplication
|
||||
import com.androidsmsgateway.domain.MessageStatus
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class SmsStatusReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.action != ACTION_SENT) return
|
||||
val id = intent.getStringExtra(EXTRA_MESSAGE_ID) ?: return
|
||||
val pendingResult = goAsync()
|
||||
val repository = (context.applicationContext as GatewayApplication).container.gatewayRepository
|
||||
val result = resultCode
|
||||
val succeeded = isSuccessfulResult(result)
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
try {
|
||||
runCatching {
|
||||
repository.outgoingById(id)?.let { message ->
|
||||
repository.updateOutgoing(
|
||||
message.copy(
|
||||
status = if (succeeded) MessageStatus.SENT.name else MessageStatus.FAILED.name,
|
||||
errorCode = if (succeeded) null else "ANDROID_SMS_ERROR_$result",
|
||||
updatedAt = System.currentTimeMillis(),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
pendingResult.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val ACTION_SENT = "com.androidsmsgateway.SMS_SENT"
|
||||
const val EXTRA_MESSAGE_ID = "message_id"
|
||||
|
||||
internal fun isSuccessfulResult(resultCode: Int): Boolean =
|
||||
resultCode == Activity.RESULT_OK || resultCode == SmsManager.RESULT_ERROR_NONE
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.androidsmsgateway.ui
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Intent
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.androidsmsgateway.GatewayApplication
|
||||
import com.androidsmsgateway.data.local.IncomingSmsEntity
|
||||
import com.androidsmsgateway.data.local.OutgoingSmsEntity
|
||||
import com.androidsmsgateway.data.local.RequestLogEntity
|
||||
import com.androidsmsgateway.domain.GatewaySettings
|
||||
import com.androidsmsgateway.domain.ServerSnapshot
|
||||
import com.androidsmsgateway.security.SecurityPolicy
|
||||
import com.androidsmsgateway.server.GatewayServerService
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
data class GatewayUiState(
|
||||
val loading: Boolean = true,
|
||||
val server: ServerSnapshot = ServerSnapshot(),
|
||||
val settings: GatewaySettings? = null,
|
||||
val requestCount: Long = 0,
|
||||
val sentCount: Long = 0,
|
||||
val receivedCount: Long = 0,
|
||||
val lastRequest: RequestLogEntity? = null,
|
||||
val incoming: List<IncomingSmsEntity> = emptyList(),
|
||||
val outgoing: List<OutgoingSmsEntity> = emptyList(),
|
||||
val logs: List<RequestLogEntity> = emptyList(),
|
||||
val message: String? = null,
|
||||
)
|
||||
|
||||
class GatewayViewModel(application: Application) : AndroidViewModel(application) {
|
||||
private val app = application as GatewayApplication
|
||||
private val container = app.container
|
||||
private val mutableState = MutableStateFlow(GatewayUiState())
|
||||
val state: StateFlow<GatewayUiState> = mutableState.asStateFlow()
|
||||
|
||||
init {
|
||||
observeState()
|
||||
viewModelScope.launch {
|
||||
val settings = container.settingsRepository.ensureInitialized()
|
||||
mutableState.value = mutableState.value.copy(settings = settings, loading = false)
|
||||
if (settings.serverEnabled) startServer()
|
||||
}
|
||||
}
|
||||
|
||||
private fun observeState() {
|
||||
viewModelScope.launch { container.serverController.snapshot.collect { update { copy(server = it) } } }
|
||||
viewModelScope.launch { container.settingsRepository.settings.collect { update { copy(settings = it, loading = false) } } }
|
||||
viewModelScope.launch { container.gatewayRepository.requestCount().collect { update { copy(requestCount = it) } } }
|
||||
viewModelScope.launch { container.gatewayRepository.outgoingCount().collect { update { copy(sentCount = it) } } }
|
||||
viewModelScope.launch { container.gatewayRepository.incomingCount().collect { update { copy(receivedCount = it) } } }
|
||||
viewModelScope.launch { container.gatewayRepository.lastRequest().collect { update { copy(lastRequest = it) } } }
|
||||
viewModelScope.launch { container.gatewayRepository.incomingMessages().collect { update { copy(incoming = it) } } }
|
||||
viewModelScope.launch { container.gatewayRepository.outgoingMessages().collect { update { copy(outgoing = it) } } }
|
||||
viewModelScope.launch { container.gatewayRepository.requestLogs().collect { update { copy(logs = it) } } }
|
||||
}
|
||||
|
||||
fun startServer() {
|
||||
ContextCompat.startForegroundService(app, Intent(app, GatewayServerService::class.java).setAction(GatewayServerService.ACTION_START))
|
||||
}
|
||||
|
||||
fun stopServer() {
|
||||
app.startService(Intent(app, GatewayServerService::class.java).setAction(GatewayServerService.ACTION_STOP))
|
||||
}
|
||||
|
||||
fun saveServerSettings(portText: String, bindAddress: String, startOnBoot: Boolean) {
|
||||
val port = portText.toIntOrNull()
|
||||
if (port == null || port !in 1024..65535) return showMessage("Port must be between 1024 and 65535")
|
||||
val bind = bindAddress.trim()
|
||||
if (!SecurityPolicy.isValidIp(bind)) return showMessage("Bind address must be a valid IP address")
|
||||
viewModelScope.launch {
|
||||
container.settingsRepository.update { it.copy(port = port, bindAddress = bind, startOnBoot = startOnBoot) }
|
||||
if (state.value.server.state.name == "RUNNING") {
|
||||
ContextCompat.startForegroundService(app, Intent(app, GatewayServerService::class.java).setAction(GatewayServerService.ACTION_RESTART))
|
||||
}
|
||||
showMessage("Server settings saved")
|
||||
}
|
||||
}
|
||||
|
||||
fun setAuthenticationEnabled(enabled: Boolean) = updateSettings(transform = { it.copy(authenticationEnabled = enabled) })
|
||||
fun setAllowlistEnabled(enabled: Boolean) = updateSettings(transform = { it.copy(allowlistEnabled = enabled) })
|
||||
|
||||
fun setApiKey(apiKey: String) {
|
||||
if (apiKey.length < 16) return showMessage("API key must contain at least 16 characters")
|
||||
updateSettings({ it.copy(apiKeyHash = SecurityPolicy.hashApiKey(apiKey)) }, "API key updated")
|
||||
}
|
||||
|
||||
fun addAllowedIp(ip: String) {
|
||||
val value = ip.trim()
|
||||
if (!SecurityPolicy.isValidIp(value)) return showMessage("Enter a valid IPv4 or IPv6 address")
|
||||
updateSettings({ current ->
|
||||
val values = current.allowedIps.lineSequence().map(String::trim).filter(String::isNotEmpty).toMutableSet()
|
||||
values += value
|
||||
current.copy(allowedIps = values.sorted().joinToString("\n"))
|
||||
}, "Allowed IP added")
|
||||
}
|
||||
|
||||
fun removeAllowedIp(ip: String) = updateSettings(transform = { current ->
|
||||
current.copy(allowedIps = current.allowedIps.lineSequence().filter { it.trim() != ip }.joinToString("\n"))
|
||||
})
|
||||
|
||||
fun clearMessage() = update { copy(message = null) }
|
||||
|
||||
private fun updateSettings(
|
||||
transform: (com.androidsmsgateway.data.local.AppSettingsEntity) -> com.androidsmsgateway.data.local.AppSettingsEntity,
|
||||
confirmation: String? = null,
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
container.settingsRepository.update(transform)
|
||||
confirmation?.let(::showMessage)
|
||||
}
|
||||
}
|
||||
|
||||
private fun showMessage(message: String) = update { copy(message = message) }
|
||||
private inline fun update(transform: GatewayUiState.() -> GatewayUiState) {
|
||||
mutableState.value = mutableState.value.transform()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
package com.androidsmsgateway.ui.components
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.ChatBubbleOutline
|
||||
import androidx.compose.material.icons.outlined.Info
|
||||
import androidx.compose.material.icons.outlined.Search
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.OutlinedTextFieldDefaults
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.SwitchDefaults
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.androidsmsgateway.ui.theme.GatewayInfo
|
||||
import com.androidsmsgateway.ui.theme.GatewayInfoBackground
|
||||
import com.androidsmsgateway.ui.theme.GatewayMint
|
||||
import com.androidsmsgateway.ui.theme.GatewayPrimary
|
||||
import com.androidsmsgateway.ui.theme.GatewaySignal
|
||||
import com.androidsmsgateway.ui.theme.GatewayWarning
|
||||
import com.androidsmsgateway.ui.theme.GatewayWarningBackground
|
||||
|
||||
val GatewayCardShape = RoundedCornerShape(18.dp)
|
||||
val GatewayControlShape = RoundedCornerShape(13.dp)
|
||||
|
||||
enum class BadgeTone { SUCCESS, INFO, WARNING, ERROR, NEUTRAL }
|
||||
|
||||
@Composable
|
||||
fun BrandMark(modifier: Modifier = Modifier) {
|
||||
Box(
|
||||
modifier
|
||||
.size(34.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(GatewayMint),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Outlined.ChatBubbleOutline,
|
||||
contentDescription = null,
|
||||
tint = GatewayPrimary,
|
||||
modifier = Modifier.size(19.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ScreenHeader(
|
||||
title: String,
|
||||
subtitle: String,
|
||||
modifier: Modifier = Modifier,
|
||||
leading: @Composable (() -> Unit)? = null,
|
||||
trailing: @Composable (() -> Unit)? = null,
|
||||
) {
|
||||
Row(
|
||||
modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
if (leading != null) leading() else BrandMark()
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.titleLarge)
|
||||
Text(
|
||||
subtitle.uppercase(),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
trailing?.invoke()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun GatewayCard(
|
||||
modifier: Modifier = Modifier,
|
||||
containerColor: Color = MaterialTheme.colorScheme.surface,
|
||||
contentPadding: PaddingValues = PaddingValues(16.dp),
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
Card(
|
||||
modifier = modifier,
|
||||
shape = GatewayCardShape,
|
||||
colors = CardDefaults.cardColors(containerColor = containerColor),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
|
||||
border = androidx.compose.foundation.BorderStroke(1.dp, MaterialTheme.colorScheme.outline.copy(alpha = 0.72f)),
|
||||
) {
|
||||
Box(Modifier.padding(contentPadding)) { content() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun StatusBadge(
|
||||
text: String,
|
||||
tone: BadgeTone,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val (background, foreground) = when (tone) {
|
||||
BadgeTone.SUCCESS -> GatewayMint to GatewayPrimary
|
||||
BadgeTone.INFO -> GatewayInfoBackground to GatewayInfo
|
||||
BadgeTone.WARNING -> GatewayWarningBackground to GatewayWarning
|
||||
BadgeTone.ERROR -> MaterialTheme.colorScheme.errorContainer to MaterialTheme.colorScheme.onErrorContainer
|
||||
BadgeTone.NEUTRAL -> MaterialTheme.colorScheme.surfaceVariant to MaterialTheme.colorScheme.onSurfaceVariant
|
||||
}
|
||||
Text(
|
||||
text.uppercase(),
|
||||
modifier = modifier
|
||||
.clip(CircleShape)
|
||||
.background(background)
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
color = foreground,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun GatewaySearchField(
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
placeholder: String,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = value,
|
||||
onValueChange = onValueChange,
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
placeholder = { Text(placeholder) },
|
||||
leadingIcon = { Icon(Icons.Outlined.Search, contentDescription = null) },
|
||||
singleLine = true,
|
||||
shape = GatewayControlShape,
|
||||
colors = OutlinedTextFieldDefaults.colors(
|
||||
focusedContainerColor = MaterialTheme.colorScheme.surface,
|
||||
unfocusedContainerColor = MaterialTheme.colorScheme.surface,
|
||||
focusedBorderColor = GatewayPrimary,
|
||||
unfocusedBorderColor = MaterialTheme.colorScheme.outline,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SettingToggleRow(
|
||||
title: String,
|
||||
description: String,
|
||||
checked: Boolean,
|
||||
onCheckedChange: (Boolean) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Row(
|
||||
modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Text(title, style = MaterialTheme.typography.titleMedium)
|
||||
Text(description, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Switch(
|
||||
checked = checked,
|
||||
onCheckedChange = onCheckedChange,
|
||||
colors = SwitchDefaults.colors(
|
||||
checkedThumbColor = Color.White,
|
||||
checkedTrackColor = GatewayPrimary,
|
||||
uncheckedThumbColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
uncheckedTrackColor = MaterialTheme.colorScheme.surfaceVariant,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun InfoBanner(
|
||||
title: String,
|
||||
body: String,
|
||||
modifier: Modifier = Modifier,
|
||||
warning: Boolean = false,
|
||||
) {
|
||||
val background = if (warning) GatewayWarningBackground else GatewayInfoBackground
|
||||
val foreground = if (warning) GatewayWarning else GatewayInfo
|
||||
Row(
|
||||
modifier
|
||||
.fillMaxWidth()
|
||||
.clip(GatewayControlShape)
|
||||
.background(background)
|
||||
.padding(14.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
verticalAlignment = Alignment.Top,
|
||||
) {
|
||||
Icon(Icons.Outlined.Info, contentDescription = null, tint = foreground, modifier = Modifier.size(20.dp))
|
||||
Column(verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Text(title, style = MaterialTheme.typography.labelLarge, color = foreground)
|
||||
Text(body, style = MaterialTheme.typography.bodySmall, color = foreground)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun EmptyState(
|
||||
icon: ImageVector,
|
||||
title: String,
|
||||
body: String,
|
||||
modifier: Modifier = Modifier,
|
||||
actionLabel: String? = null,
|
||||
onAction: (() -> Unit)? = null,
|
||||
) {
|
||||
Column(
|
||||
modifier.fillMaxWidth().padding(horizontal = 28.dp, vertical = 54.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(72.dp).clip(CircleShape).background(MaterialTheme.colorScheme.primaryContainer),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(icon, contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(32.dp))
|
||||
}
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(title, style = MaterialTheme.typography.titleMedium)
|
||||
Text(
|
||||
body,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 3,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (actionLabel != null && onAction != null) {
|
||||
Button(
|
||||
onClick = onAction,
|
||||
colors = ButtonDefaults.buttonColors(containerColor = GatewayPrimary),
|
||||
shape = GatewayControlShape,
|
||||
) { Text(actionLabel) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SectionLabel(text: String, modifier: Modifier = Modifier) {
|
||||
Text(
|
||||
text.uppercase(),
|
||||
modifier = modifier,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ClickableSettingRow(
|
||||
title: String,
|
||||
description: String,
|
||||
icon: ImageVector,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Row(
|
||||
modifier
|
||||
.fillMaxWidth()
|
||||
.clip(GatewayControlShape)
|
||||
.clickable(onClick = onClick)
|
||||
.border(1.dp, MaterialTheme.colorScheme.outline, GatewayControlShape)
|
||||
.padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(14.dp),
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(38.dp).clip(CircleShape).background(MaterialTheme.colorScheme.primaryContainer),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(icon, contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(title, style = MaterialTheme.typography.titleMedium)
|
||||
Text(description, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Text("›", style = MaterialTheme.typography.headlineMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun LiveBadge() {
|
||||
Row(
|
||||
Modifier.clip(CircleShape).background(GatewayMint).padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Box(Modifier.size(6.dp).clip(CircleShape).background(GatewaySignal))
|
||||
Text("LIVE", color = GatewayPrimary, style = MaterialTheme.typography.labelSmall, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
package com.androidsmsgateway.ui.screens
|
||||
|
||||
import android.Manifest
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.widget.Toast
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.CheckCircle
|
||||
import androidx.compose.material.icons.outlined.ContentCopy
|
||||
import androidx.compose.material.icons.outlined.Description
|
||||
import androidx.compose.material.icons.outlined.ErrorOutline
|
||||
import androidx.compose.material.icons.outlined.Language
|
||||
import androidx.compose.material.icons.outlined.Security
|
||||
import androidx.compose.material.icons.outlined.StopCircle
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableLongStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.net.toUri
|
||||
import com.androidsmsgateway.domain.ServerState
|
||||
import com.androidsmsgateway.ui.GatewayUiState
|
||||
import com.androidsmsgateway.ui.components.BadgeTone
|
||||
import com.androidsmsgateway.ui.components.GatewayCard
|
||||
import com.androidsmsgateway.ui.components.GatewayCardShape
|
||||
import com.androidsmsgateway.ui.components.InfoBanner
|
||||
import com.androidsmsgateway.ui.components.ScreenHeader
|
||||
import com.androidsmsgateway.ui.components.StatusBadge
|
||||
import com.androidsmsgateway.ui.theme.GatewayErrorBackground
|
||||
import com.androidsmsgateway.ui.theme.GatewayMint
|
||||
import com.androidsmsgateway.ui.theme.GatewayPrimary
|
||||
import com.androidsmsgateway.ui.theme.GatewayPrimaryDark
|
||||
import com.androidsmsgateway.ui.theme.GatewaySignal
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
@Composable
|
||||
fun DashboardScreen(
|
||||
state: GatewayUiState,
|
||||
expanded: Boolean,
|
||||
start: () -> Unit,
|
||||
stop: () -> Unit,
|
||||
openSecurity: () -> Unit,
|
||||
openPermissions: () -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val running = state.server.state == ServerState.RUNNING
|
||||
var now by remember { mutableLongStateOf(System.currentTimeMillis()) }
|
||||
var confirmStop by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(running) {
|
||||
while (running) {
|
||||
now = System.currentTimeMillis()
|
||||
delay(1_000)
|
||||
}
|
||||
}
|
||||
|
||||
val hasSend = ContextCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED
|
||||
val hasReceive = ContextCompat.checkSelfPermission(context, Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED
|
||||
val authenticationReady = state.settings?.let { !it.authenticationEnabled || it.apiKeyHash.isNotBlank() } ?: true
|
||||
|
||||
Column(
|
||||
Modifier.verticalScroll(rememberScrollState()).padding(horizontal = if (expanded) 28.dp else 16.dp, vertical = 18.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
) {
|
||||
ScreenHeader("SMS Gateway", "Operations console")
|
||||
if (expanded) {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.Top) {
|
||||
Column(Modifier.weight(1.15f), verticalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
ServerHeroCard(state, now, start)
|
||||
MetricsRow(state)
|
||||
}
|
||||
Column(Modifier.weight(0.85f), verticalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
LastRequestCard(state)
|
||||
SecuritySummaryCard(state, openSecurity)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ServerHeroCard(state, now, start)
|
||||
MetricsRow(state)
|
||||
LastRequestCard(state)
|
||||
SecuritySummaryCard(state, openSecurity)
|
||||
}
|
||||
|
||||
if (!authenticationReady) {
|
||||
InfoBanner(
|
||||
title = "Security setup required",
|
||||
body = "Configure an API key before connecting a backend.",
|
||||
warning = true,
|
||||
modifier = Modifier.clip(RoundedCornerShape(13.dp)),
|
||||
)
|
||||
}
|
||||
if (!hasSend || !hasReceive) {
|
||||
OutlinedButton(onClick = openPermissions, modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(13.dp)) {
|
||||
Icon(Icons.Outlined.ErrorOutline, contentDescription = null)
|
||||
Spacer(Modifier.size(8.dp))
|
||||
Text("Review missing SMS permissions")
|
||||
}
|
||||
}
|
||||
if (running) {
|
||||
Button(
|
||||
onClick = { confirmStop = true },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(13.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.errorContainer,
|
||||
contentColor = MaterialTheme.colorScheme.onErrorContainer,
|
||||
),
|
||||
) {
|
||||
Icon(Icons.Outlined.StopCircle, contentDescription = null)
|
||||
Spacer(Modifier.size(8.dp))
|
||||
Text("Stop server")
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
}
|
||||
|
||||
if (confirmStop) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmStop = false },
|
||||
icon = { Icon(Icons.Outlined.StopCircle, contentDescription = null) },
|
||||
title = { Text("Stop the gateway?") },
|
||||
text = { Text("API clients will immediately lose access until the server is started again.") },
|
||||
confirmButton = {
|
||||
Button(
|
||||
onClick = { confirmStop = false; stop() },
|
||||
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error),
|
||||
) { Text("Stop server") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { confirmStop = false }) { Text("Keep running") } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ServerHeroCard(state: GatewayUiState, now: Long, start: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val status = state.server.state
|
||||
val running = status == ServerState.RUNNING
|
||||
val busy = status == ServerState.STARTING || status == ServerState.STOPPING
|
||||
val error = status == ServerState.ERROR
|
||||
val container = when {
|
||||
running -> GatewayPrimaryDark
|
||||
error -> MaterialTheme.colorScheme.errorContainer
|
||||
else -> MaterialTheme.colorScheme.surface
|
||||
}
|
||||
val foreground = when {
|
||||
running -> Color.White
|
||||
error -> MaterialTheme.colorScheme.onErrorContainer
|
||||
else -> MaterialTheme.colorScheme.onSurface
|
||||
}
|
||||
val muted = foreground.copy(alpha = 0.72f)
|
||||
val title = when (status) {
|
||||
ServerState.RUNNING -> "Gateway online"
|
||||
ServerState.STARTING -> "Bringing gateway online"
|
||||
ServerState.STOPPING -> "Stopping gateway"
|
||||
ServerState.ERROR -> "Server failed to start"
|
||||
ServerState.STOPPED -> "Ready when you are"
|
||||
}
|
||||
val summary = when (status) {
|
||||
ServerState.RUNNING -> "Secure and reachable on your network"
|
||||
ServerState.STARTING -> "Opening the HTTP listener"
|
||||
ServerState.STOPPING -> "Closing active gateway resources"
|
||||
ServerState.ERROR -> state.server.lastError ?: "The HTTP listener could not be started"
|
||||
ServerState.STOPPED -> "Start the server when permissions and security are ready"
|
||||
}
|
||||
GatewayCard(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
containerColor = container,
|
||||
contentPadding = androidx.compose.foundation.layout.PaddingValues(18.dp),
|
||||
) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
|
||||
StatusBadge(
|
||||
text = status.name,
|
||||
tone = when (status) {
|
||||
ServerState.RUNNING -> BadgeTone.SUCCESS
|
||||
ServerState.STARTING, ServerState.STOPPING -> BadgeTone.INFO
|
||||
ServerState.ERROR -> BadgeTone.ERROR
|
||||
ServerState.STOPPED -> BadgeTone.NEUTRAL
|
||||
},
|
||||
)
|
||||
if (running) Icon(Icons.Outlined.CheckCircle, "Server is healthy", tint = GatewaySignal)
|
||||
}
|
||||
Column(verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Text(title, style = MaterialTheme.typography.headlineMedium, color = foreground)
|
||||
Text(summary, style = MaterialTheme.typography.bodyMedium, color = muted, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clip(RoundedCornerShape(12.dp)).background(foreground.copy(alpha = 0.08f)).padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(Icons.Outlined.Language, contentDescription = null, tint = if (running) GatewaySignal else GatewayPrimary, modifier = Modifier.size(19.dp))
|
||||
Text(
|
||||
"${state.server.ipAddress}:${state.server.port}",
|
||||
modifier = Modifier.weight(1f).padding(horizontal = 9.dp),
|
||||
color = foreground,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
IconButton(
|
||||
onClick = {
|
||||
val address = "${state.server.ipAddress}:${state.server.port}"
|
||||
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
clipboard.setPrimaryClip(ClipData.newPlainText("Gateway address", address))
|
||||
Toast.makeText(context, "Gateway address copied", Toast.LENGTH_SHORT).show()
|
||||
},
|
||||
modifier = Modifier.size(34.dp),
|
||||
) { Icon(Icons.Outlined.ContentCopy, "Copy gateway address", tint = muted, modifier = Modifier.size(17.dp)) }
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
|
||||
Column {
|
||||
Text("UPTIME", style = MaterialTheme.typography.labelSmall, color = muted)
|
||||
Text(formatDuration(state.server.uptimeMillis(now)), style = MaterialTheme.typography.labelLarge, color = foreground)
|
||||
}
|
||||
if (running) {
|
||||
TextButton(
|
||||
onClick = {
|
||||
val host = state.server.ipAddress.takeUnless { it == "Unavailable" } ?: "127.0.0.1"
|
||||
context.startActivity(Intent(Intent.ACTION_VIEW, "http://$host:${state.server.port}/docs".toUri()))
|
||||
},
|
||||
colors = ButtonDefaults.textButtonColors(contentColor = GatewaySignal),
|
||||
) {
|
||||
Icon(Icons.Outlined.Description, contentDescription = null, modifier = Modifier.size(17.dp))
|
||||
Spacer(Modifier.size(6.dp))
|
||||
Text("Open API docs")
|
||||
}
|
||||
} else {
|
||||
Button(onClick = start, enabled = !busy, shape = RoundedCornerShape(11.dp)) {
|
||||
Text(if (error) "Retry" else if (busy) status.name.lowercase().replaceFirstChar(Char::uppercase) else "Start server")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MetricsRow(state: GatewayUiState) {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
MetricCard("Requests", state.requestCount, Modifier.weight(1f))
|
||||
MetricCard("Outgoing", state.sentCount, Modifier.weight(1f))
|
||||
MetricCard("Incoming", state.receivedCount, Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MetricCard(label: String, value: Long, modifier: Modifier) {
|
||||
GatewayCard(modifier = modifier, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 12.dp, vertical = 14.dp)) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||
Text(formatCount(value), style = MaterialTheme.typography.headlineMedium, maxLines = 1)
|
||||
Text(label, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LastRequestCard(state: GatewayUiState) {
|
||||
GatewayCard(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("Last request", style = MaterialTheme.typography.titleMedium)
|
||||
state.lastRequest?.let {
|
||||
StatusBadge(it.statusCode.toString(), if (it.statusCode in 200..299) BadgeTone.SUCCESS else if (it.statusCode >= 500) BadgeTone.ERROR else BadgeTone.WARNING)
|
||||
}
|
||||
}
|
||||
state.lastRequest?.let {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatusBadge(it.method, BadgeTone.INFO)
|
||||
Text(it.path, style = MaterialTheme.typography.labelLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
Text("${it.durationMs} ms · ${it.clientIp} · ${formatTime(it.timestamp)}", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
} ?: Text("No API requests yet", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SecuritySummaryCard(state: GatewayUiState, openSecurity: () -> Unit) {
|
||||
val settings = state.settings
|
||||
val authenticationReady = settings != null && settings.authenticationEnabled && settings.apiKeyHash.isNotBlank()
|
||||
val protected = authenticationReady && settings.allowlistEnabled && settings.allowedIps.isNotEmpty()
|
||||
GatewayCard(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(9.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Icon(Icons.Outlined.Security, contentDescription = null, tint = if (authenticationReady) GatewayPrimary else MaterialTheme.colorScheme.error)
|
||||
Column {
|
||||
Text(if (protected) "Protected" else if (authenticationReady) "API key protected" else "Needs attention", style = MaterialTheme.typography.titleMedium)
|
||||
Text(
|
||||
if (settings?.allowlistEnabled == true) "Allowlist · ${settings.allowedIps.size} trusted clients" else "Allowlist is disabled",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
StatusBadge(if (protected) "Healthy" else "Review", if (protected) BadgeTone.SUCCESS else BadgeTone.WARNING)
|
||||
}
|
||||
TextButton(onClick = openSecurity, modifier = Modifier.align(Alignment.End)) { Text("Review security") }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.androidsmsgateway.ui.screens
|
||||
|
||||
import java.text.DateFormat
|
||||
import java.text.NumberFormat
|
||||
import java.util.Date
|
||||
|
||||
internal fun formatTimestamp(value: Long): String =
|
||||
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(Date(value))
|
||||
|
||||
internal fun formatTime(value: Long): String =
|
||||
DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(value))
|
||||
|
||||
internal fun formatDuration(milliseconds: Long): String {
|
||||
val seconds = milliseconds / 1000
|
||||
return "%02d:%02d:%02d".format(seconds / 3600, seconds % 3600 / 60, seconds % 60)
|
||||
}
|
||||
|
||||
internal fun formatCount(value: Long): String = NumberFormat.getIntegerInstance().format(value)
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.androidsmsgateway.ui.screens
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.outlined.ReceiptLong
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.FilterChipDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.androidsmsgateway.data.local.RequestLogEntity
|
||||
import com.androidsmsgateway.ui.GatewayUiState
|
||||
import com.androidsmsgateway.ui.components.BadgeTone
|
||||
import com.androidsmsgateway.ui.components.EmptyState
|
||||
import com.androidsmsgateway.ui.components.GatewayCard
|
||||
import com.androidsmsgateway.ui.components.GatewaySearchField
|
||||
import com.androidsmsgateway.ui.components.LiveBadge
|
||||
import com.androidsmsgateway.ui.components.ScreenHeader
|
||||
import com.androidsmsgateway.ui.components.StatusBadge
|
||||
import com.androidsmsgateway.ui.theme.GatewayPrimary
|
||||
|
||||
private data class LogFilter(val label: String, val accepts: (Int) -> Boolean)
|
||||
|
||||
private val filters = listOf(
|
||||
LogFilter("All") { true },
|
||||
LogFilter("Success") { it in 200..399 },
|
||||
LogFilter("4xx") { it in 400..499 },
|
||||
LogFilter("5xx") { it >= 500 },
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun LogsScreen(state: GatewayUiState) {
|
||||
var selectedFilter by rememberSaveable { mutableIntStateOf(0) }
|
||||
var query by rememberSaveable { mutableStateOf("") }
|
||||
val visibleLogs = remember(state.logs, selectedFilter, query) {
|
||||
state.logs.filter {
|
||||
filters[selectedFilter].accepts(it.statusCode) &&
|
||||
(query.isBlank() || it.path.contains(query, true) || it.clientIp.contains(query, true) || it.method.contains(query, true))
|
||||
}
|
||||
}
|
||||
val listState = rememberLazyListState()
|
||||
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
Column(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 18.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(13.dp),
|
||||
) {
|
||||
ScreenHeader("Request logs", "HTTP traffic", trailing = { LiveBadge() })
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(7.dp)) {
|
||||
filters.forEachIndexed { index, filter ->
|
||||
FilterChip(
|
||||
selected = selectedFilter == index,
|
||||
onClick = { selectedFilter = index },
|
||||
label = { Text(filter.label) },
|
||||
shape = RoundedCornerShape(50),
|
||||
colors = FilterChipDefaults.filterChipColors(
|
||||
selectedContainerColor = MaterialTheme.colorScheme.onSurface,
|
||||
selectedLabelColor = MaterialTheme.colorScheme.surface,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
GatewaySearchField(query, { query = it.take(100) }, "Search path or client IP")
|
||||
}
|
||||
if (visibleLogs.isEmpty()) {
|
||||
EmptyState(
|
||||
icon = Icons.AutoMirrored.Outlined.ReceiptLong,
|
||||
title = if (state.logs.isEmpty()) "No API requests yet" else "No matching requests",
|
||||
body = if (state.logs.isEmpty()) "Requests will appear here as clients use the gateway." else "Try a different response filter, path, or client IP.",
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
} else {
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
state = listState,
|
||||
contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 20.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
items(visibleLogs, key = { it.id }) { log -> LogCard(log) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LogCard(log: RequestLogEntity) {
|
||||
val tone = when (log.statusCode) {
|
||||
in 200..399 -> BadgeTone.SUCCESS
|
||||
in 400..499 -> BadgeTone.WARNING
|
||||
else -> BadgeTone.ERROR
|
||||
}
|
||||
GatewayCard(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(9.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(9.dp)) {
|
||||
StatusBadge(log.method, if (log.method == "GET") BadgeTone.SUCCESS else BadgeTone.INFO)
|
||||
Text(log.path, modifier = Modifier.weight(1f), style = MaterialTheme.typography.labelLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
StatusBadge(log.statusCode.toString(), tone)
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||
Text("${log.durationMs} ms · ${log.clientIp}", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Text(formatTime(log.timestamp), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package com.androidsmsgateway.ui.screens
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Inbox
|
||||
import androidx.compose.material.icons.outlined.MarkEmailRead
|
||||
import androidx.compose.material.icons.outlined.Outbox
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.androidsmsgateway.data.local.IncomingSmsEntity
|
||||
import com.androidsmsgateway.data.local.OutgoingSmsEntity
|
||||
import com.androidsmsgateway.ui.GatewayUiState
|
||||
import com.androidsmsgateway.ui.components.BadgeTone
|
||||
import com.androidsmsgateway.ui.components.EmptyState
|
||||
import com.androidsmsgateway.ui.components.GatewayCard
|
||||
import com.androidsmsgateway.ui.components.GatewaySearchField
|
||||
import com.androidsmsgateway.ui.components.LiveBadge
|
||||
import com.androidsmsgateway.ui.components.ScreenHeader
|
||||
import com.androidsmsgateway.ui.components.StatusBadge
|
||||
import com.androidsmsgateway.ui.theme.GatewayInfoBackground
|
||||
import com.androidsmsgateway.ui.theme.GatewayMint
|
||||
import com.androidsmsgateway.ui.theme.GatewayPrimary
|
||||
|
||||
@Composable
|
||||
fun MessagesScreen(state: GatewayUiState) {
|
||||
var tab by rememberSaveable { mutableIntStateOf(0) }
|
||||
var query by rememberSaveable { mutableStateOf("") }
|
||||
val incoming = remember(state.incoming, query) {
|
||||
state.incoming.filter { query.isBlank() || it.sender.contains(query, true) || it.message.contains(query, true) }
|
||||
}
|
||||
val outgoing = remember(state.outgoing, query) {
|
||||
state.outgoing.filter {
|
||||
query.isBlank() || it.recipient.contains(query, true) || it.message.contains(query, true) || it.status.contains(query, true)
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
Column(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 18.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
) {
|
||||
ScreenHeader("Messages", "Live SMS activity", trailing = { LiveBadge() })
|
||||
MessageTabs(tab) { tab = it }
|
||||
GatewaySearchField(
|
||||
value = query,
|
||||
onValueChange = { query = it.take(100) },
|
||||
placeholder = "Search sender or message",
|
||||
)
|
||||
}
|
||||
when {
|
||||
tab == 0 && incoming.isEmpty() -> EmptyState(
|
||||
icon = Icons.Outlined.Inbox,
|
||||
title = if (query.isBlank()) "No incoming messages" else "No matching messages",
|
||||
body = if (query.isBlank()) "Messages received by this device will appear here." else "Try another sender, number, or phrase.",
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
tab == 1 && outgoing.isEmpty() -> EmptyState(
|
||||
icon = Icons.Outlined.Outbox,
|
||||
title = if (query.isBlank()) "No outgoing messages" else "No matching messages",
|
||||
body = if (query.isBlank()) "SMS requests submitted through the API will appear here." else "Try another recipient, status, or phrase.",
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
tab == 0 -> IncomingList(incoming)
|
||||
else -> OutgoingList(outgoing)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MessageTabs(selected: Int, onSelected: (Int) -> Unit) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(MaterialTheme.colorScheme.surfaceVariant).padding(4.dp),
|
||||
) {
|
||||
listOf("Incoming", "Outgoing").forEachIndexed { index, label ->
|
||||
Box(
|
||||
Modifier.weight(1f).clip(RoundedCornerShape(11.dp))
|
||||
.background(if (selected == index) MaterialTheme.colorScheme.surface else MaterialTheme.colorScheme.surfaceVariant)
|
||||
.clickable { onSelected(index) }
|
||||
.padding(vertical = 10.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
label,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = if (selected == index) GatewayPrimary else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun IncomingList(messages: List<IncomingSmsEntity>) {
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 20.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
items(messages, key = { it.id }) { item ->
|
||||
MessageCard(item.sender, item.message, item.status, item.receivedAt, incoming = true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun OutgoingList(messages: List<OutgoingSmsEntity>) {
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 20.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
items(messages, key = { it.id }) { item ->
|
||||
MessageCard(item.recipient, item.message, item.status, item.requestedAt, incoming = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MessageCard(address: String, body: String, status: String, timestamp: Long, incoming: Boolean) {
|
||||
val normalized = status.lowercase()
|
||||
val tone = when (normalized) {
|
||||
"received", "sent" -> BadgeTone.SUCCESS
|
||||
"pending" -> BadgeTone.INFO
|
||||
"failed" -> BadgeTone.ERROR
|
||||
else -> BadgeTone.NEUTRAL
|
||||
}
|
||||
val avatarColor = if (incoming) GatewayMint else GatewayInfoBackground
|
||||
GatewayCard(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(11.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(11.dp)) {
|
||||
Box(Modifier.size(38.dp).clip(CircleShape).background(avatarColor), contentAlignment = Alignment.Center) {
|
||||
Text(initials(address), style = MaterialTheme.typography.labelMedium, color = GatewayPrimary, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(address, style = MaterialTheme.typography.titleMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
StatusBadge(normalized, tone)
|
||||
}
|
||||
Text(formatTime(timestamp), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Text(body, style = MaterialTheme.typography.bodyMedium, maxLines = 4, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun initials(value: String): String {
|
||||
val letters = value.trim().split(Regex("\\s+")).mapNotNull { it.firstOrNull()?.takeIf(Char::isLetterOrDigit) }
|
||||
return when {
|
||||
letters.size >= 2 -> "${letters[0]}${letters[1]}".uppercase()
|
||||
letters.size == 1 -> letters[0].uppercase()
|
||||
else -> "SMS"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package com.androidsmsgateway.ui.screens
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.compose.LocalActivity
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
|
||||
import androidx.compose.material.icons.outlined.Check
|
||||
import androidx.compose.material.icons.outlined.Lock
|
||||
import androidx.compose.material.icons.outlined.WarningAmber
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.net.toUri
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import com.androidsmsgateway.ui.components.BadgeTone
|
||||
import com.androidsmsgateway.ui.components.GatewayCard
|
||||
import com.androidsmsgateway.ui.components.InfoBanner
|
||||
import com.androidsmsgateway.ui.components.ScreenHeader
|
||||
import com.androidsmsgateway.ui.components.StatusBadge
|
||||
import com.androidsmsgateway.ui.theme.GatewayMint
|
||||
import com.androidsmsgateway.ui.theme.GatewayPrimary
|
||||
import com.androidsmsgateway.ui.theme.GatewayWarning
|
||||
import com.androidsmsgateway.ui.theme.GatewayWarningBackground
|
||||
|
||||
private data class PermissionItem(val title: String, val permission: String, val description: String)
|
||||
|
||||
@Composable
|
||||
fun PermissionsScreen(onBack: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val activity = LocalActivity.current
|
||||
val lifecycleOwner = activity as? LifecycleOwner
|
||||
var refresh by remember { mutableIntStateOf(0) }
|
||||
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { refresh++ }
|
||||
val permissions = buildList {
|
||||
add(PermissionItem("Send SMS", Manifest.permission.SEND_SMS, "Required to send messages through the API"))
|
||||
add(PermissionItem("Receive SMS", Manifest.permission.RECEIVE_SMS, "Required to persist incoming messages"))
|
||||
if (Build.VERSION.SDK_INT >= 33) {
|
||||
add(PermissionItem("Gateway notification", Manifest.permission.POST_NOTIFICATIONS, "Keeps the foreground server visible"))
|
||||
}
|
||||
}
|
||||
val grantState = permissions.associateWith {
|
||||
refresh
|
||||
ContextCompat.checkSelfPermission(context, it.permission) == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
val granted = grantState.count { it.value }
|
||||
|
||||
DisposableEffect(lifecycleOwner) {
|
||||
val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_RESUME) refresh++ }
|
||||
lifecycleOwner?.lifecycle?.addObserver(observer)
|
||||
onDispose { lifecycleOwner?.lifecycle?.removeObserver(observer) }
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier.verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 18.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
) {
|
||||
ScreenHeader(
|
||||
title = "SMS permissions",
|
||||
subtitle = "Android access",
|
||||
leading = {
|
||||
IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Outlined.ArrowBack, contentDescription = "Back to server settings") }
|
||||
},
|
||||
)
|
||||
GatewayCard(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text("Gateway readiness", style = MaterialTheme.typography.labelLarge)
|
||||
Text("$granted of ${permissions.size} permissions granted", style = MaterialTheme.typography.titleLarge)
|
||||
LinearProgressIndicator(
|
||||
progress = { granted.toFloat() / permissions.size.coerceAtLeast(1) },
|
||||
modifier = Modifier.fillMaxWidth().clip(CircleShape),
|
||||
color = GatewayPrimary,
|
||||
trackColor = MaterialTheme.colorScheme.surfaceVariant,
|
||||
drawStopIndicator = {},
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"Permissions are requested only when you choose to grant them.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
permissions.forEach { item ->
|
||||
PermissionCard(item, grantState.getValue(item)) { launcher.launch(item.permission) }
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = { context.startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, "package:${context.packageName}".toUri())) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(13.dp),
|
||||
) { Text("Open Android app settings") }
|
||||
InfoBanner(
|
||||
title = "Your privacy",
|
||||
body = "SMS access stays on this device and is never requested without context.",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PermissionCard(item: PermissionItem, granted: Boolean, grant: () -> Unit) {
|
||||
GatewayCard(Modifier.fillMaxWidth()) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(13.dp)) {
|
||||
Box(
|
||||
Modifier.size(40.dp).clip(CircleShape).background(if (granted) GatewayMint else GatewayWarningBackground),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
if (granted) Icons.Outlined.Check else Icons.Outlined.WarningAmber,
|
||||
contentDescription = null,
|
||||
tint = if (granted) GatewayPrimary else GatewayWarning,
|
||||
)
|
||||
}
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Text(item.title, style = MaterialTheme.typography.titleMedium)
|
||||
StatusBadge(if (granted) "Granted" else "Required", if (granted) BadgeTone.SUCCESS else BadgeTone.WARNING)
|
||||
Text(item.description, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
if (!granted) Button(onClick = grant, shape = RoundedCornerShape(50)) { Text("Grant") }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package com.androidsmsgateway.ui.screens
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Key
|
||||
import androidx.compose.material.icons.outlined.Security
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.androidsmsgateway.ui.GatewayUiState
|
||||
import com.androidsmsgateway.ui.GatewayViewModel
|
||||
import com.androidsmsgateway.security.SecurityPolicy
|
||||
import com.androidsmsgateway.ui.components.BadgeTone
|
||||
import com.androidsmsgateway.ui.components.GatewayCard
|
||||
import com.androidsmsgateway.ui.components.GatewayControlShape
|
||||
import com.androidsmsgateway.ui.components.InfoBanner
|
||||
import com.androidsmsgateway.ui.components.ScreenHeader
|
||||
import com.androidsmsgateway.ui.components.SectionLabel
|
||||
import com.androidsmsgateway.ui.components.SettingToggleRow
|
||||
import com.androidsmsgateway.ui.components.StatusBadge
|
||||
import com.androidsmsgateway.ui.theme.GatewayMint
|
||||
import com.androidsmsgateway.ui.theme.GatewayPrimary
|
||||
import com.androidsmsgateway.ui.theme.GatewayPrimaryDark
|
||||
import com.androidsmsgateway.ui.theme.GatewaySignal
|
||||
|
||||
@Composable
|
||||
fun SecurityScreen(state: GatewayUiState, viewModel: GatewayViewModel) {
|
||||
val settings = state.settings ?: return
|
||||
var newKey by remember { mutableStateOf("") }
|
||||
var ip by remember { mutableStateOf("") }
|
||||
var confirmDisableAuth by remember { mutableStateOf(false) }
|
||||
var confirmEmptyAllowlist by remember { mutableStateOf(false) }
|
||||
var showKeyDialog by remember { mutableStateOf(false) }
|
||||
var pendingRemoval by remember { mutableStateOf<String?>(null) }
|
||||
val keyConfigured = settings.apiKeyHash.isNotBlank()
|
||||
val protected = settings.authenticationEnabled && keyConfigured
|
||||
val score = when {
|
||||
protected && settings.allowlistEnabled && settings.allowedIps.isNotEmpty() -> 82
|
||||
protected -> 62
|
||||
settings.authenticationEnabled -> 34
|
||||
else -> 12
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier.verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 18.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
) {
|
||||
ScreenHeader("Security", "Access control")
|
||||
SecurityHero(protected, settings.allowlistEnabled, settings.allowedIps.size, score)
|
||||
SectionLabel("Gateway authentication")
|
||||
GatewayCard(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
SettingToggleRow(
|
||||
title = "Require API key",
|
||||
description = "Authenticate every operational API request",
|
||||
checked = settings.authenticationEnabled,
|
||||
onCheckedChange = { enabled ->
|
||||
if (!enabled && settings.authenticationEnabled) confirmDisableAuth = true
|
||||
else viewModel.setAuthenticationEnabled(enabled)
|
||||
},
|
||||
)
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Icon(Icons.Outlined.Key, contentDescription = null, tint = if (keyConfigured) GatewayPrimary else MaterialTheme.colorScheme.error)
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(if (keyConfigured) "API key configured" else "API key not configured", style = MaterialTheme.typography.labelLarge)
|
||||
Text(
|
||||
if (keyConfigured) "Stored securely as a one-way hash" else "A key of at least 16 characters is required",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
StatusBadge(if (keyConfigured) "Hidden" else "Required", if (keyConfigured) BadgeTone.SUCCESS else BadgeTone.WARNING)
|
||||
}
|
||||
if (!keyConfigured) {
|
||||
OutlinedTextField(
|
||||
value = newKey,
|
||||
onValueChange = { newKey = it.take(256) },
|
||||
label = { Text("New API key") },
|
||||
supportingText = { Text("Minimum 16 characters") },
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
singleLine = true,
|
||||
shape = GatewayControlShape,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Button(
|
||||
onClick = { viewModel.setApiKey(newKey); if (newKey.length >= 16) newKey = "" },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = GatewayControlShape,
|
||||
) { Text("Set API key") }
|
||||
} else {
|
||||
OutlinedButton(onClick = { showKeyDialog = true }, modifier = Modifier.fillMaxWidth(), shape = GatewayControlShape) {
|
||||
Text("Rotate API key")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SectionLabel("IP allowlist")
|
||||
GatewayCard(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(13.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("IP allowlist", style = MaterialTheme.typography.titleMedium)
|
||||
Text("Only exact client IPs can call operations", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
StatusBadge(if (settings.allowlistEnabled) "Enabled" else "Off", if (settings.allowlistEnabled) BadgeTone.SUCCESS else BadgeTone.NEUTRAL)
|
||||
}
|
||||
SettingToggleRow(
|
||||
title = "Enable allowlist",
|
||||
description = "Documentation stays public; API operations are restricted",
|
||||
checked = settings.allowlistEnabled,
|
||||
onCheckedChange = { enabled ->
|
||||
if (enabled && settings.allowedIps.isEmpty()) confirmEmptyAllowlist = true
|
||||
else viewModel.setAllowlistEnabled(enabled)
|
||||
},
|
||||
)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
OutlinedTextField(
|
||||
value = ip,
|
||||
onValueChange = { ip = it.take(45) },
|
||||
label = { Text("IP address") },
|
||||
singleLine = true,
|
||||
shape = GatewayControlShape,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Button(
|
||||
onClick = {
|
||||
viewModel.addAllowedIp(ip)
|
||||
if (SecurityPolicy.isValidIp(ip.trim())) ip = ""
|
||||
},
|
||||
shape = GatewayControlShape,
|
||||
) { Text("Add") }
|
||||
}
|
||||
if (settings.allowedIps.isEmpty()) {
|
||||
Text("No trusted client IPs added", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
} else {
|
||||
settings.allowedIps.sorted().forEach { allowed ->
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(allowed, modifier = Modifier.weight(1f), style = MaterialTheme.typography.labelLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
TextButton(onClick = {
|
||||
if (settings.allowlistEnabled && settings.allowedIps.size == 1) pendingRemoval = allowed
|
||||
else viewModel.removeAllowedIp(allowed)
|
||||
}) { Text("Remove", color = MaterialTheme.colorScheme.error) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
InfoBanner(
|
||||
title = "Security notes",
|
||||
body = "API keys and authentication headers are never written to logs. CIDR and HMAC signing can be added in a later phase.",
|
||||
)
|
||||
}
|
||||
|
||||
if (confirmDisableAuth) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmDisableAuth = false },
|
||||
icon = { Icon(Icons.Outlined.Security, contentDescription = null) },
|
||||
title = { Text("Disable API authentication?") },
|
||||
text = { Text("Any client that can reach this device may call the API unless the IP allowlist blocks it.") },
|
||||
confirmButton = {
|
||||
Button(
|
||||
onClick = { confirmDisableAuth = false; viewModel.setAuthenticationEnabled(false) },
|
||||
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error),
|
||||
) { Text("Disable") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { confirmDisableAuth = false }) { Text("Keep enabled") } },
|
||||
)
|
||||
}
|
||||
if (confirmEmptyAllowlist) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmEmptyAllowlist = false },
|
||||
title = { Text("Enable an empty allowlist?") },
|
||||
text = { Text("Every operational API client will be blocked until at least one IP address is added.") },
|
||||
confirmButton = {
|
||||
Button(onClick = { confirmEmptyAllowlist = false; viewModel.setAllowlistEnabled(true) }) { Text("Enable") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { confirmEmptyAllowlist = false }) { Text("Cancel") } },
|
||||
)
|
||||
}
|
||||
if (showKeyDialog) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showKeyDialog = false; newKey = "" },
|
||||
title = { Text("Rotate API key") },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text("The current backend key will stop working immediately.")
|
||||
OutlinedTextField(
|
||||
value = newKey,
|
||||
onValueChange = { newKey = it.take(256) },
|
||||
label = { Text("New API key") },
|
||||
supportingText = { Text("Minimum 16 characters") },
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
singleLine = true,
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
Button(onClick = {
|
||||
viewModel.setApiKey(newKey)
|
||||
if (newKey.length >= 16) { showKeyDialog = false; newKey = "" }
|
||||
}) { Text("Rotate key") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { showKeyDialog = false; newKey = "" }) { Text("Cancel") } },
|
||||
)
|
||||
}
|
||||
pendingRemoval?.let { address ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { pendingRemoval = null },
|
||||
title = { Text("Remove the last allowed IP?") },
|
||||
text = { Text("The allowlist will stay enabled and every operational API client will be blocked.") },
|
||||
confirmButton = {
|
||||
Button(
|
||||
onClick = { viewModel.removeAllowedIp(address); pendingRemoval = null },
|
||||
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error),
|
||||
) { Text("Remove") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { pendingRemoval = null }) { Text("Keep address") } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SecurityHero(protected: Boolean, allowlist: Boolean, trustedClients: Int, score: Int) {
|
||||
GatewayCard(
|
||||
Modifier.fillMaxWidth(),
|
||||
containerColor = GatewayPrimaryDark,
|
||||
contentPadding = androidx.compose.foundation.layout.PaddingValues(18.dp),
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(13.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Box(Modifier.size(38.dp).clip(RoundedCornerShape(12.dp)).background(Color.White.copy(alpha = 0.08f)), contentAlignment = Alignment.Center) {
|
||||
Icon(Icons.Outlined.Security, contentDescription = null, tint = GatewaySignal)
|
||||
}
|
||||
Column {
|
||||
Text("Security posture", style = MaterialTheme.typography.bodySmall, color = Color.White.copy(alpha = 0.7f))
|
||||
Text(if (protected) "Protected" else "Needs attention", style = MaterialTheme.typography.headlineMedium, color = Color.White)
|
||||
}
|
||||
}
|
||||
Column(horizontalAlignment = Alignment.End) {
|
||||
Text(score.toString(), style = MaterialTheme.typography.headlineLarge, color = GatewaySignal)
|
||||
Text("/100", style = MaterialTheme.typography.labelSmall, color = Color.White.copy(alpha = 0.65f))
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"Authentication ${if (protected) "active" else "needs setup"} · ${if (allowlist) "$trustedClients trusted clients" else "allowlist disabled"}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = Color.White.copy(alpha = 0.72f),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package com.androidsmsgateway.ui.screens
|
||||
|
||||
import android.content.Intent
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.AdminPanelSettings
|
||||
import androidx.compose.material.icons.outlined.Description
|
||||
import androidx.compose.material.icons.outlined.Language
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.net.toUri
|
||||
import com.androidsmsgateway.domain.ServerState
|
||||
import com.androidsmsgateway.security.SecurityPolicy
|
||||
import com.androidsmsgateway.ui.GatewayUiState
|
||||
import com.androidsmsgateway.ui.components.BadgeTone
|
||||
import com.androidsmsgateway.ui.components.ClickableSettingRow
|
||||
import com.androidsmsgateway.ui.components.GatewayCard
|
||||
import com.androidsmsgateway.ui.components.GatewayControlShape
|
||||
import com.androidsmsgateway.ui.components.InfoBanner
|
||||
import com.androidsmsgateway.ui.components.ScreenHeader
|
||||
import com.androidsmsgateway.ui.components.SectionLabel
|
||||
import com.androidsmsgateway.ui.components.SettingToggleRow
|
||||
import com.androidsmsgateway.ui.components.StatusBadge
|
||||
|
||||
@Composable
|
||||
fun ServerSettingsScreen(
|
||||
state: GatewayUiState,
|
||||
save: (String, String, Boolean) -> Unit,
|
||||
permissions: () -> Unit,
|
||||
) {
|
||||
val settings = state.settings ?: return
|
||||
val context = LocalContext.current
|
||||
var port by remember(settings.port) { mutableStateOf(settings.port.toString()) }
|
||||
var bind by remember(settings.bindAddress) { mutableStateOf(settings.bindAddress) }
|
||||
var boot by remember(settings.startOnBoot) { mutableStateOf(settings.startOnBoot) }
|
||||
var attempted by remember { mutableStateOf(false) }
|
||||
val portValid = port.toIntOrNull()?.let { it in 1024..65535 } == true
|
||||
val bindValid = SecurityPolicy.isValidIp(bind.trim())
|
||||
val running = state.server.state == ServerState.RUNNING
|
||||
|
||||
Column(
|
||||
Modifier.verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 18.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
) {
|
||||
ScreenHeader("Server", "Network configuration")
|
||||
GatewayCard(Modifier.fillMaxWidth()) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Icon(Icons.Outlined.Language, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Text(if (running) "Listening now" else "HTTP listener", style = MaterialTheme.typography.titleMedium)
|
||||
Text("${state.server.ipAddress}:${state.server.port}", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
StatusBadge(state.server.state.name, if (running) BadgeTone.SUCCESS else BadgeTone.NEUTRAL)
|
||||
}
|
||||
}
|
||||
|
||||
SectionLabel("Networking")
|
||||
GatewayCard(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
OutlinedTextField(
|
||||
value = port,
|
||||
onValueChange = { port = it.filter(Char::isDigit).take(5) },
|
||||
label = { Text("HTTP port") },
|
||||
supportingText = { Text(if (attempted && !portValid) "Enter a port from 1024 to 65535" else "Allowed range: 1024–65535") },
|
||||
isError = attempted && !portValid,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
singleLine = true,
|
||||
shape = GatewayControlShape,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = bind,
|
||||
onValueChange = { bind = it.take(45) },
|
||||
label = { Text("Bind address") },
|
||||
supportingText = { Text(if (attempted && !bindValid) "Enter a valid IPv4 or IPv6 address" else "Use 0.0.0.0 for all IPv4 interfaces") },
|
||||
isError = attempted && !bindValid,
|
||||
singleLine = true,
|
||||
shape = GatewayControlShape,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
SettingToggleRow(
|
||||
title = "Start after device reboot",
|
||||
description = "Restore the gateway when Android finishes booting",
|
||||
checked = boot,
|
||||
onCheckedChange = { boot = it },
|
||||
)
|
||||
Button(
|
||||
onClick = {
|
||||
attempted = true
|
||||
if (portValid && bindValid) save(port, bind, boot)
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(13.dp),
|
||||
) { Text(if (running) "Save, apply, and restart" else "Save and apply") }
|
||||
if (running) {
|
||||
Text(
|
||||
"Saving network changes briefly restarts the running server.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SectionLabel("Android access")
|
||||
ClickableSettingRow(
|
||||
title = "SMS permissions",
|
||||
description = "Review Send SMS, Receive SMS, and notification access",
|
||||
icon = Icons.Outlined.AdminPanelSettings,
|
||||
onClick = permissions,
|
||||
)
|
||||
if (running) {
|
||||
OutlinedButton(
|
||||
onClick = {
|
||||
val host = state.server.ipAddress.takeUnless { it == "Unavailable" } ?: "127.0.0.1"
|
||||
context.startActivity(Intent(Intent.ACTION_VIEW, "http://$host:${state.server.port}/docs".toUri()))
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(13.dp),
|
||||
) {
|
||||
Icon(Icons.Outlined.Description, contentDescription = null)
|
||||
Spacer(Modifier.size(8.dp))
|
||||
Text("Open interactive API documentation")
|
||||
}
|
||||
}
|
||||
InfoBanner(
|
||||
title = "Trusted networks only",
|
||||
body = "Plain HTTP is not encrypted. Use a private network, VPN, or TLS reverse proxy for remote access.",
|
||||
warning = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.androidsmsgateway.ui.theme
|
||||
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
val GatewayInk = Color(0xFF0B1F1B)
|
||||
val GatewayPrimary = Color(0xFF246B57)
|
||||
val GatewayPrimaryDark = Color(0xFF123E34)
|
||||
val GatewaySignal = Color(0xFF59C8A5)
|
||||
val GatewayMint = Color(0xFFD8F7EB)
|
||||
val GatewayNetwork = Color(0xFF43A5BA)
|
||||
val GatewayInfo = Color(0xFF2C6FB7)
|
||||
val GatewayInfoBackground = Color(0xFFDCEBFF)
|
||||
val GatewayWarning = Color(0xFFA06400)
|
||||
val GatewayWarningBackground = Color(0xFFFFF0C8)
|
||||
val GatewayError = Color(0xFFBA3A34)
|
||||
val GatewayErrorBackground = Color(0xFFFFDAD6)
|
||||
val GatewaySurface = Color(0xFFF5F8F6)
|
||||
val GatewaySurfaceHigh = Color(0xFFEAF0ED)
|
||||
val GatewayOutline = Color(0xFFD6DFDA)
|
||||
val GatewayTextMuted = Color(0xFF63736E)
|
||||
|
||||
private val LightColors = lightColorScheme(
|
||||
primary = GatewayPrimary,
|
||||
onPrimary = Color.White,
|
||||
primaryContainer = GatewayMint,
|
||||
onPrimaryContainer = GatewayPrimaryDark,
|
||||
secondary = GatewayNetwork,
|
||||
onSecondary = Color.White,
|
||||
secondaryContainer = GatewayInfoBackground,
|
||||
onSecondaryContainer = Color(0xFF173F5C),
|
||||
tertiary = GatewaySignal,
|
||||
onTertiary = GatewayInk,
|
||||
background = GatewaySurface,
|
||||
onBackground = GatewayInk,
|
||||
surface = Color.White,
|
||||
onSurface = GatewayInk,
|
||||
surfaceVariant = GatewaySurfaceHigh,
|
||||
onSurfaceVariant = GatewayTextMuted,
|
||||
outline = GatewayOutline,
|
||||
error = GatewayError,
|
||||
onError = Color.White,
|
||||
errorContainer = GatewayErrorBackground,
|
||||
onErrorContainer = Color(0xFF6C1714),
|
||||
)
|
||||
|
||||
private val DarkColors = darkColorScheme(
|
||||
primary = Color(0xFF77DDB8),
|
||||
onPrimary = Color(0xFF00382B),
|
||||
primaryContainer = Color(0xFF185240),
|
||||
onPrimaryContainer = Color(0xFFAAF3D5),
|
||||
secondary = Color(0xFF82D1DF),
|
||||
onSecondary = Color(0xFF00363E),
|
||||
secondaryContainer = Color(0xFF164C55),
|
||||
onSecondaryContainer = Color(0xFFB5EBF3),
|
||||
tertiary = Color(0xFF59C8A5),
|
||||
onTertiary = Color(0xFF00382B),
|
||||
background = Color(0xFF071814),
|
||||
onBackground = Color(0xFFE1EEE8),
|
||||
surface = Color(0xFF0D211C),
|
||||
onSurface = Color(0xFFE1EEE8),
|
||||
surfaceVariant = Color(0xFF17302A),
|
||||
onSurfaceVariant = Color(0xFFB6C9C1),
|
||||
outline = Color(0xFF38544B),
|
||||
error = Color(0xFFFFB4AB),
|
||||
onError = Color(0xFF690005),
|
||||
errorContainer = Color(0xFF5B211F),
|
||||
onErrorContainer = Color(0xFFFFDAD6),
|
||||
)
|
||||
|
||||
private val GatewayTypography = androidx.compose.material3.Typography(
|
||||
displaySmall = TextStyle(
|
||||
fontFamily = FontFamily.SansSerif,
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 36.sp,
|
||||
lineHeight = 42.sp,
|
||||
),
|
||||
headlineLarge = TextStyle(
|
||||
fontFamily = FontFamily.SansSerif,
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 30.sp,
|
||||
lineHeight = 36.sp,
|
||||
),
|
||||
headlineMedium = TextStyle(
|
||||
fontFamily = FontFamily.SansSerif,
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 24.sp,
|
||||
lineHeight = 30.sp,
|
||||
),
|
||||
titleLarge = TextStyle(
|
||||
fontFamily = FontFamily.SansSerif,
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 20.sp,
|
||||
lineHeight = 26.sp,
|
||||
),
|
||||
titleMedium = TextStyle(
|
||||
fontFamily = FontFamily.SansSerif,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
fontSize = 16.sp,
|
||||
lineHeight = 22.sp,
|
||||
),
|
||||
bodyLarge = TextStyle(
|
||||
fontFamily = FontFamily.SansSerif,
|
||||
fontWeight = FontWeight.Normal,
|
||||
fontSize = 15.sp,
|
||||
lineHeight = 22.sp,
|
||||
),
|
||||
bodyMedium = TextStyle(
|
||||
fontFamily = FontFamily.SansSerif,
|
||||
fontWeight = FontWeight.Normal,
|
||||
fontSize = 14.sp,
|
||||
lineHeight = 20.sp,
|
||||
),
|
||||
bodySmall = TextStyle(
|
||||
fontFamily = FontFamily.SansSerif,
|
||||
fontWeight = FontWeight.Normal,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
),
|
||||
labelLarge = TextStyle(
|
||||
fontFamily = FontFamily.SansSerif,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
fontSize = 14.sp,
|
||||
lineHeight = 20.sp,
|
||||
),
|
||||
labelMedium = TextStyle(
|
||||
fontFamily = FontFamily.SansSerif,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
letterSpacing = 0.2.sp,
|
||||
),
|
||||
labelSmall = TextStyle(
|
||||
fontFamily = FontFamily.SansSerif,
|
||||
fontWeight = FontWeight.Medium,
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 14.sp,
|
||||
letterSpacing = 0.35.sp,
|
||||
),
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun GatewayTheme(
|
||||
darkTheme: Boolean = isSystemInDarkTheme(),
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
MaterialTheme(
|
||||
colorScheme = if (darkTheme) DarkColors else LightColors,
|
||||
typography = GatewayTypography,
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="48dp"
|
||||
android:height="48dp"
|
||||
android:viewportWidth="48"
|
||||
android:viewportHeight="48">
|
||||
<path
|
||||
android:fillColor="#006C4C"
|
||||
android:pathData="M8,6h32a4,4 0,0 1,4 4v22a4,4 0,0 1,-4 4H20l-10,8v-8H8a4,4 0,0 1,-4 -4V10a4,4 0,0 1,4 -4z" />
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:pathData="M12,16h24v4H12zM12,24h18v4H12z" />
|
||||
</vector>
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
<resources>
|
||||
<string name="app_name">SMS Gateway</string>
|
||||
</resources>
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
<resources>
|
||||
<style name="Theme.AndroidSmsGateway" parent="android:style/Theme.Material.Light.NoActionBar">
|
||||
<item name="android:fontFamily">sans</item>
|
||||
<item name="android:windowLightStatusBar">true</item>
|
||||
<item name="android:statusBarColor">@android:color/transparent</item>
|
||||
<item name="android:navigationBarColor">@android:color/white</item>
|
||||
</style>
|
||||
</resources>
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<full-backup-content>
|
||||
<exclude domain="root" path="." />
|
||||
</full-backup-content>
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<data-extraction-rules>
|
||||
<cloud-backup>
|
||||
<exclude domain="root" path="." />
|
||||
</cloud-backup>
|
||||
<device-transfer>
|
||||
<exclude domain="root" path="." />
|
||||
</device-transfer>
|
||||
</data-extraction-rules>
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.androidsmsgateway.security
|
||||
|
||||
import com.androidsmsgateway.domain.GatewaySettings
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Test
|
||||
|
||||
class SecurityPolicyTest {
|
||||
@Test
|
||||
fun validBearerKeyIsAccepted() {
|
||||
val settings = settings(apiKeyHash = SecurityPolicy.hashApiKey("a-secure-test-key"))
|
||||
val result = SecurityPolicy.evaluate(
|
||||
settings,
|
||||
clientIp = "192.168.1.10",
|
||||
headers = mapOf("authorization" to "Bearer a-secure-test-key"),
|
||||
)
|
||||
assertEquals(AccessDecision.ALLOWED, result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun missingAndInvalidKeysAreDifferentStableDecisions() {
|
||||
val settings = settings(apiKeyHash = SecurityPolicy.hashApiKey("a-secure-test-key"))
|
||||
assertEquals(AccessDecision.MISSING_CREDENTIALS, SecurityPolicy.evaluate(settings, "127.0.0.1", emptyMap()))
|
||||
assertEquals(
|
||||
AccessDecision.INVALID_CREDENTIALS,
|
||||
SecurityPolicy.evaluate(settings, "127.0.0.1", mapOf("X-API-Key" to "wrong-key")),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun allowlistRejectsAddressBeforeAuthentication() {
|
||||
val settings = settings(
|
||||
apiKeyHash = SecurityPolicy.hashApiKey("a-secure-test-key"),
|
||||
allowlistEnabled = true,
|
||||
allowedIps = setOf("10.0.0.5"),
|
||||
)
|
||||
assertEquals(
|
||||
AccessDecision.IP_DENIED,
|
||||
SecurityPolicy.evaluate(settings, "10.0.0.6", mapOf("X-API-Key" to "a-secure-test-key")),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun hashesDoNotRevealOriginalKey() {
|
||||
val hash = SecurityPolicy.hashApiKey("a-secure-test-key")
|
||||
assertNotEquals("a-secure-test-key", hash)
|
||||
assertEquals(64, hash.length)
|
||||
}
|
||||
|
||||
private fun settings(
|
||||
apiKeyHash: String,
|
||||
allowlistEnabled: Boolean = false,
|
||||
allowedIps: Set<String> = emptySet(),
|
||||
) = GatewaySettings(
|
||||
deviceId = "test-device",
|
||||
port = 8080,
|
||||
bindAddress = "127.0.0.1",
|
||||
serverEnabled = false,
|
||||
startOnBoot = false,
|
||||
authenticationEnabled = true,
|
||||
apiKeyHash = apiKeyHash,
|
||||
allowlistEnabled = allowlistEnabled,
|
||||
allowedIps = allowedIps,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.androidsmsgateway.server
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ApiContractValidationTest {
|
||||
@Test
|
||||
fun phoneValidationAcceptsInternationalAndLocalDigits() {
|
||||
assertTrue(ApiRouter.PHONE_REGEX.matches("+989121234567"))
|
||||
assertTrue(ApiRouter.PHONE_REGEX.matches("09121234567"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun phoneValidationRejectsFormattingAndInjectionCharacters() {
|
||||
assertFalse(ApiRouter.PHONE_REGEX.matches("+98 912 123 4567"))
|
||||
assertFalse(ApiRouter.PHONE_REGEX.matches("+98912;DROP"))
|
||||
assertFalse(ApiRouter.PHONE_REGEX.matches("12"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun requestLimitsRemainBounded() {
|
||||
assertTrue(ApiRouter.MAX_BODY_BYTES <= 16_384)
|
||||
assertEquals(160, ApiRouter.MAX_SMS_CHARACTERS)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.androidsmsgateway.sms
|
||||
|
||||
import android.app.Activity
|
||||
import android.telephony.SmsManager
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SmsStatusReceiverTest {
|
||||
@Test
|
||||
fun `activity result ok is successful`() {
|
||||
assertTrue(SmsStatusReceiver.isSuccessfulResult(Activity.RESULT_OK))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sms manager no error is successful`() {
|
||||
assertTrue(SmsStatusReceiver.isSuccessfulResult(SmsManager.RESULT_ERROR_NONE))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sms manager error is not successful`() {
|
||||
assertFalse(SmsStatusReceiver.isSuccessfulResult(SmsManager.RESULT_ERROR_GENERIC_FAILURE))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user