commit c35b466de6643e023b3219e336c20bf673b93111 Author: Shihaam Abdul Rahman Date: Fri Feb 6 00:38:02 2026 +0500 working api and app diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..aa724b7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/.name b/.idea/.name new file mode 100644 index 0000000..c8cda0f --- /dev/null +++ b/.idea/.name @@ -0,0 +1 @@ +Textpipe \ No newline at end of file diff --git a/.idea/AndroidProjectSystem.xml b/.idea/AndroidProjectSystem.xml new file mode 100644 index 0000000..4a53bee --- /dev/null +++ b/.idea/AndroidProjectSystem.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..b86273d --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/deploymentTargetSelector.xml b/.idea/deploymentTargetSelector.xml new file mode 100644 index 0000000..b268ef3 --- /dev/null +++ b/.idea/deploymentTargetSelector.xml @@ -0,0 +1,10 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..639c779 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..f7608ed --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml new file mode 100644 index 0000000..16660f1 --- /dev/null +++ b/.idea/runConfigurations.xml @@ -0,0 +1,17 @@ + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/PLAN.md b/PLAN.md new file mode 100644 index 0000000..424fde2 --- /dev/null +++ b/PLAN.md @@ -0,0 +1,325 @@ +# Textpipe SMS API Gateway - Implementation Plan + +## Overview + +Build an Android SMS API Gateway with an embedded HTTP server (Ktor), dual SIM support, local message database, and background service. + +--- + +## Architecture + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ MainActivity │ +│ (Compose UI + Permissions) │ +└─────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────┐ +│ TextpipeService │ +│ (Foreground Service + Lifecycle) │ +│ ┌──────────────────────────────────────────────────────────┐ │ +│ │ TextpipeServer (Ktor CIO) │ │ +│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────┐ │ │ +│ │ │ /api/status │ │/api/sms/send│ │/api/sms/messages│ │ │ +│ │ └─────────────┘ └─────────────┘ └─────────────────┘ │ │ +│ └──────────────────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────────────┘ + │ │ │ + ▼ ▼ ▼ +┌─────────────┐ ┌─────────────┐ ┌─────────────────┐ +│ SimManager │ │ SmsSender │ │ SmsRepository │ +│ (API Keys) │ │ (SmsManager)│ │ (Room + Send) │ +└─────────────┘ └─────────────┘ └─────────────────┘ + │ │ + ▼ ▼ + ┌─────────────────────────────────┐ + │ AppDatabase (Room) │ + │ sms_messages table │ + └─────────────────────────────────┘ +``` + +--- + +## Package Structure + +``` +sh.sar.textpipe/ +├── MainActivity.kt (modify) +├── TextpipeApplication.kt (create) +├── data/ +│ ├── db/ +│ │ ├── AppDatabase.kt +│ │ ├── SmsMessageDao.kt +│ │ └── SmsMessageEntity.kt +│ ├── model/ +│ │ └── ApiModels.kt +│ └── repository/ +│ └── SmsRepository.kt +├── server/ +│ ├── TextpipeServer.kt +│ ├── auth/ +│ │ └── ApiKeyAuth.kt +│ └── routes/ +│ ├── SmsRoutes.kt +│ └── StatusRoutes.kt +├── service/ +│ ├── TextpipeService.kt +│ ├── BootReceiver.kt +│ ├── SmsReceiver.kt +│ └── SmsSender.kt +├── sim/ +│ └── SimManager.kt +├── root/ +│ └── RootManager.kt +└── ui/ + ├── MainScreen.kt + └── MainViewModel.kt +``` + +--- + +## API Endpoints + +### Authentication +- API key in header: `Authorization: Bearer ` or `X-API-Key: ` +- Each SIM slot has its own unique API key (auto-generated, persistent) +- API key determines which SIM sends the message + +### Endpoints + +| Method | Path | Auth | Description | +|--------|------|------|-------------| +| GET | `/api/status` | No | Server health, SIM info, uptime | +| POST | `/api/sms/send` | Yes | Send SMS | +| GET | `/api/sms/messages` | Yes | List messages (optional `?type=sent\|received`) | +| GET | `/api/sms/status/{id}` | Yes | Get specific message status | + +### Request/Response Examples + +**POST /api/sms/send** +```json +// Request +{ "to": "+1234567890", "text": "Hello World" } + +// Response +{ "id": 1, "status": "pending", "simSlot": 0 } +``` + +**GET /api/sms/messages** +```json +[ + { + "id": 1, + "type": "sent", + "address": "+1234567890", + "text": "Hello World", + "simSlot": 0, + "status": "delivered", + "timestamp": 1707148800000, + "deliveryTimestamp": 1707148805000 + } +] +``` + +**GET /api/status** +```json +{ + "running": true, + "port": 8080, + "uptime": 3600000, + "sims": [ + { "slot": 0, "carrier": "Carrier1", "number": "+1...", "hasApiKey": true }, + { "slot": 1, "carrier": "Carrier2", "number": "+1...", "hasApiKey": true } + ] +} +``` + +--- + +## Dependencies to Add + +### libs.versions.toml additions + +```toml +[versions] +ktor = "3.0.3" +room = "2.6.1" +kotlinxSerialization = "1.7.3" +datastorePreferences = "1.1.1" +ksp = "2.0.21-1.0.28" +coroutines = "1.9.0" + +[libraries] +ktor-server-core = { group = "io.ktor", name = "ktor-server-core", version.ref = "ktor" } +ktor-server-cio = { group = "io.ktor", name = "ktor-server-cio", version.ref = "ktor" } +ktor-server-content-negotiation = { group = "io.ktor", name = "ktor-server-content-negotiation", version.ref = "ktor" } +ktor-serialization-kotlinx-json = { group = "io.ktor", name = "ktor-serialization-kotlinx-json", version.ref = "ktor" } +ktor-server-status-pages = { group = "io.ktor", name = "ktor-server-status-pages", version.ref = "ktor" } +ktor-server-cors = { group = "io.ktor", name = "ktor-server-cors", version.ref = "ktor" } +room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" } +room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" } +room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" } +kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinxSerialization" } +datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastorePreferences" } +kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" } + +[plugins] +kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } +ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } +``` + +--- + +## Permissions Required + +```xml + + + + + + + + + + + + + + + + + + + + + + + +``` + +--- + +## Implementation Order + +### Phase 0: Build Configuration +1. `gradle/libs.versions.toml` - Add all new dependencies +2. `build.gradle.kts` (root) - Add KSP and serialization plugins +3. `app/build.gradle.kts` - Add dependencies and plugins +4. `AndroidManifest.xml` - Add permissions, services, receivers + +### Phase 1: Data Layer +5. `data/model/ApiModels.kt` - Request/response data classes +6. `data/db/SmsMessageEntity.kt` - Room entity +7. `data/db/SmsMessageDao.kt` - Database operations +8. `data/db/AppDatabase.kt` - Room database + +### Phase 2: Core Managers +9. `sim/SimManager.kt` - SIM detection, API key management +10. `root/RootManager.kt` - Root access and iptables port redirect + +### Phase 3: SMS Operations +11. `service/SmsSender.kt` - Send SMS with delivery tracking +12. `data/repository/SmsRepository.kt` - Combine database + sending +13. `service/SmsReceiver.kt` - Receive incoming SMS + +### Phase 4: HTTP Server +14. `server/auth/ApiKeyAuth.kt` - API key validation +15. `server/routes/StatusRoutes.kt` - Health check endpoint +16. `server/routes/SmsRoutes.kt` - SMS API endpoints +17. `server/TextpipeServer.kt` - Ktor server configuration + +### Phase 5: Service Layer +18. `service/TextpipeService.kt` - Foreground service +19. `service/BootReceiver.kt` - Auto-start on boot +20. `TextpipeApplication.kt` - Application class + +### Phase 6: UI Layer +21. `ui/MainViewModel.kt` - UI state management +22. `ui/MainScreen.kt` - Compose UI +23. `MainActivity.kt` - Update with permissions and new UI + +--- + +## Key Technical Decisions + +### HTTP Server +- **Ktor CIO engine** (not Netty) - lighter weight for Android +- Server runs on configurable port (default 8080) +- For ports 80/443: Use iptables NAT redirect via `su` (don't run JVM as root) + +### Dual SIM Support +- `SubscriptionManager.getActiveSubscriptionInfoList()` for SIM detection +- `SmsManager.createForSubscriptionId(subscriptionId)` for sending +- API key maps to subscription ID, not slot index + +### SMS Delivery Tracking +- PendingIntents for sent confirmation and delivery reports +- Update database status: pending → sent → delivered/failed +- Multipart SMS via `sendMultipartTextMessage()` + +### Background Persistence +- Foreground service with persistent notification +- `FOREGROUND_SERVICE_TYPE_SPECIAL_USE` for API 34+ +- Boot receiver for auto-start + +### API Key Storage +- SharedPreferences (not DataStore) for synchronous reads +- Key format: UUID, stored per SIM slot +- Generated on first run, persistent across app updates + +--- + +## Files to Create/Modify (22 total) + +| # | File | Action | +|---|------|--------| +| 1 | `gradle/libs.versions.toml` | Modify | +| 2 | `build.gradle.kts` (root) | Modify | +| 3 | `app/build.gradle.kts` | Modify | +| 4 | `app/src/main/AndroidManifest.xml` | Modify | +| 5 | `data/model/ApiModels.kt` | Create | +| 6 | `data/db/SmsMessageEntity.kt` | Create | +| 7 | `data/db/SmsMessageDao.kt` | Create | +| 8 | `data/db/AppDatabase.kt` | Create | +| 9 | `sim/SimManager.kt` | Create | +| 10 | `root/RootManager.kt` | Create | +| 11 | `service/SmsSender.kt` | Create | +| 12 | `data/repository/SmsRepository.kt` | Create | +| 13 | `service/SmsReceiver.kt` | Create | +| 14 | `server/auth/ApiKeyAuth.kt` | Create | +| 15 | `server/routes/StatusRoutes.kt` | Create | +| 16 | `server/routes/SmsRoutes.kt` | Create | +| 17 | `server/TextpipeServer.kt` | Create | +| 18 | `service/TextpipeService.kt` | Create | +| 19 | `service/BootReceiver.kt` | Create | +| 20 | `TextpipeApplication.kt` | Create | +| 21 | `ui/MainViewModel.kt` | Create | +| 22 | `ui/MainScreen.kt` | Create | +| 23 | `MainActivity.kt` | Modify | + +--- + +## UI Features (Basic for now) + +- Server status indicator (Running/Stopped) +- Port configuration input +- Start/Stop toggle button +- SIM cards list with: + - Carrier name + - Phone number (if available) + - API key with copy button +- Root port redirect toggle (if root available) +- Battery optimization exemption button + +--- + +## Out of Scope (Deferred) + +- WebUI for viewing messages in browser +- Rate limiting +- IP whitelisting +- HTTPS/TLS (beyond port redirect) +- Message scheduling +- Webhook callbacks diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..b4ef00d --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,85 @@ +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.compose) + alias(libs.plugins.kotlin.serialization) + alias(libs.plugins.ksp) +} + +android { + namespace = "sh.sar.textpipe" + compileSdk { + version = release(36) + } + + defaultConfig { + applicationId = "sh.sar.textpipe" + minSdk = 24 + targetSdk = 36 + versionCode = 1 + versionName = "1.0" + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + buildFeatures { + compose = true + } + + ksp { + arg("room.schemaLocation", "$projectDir/schemas") + } +} + +dependencies { + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.lifecycle.runtime.ktx) + implementation(libs.androidx.activity.compose) + implementation(platform(libs.androidx.compose.bom)) + implementation(libs.androidx.compose.ui) + implementation(libs.androidx.compose.ui.graphics) + implementation(libs.androidx.compose.ui.tooling.preview) + implementation(libs.androidx.compose.material3) + + // Ktor server + implementation(libs.ktor.server.core) + implementation(libs.ktor.server.cio) + implementation(libs.ktor.server.content.negotiation) + implementation(libs.ktor.serialization.kotlinx.json) + implementation(libs.ktor.server.status.pages) + implementation(libs.ktor.server.cors) + + // Room + implementation(libs.room.runtime) + implementation(libs.room.ktx) + ksp(libs.room.compiler) + + // Serialization + implementation(libs.kotlinx.serialization.json) + + // DataStore + implementation(libs.datastore.preferences) + + // Coroutines + implementation(libs.kotlinx.coroutines.android) + + testImplementation(libs.junit) + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.espresso.core) + androidTestImplementation(platform(libs.androidx.compose.bom)) + androidTestImplementation(libs.androidx.compose.ui.test.junit4) + debugImplementation(libs.androidx.compose.ui.tooling) + debugImplementation(libs.androidx.compose.ui.test.manifest) +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/app/schemas/sh.sar.textpipe.data.db.AppDatabase/1.json b/app/schemas/sh.sar.textpipe.data.db.AppDatabase/1.json new file mode 100644 index 0000000..2839239 --- /dev/null +++ b/app/schemas/sh.sar.textpipe.data.db.AppDatabase/1.json @@ -0,0 +1,72 @@ +{ + "formatVersion": 1, + "database": { + "version": 1, + "identityHash": "e36efa26de5bbbd1ccb4beacc9470fcd", + "entities": [ + { + "tableName": "sms_messages", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `type` TEXT NOT NULL, `address` TEXT NOT NULL, `text` TEXT NOT NULL, `simSlot` INTEGER NOT NULL, `status` TEXT NOT NULL, `timestamp` INTEGER NOT NULL, `deliveryTimestamp` INTEGER)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "address", + "columnName": "address", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "text", + "columnName": "text", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "simSlot", + "columnName": "simSlot", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deliveryTimestamp", + "columnName": "deliveryTimestamp", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "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, 'e36efa26de5bbbd1ccb4beacc9470fcd')" + ] + } +} \ No newline at end of file diff --git a/app/src/androidTest/java/sh/sar/textpipe/ExampleInstrumentedTest.kt b/app/src/androidTest/java/sh/sar/textpipe/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..dc782ff --- /dev/null +++ b/app/src/androidTest/java/sh/sar/textpipe/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package sh.sar.textpipe + +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("sh.sar.textpipe", appContext.packageName) + } +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..35268ef --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,84 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/java/sh/sar/textpipe/MainActivity.kt b/app/src/main/java/sh/sar/textpipe/MainActivity.kt new file mode 100644 index 0000000..1fd0eb5 --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/MainActivity.kt @@ -0,0 +1,71 @@ +package sh.sar.textpipe + +import android.Manifest +import android.content.pm.PackageManager +import android.os.Build +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.activity.result.contract.ActivityResultContracts +import androidx.activity.viewModels +import androidx.core.content.ContextCompat +import sh.sar.textpipe.ui.MainScreen +import sh.sar.textpipe.ui.MainViewModel +import sh.sar.textpipe.ui.theme.TextpipeTheme + +class MainActivity : ComponentActivity() { + + private val viewModel: MainViewModel by viewModels() + + private val requiredPermissions = buildList { + add(Manifest.permission.SEND_SMS) + add(Manifest.permission.RECEIVE_SMS) + add(Manifest.permission.READ_SMS) + add(Manifest.permission.READ_PHONE_STATE) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + add(Manifest.permission.READ_PHONE_NUMBERS) + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + add(Manifest.permission.POST_NOTIFICATIONS) + } + }.toTypedArray() + + private val permissionLauncher = registerForActivityResult( + ActivityResultContracts.RequestMultiplePermissions() + ) { permissions -> + val allGranted = permissions.values.all { it } + if (allGranted) { + viewModel.refreshSimInfo() + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + + requestPermissionsIfNeeded() + + setContent { + TextpipeTheme { + MainScreen(viewModel = viewModel) + } + } + } + + override fun onResume() { + super.onResume() + viewModel.refreshBatteryOptimizationStatus() + viewModel.refreshSimInfo() + } + + private fun requestPermissionsIfNeeded() { + val permissionsToRequest = requiredPermissions.filter { + ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED + }.toTypedArray() + + if (permissionsToRequest.isNotEmpty()) { + permissionLauncher.launch(permissionsToRequest) + } + } +} diff --git a/app/src/main/java/sh/sar/textpipe/TextpipeApplication.kt b/app/src/main/java/sh/sar/textpipe/TextpipeApplication.kt new file mode 100644 index 0000000..7f9bfcc --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/TextpipeApplication.kt @@ -0,0 +1,42 @@ +package sh.sar.textpipe + +import android.app.Application +import android.util.Log +import sh.sar.textpipe.data.db.AppDatabase +import sh.sar.textpipe.sim.SimManager +import java.net.BindException + +class TextpipeApplication : Application() { + + companion object { + private const val TAG = "TextpipeApplication" + } + + lateinit var database: AppDatabase + private set + + lateinit var simManager: SimManager + private set + + private var defaultHandler: Thread.UncaughtExceptionHandler? = null + + override fun onCreate() { + super.onCreate() + database = AppDatabase.getInstance(this) + simManager = SimManager(this) + + // Set up global uncaught exception handler to prevent crashes from Ktor binding issues + defaultHandler = Thread.getDefaultUncaughtExceptionHandler() + Thread.setDefaultUncaughtExceptionHandler { thread, throwable -> + if (throwable is BindException || + (throwable.cause is BindException) || + throwable.message?.contains("Address already in use") == true) { + // Log but don't crash for bind exceptions + Log.e(TAG, "Caught BindException in thread ${thread.name}, ignoring to prevent crash", throwable) + } else { + // For other exceptions, use the default handler + defaultHandler?.uncaughtException(thread, throwable) + } + } + } +} diff --git a/app/src/main/java/sh/sar/textpipe/data/db/AppDatabase.kt b/app/src/main/java/sh/sar/textpipe/data/db/AppDatabase.kt new file mode 100644 index 0000000..054412c --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/data/db/AppDatabase.kt @@ -0,0 +1,26 @@ +package sh.sar.textpipe.data.db + +import android.content.Context +import androidx.room.Database +import androidx.room.Room +import androidx.room.RoomDatabase + +@Database(entities = [SmsMessageEntity::class], version = 1, exportSchema = true) +abstract class AppDatabase : RoomDatabase() { + abstract fun smsMessageDao(): SmsMessageDao + + companion object { + @Volatile + private var INSTANCE: AppDatabase? = null + + fun getInstance(context: Context): AppDatabase { + return INSTANCE ?: synchronized(this) { + INSTANCE ?: Room.databaseBuilder( + context.applicationContext, + AppDatabase::class.java, + "textpipe.db" + ).build().also { INSTANCE = it } + } + } + } +} diff --git a/app/src/main/java/sh/sar/textpipe/data/db/SmsMessageDao.kt b/app/src/main/java/sh/sar/textpipe/data/db/SmsMessageDao.kt new file mode 100644 index 0000000..ed4262c --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/data/db/SmsMessageDao.kt @@ -0,0 +1,36 @@ +package sh.sar.textpipe.data.db + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.Query +import androidx.room.Update + +@Dao +interface SmsMessageDao { + @Insert + suspend fun insert(message: SmsMessageEntity): Long + + @Update + suspend fun update(message: SmsMessageEntity) + + @Query("SELECT * FROM sms_messages ORDER BY timestamp DESC") + suspend fun getAll(): List + + @Query("SELECT * FROM sms_messages WHERE type = :type ORDER BY timestamp DESC") + suspend fun getByType(type: String): List + + @Query("SELECT * FROM sms_messages WHERE id = :id") + suspend fun getById(id: Long): SmsMessageEntity? + + @Query("UPDATE sms_messages SET status = :status, deliveryTimestamp = :deliveryTimestamp WHERE id = :id") + suspend fun updateStatus(id: Long, status: String, deliveryTimestamp: Long? = null) + + @Query("SELECT * FROM sms_messages WHERE address = :address ORDER BY timestamp DESC") + suspend fun getByAddress(address: String): List + + @Query("SELECT COUNT(*) FROM sms_messages") + suspend fun getCount(): Int + + @Query("SELECT COUNT(*) FROM sms_messages WHERE type = :type") + suspend fun getCountByType(type: String): Int +} diff --git a/app/src/main/java/sh/sar/textpipe/data/db/SmsMessageEntity.kt b/app/src/main/java/sh/sar/textpipe/data/db/SmsMessageEntity.kt new file mode 100644 index 0000000..263ff85 --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/data/db/SmsMessageEntity.kt @@ -0,0 +1,17 @@ +package sh.sar.textpipe.data.db + +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity(tableName = "sms_messages") +data class SmsMessageEntity( + @PrimaryKey(autoGenerate = true) + val id: Long = 0, + val type: String, // "sent" or "received" + val address: String, // phone number (to or from) + val text: String, + val simSlot: Int, + val status: String, // "pending", "sent", "delivered", "failed" + val timestamp: Long, // epoch millis, when created/received + val deliveryTimestamp: Long? = null // epoch millis, when delivered +) diff --git a/app/src/main/java/sh/sar/textpipe/data/model/ApiModels.kt b/app/src/main/java/sh/sar/textpipe/data/model/ApiModels.kt new file mode 100644 index 0000000..bd46815 --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/data/model/ApiModels.kt @@ -0,0 +1,55 @@ +package sh.sar.textpipe.data.model + +import kotlinx.serialization.Serializable + +@Serializable +data class SendSmsRequest( + val to: String, + val text: String +) + +@Serializable +data class SendSmsResponse( + val id: Long, + val status: String, + val simSlot: Int +) + +@Serializable +data class SmsMessageResponse( + val id: Long, + val type: String, + val address: String, + val text: String, + val simSlot: Int, + val status: String, + val timestamp: Long, + val deliveryTimestamp: Long? +) + +@Serializable +data class StatusResponse( + val running: Boolean, + val port: Int, + val uptime: Long, + val sims: List +) + +@Serializable +data class SimInfo( + val slot: Int, + val carrier: String?, + val number: String?, + val hasApiKey: Boolean +) + +@Serializable +data class ErrorResponse( + val error: String +) + +@Serializable +data class MessagesResponse( + val messages: List, + val total: Int +) diff --git a/app/src/main/java/sh/sar/textpipe/data/repository/SmsRepository.kt b/app/src/main/java/sh/sar/textpipe/data/repository/SmsRepository.kt new file mode 100644 index 0000000..e41a086 --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/data/repository/SmsRepository.kt @@ -0,0 +1,71 @@ +package sh.sar.textpipe.data.repository + +import sh.sar.textpipe.data.db.SmsMessageDao +import sh.sar.textpipe.data.db.SmsMessageEntity +import sh.sar.textpipe.data.model.SendSmsResponse +import sh.sar.textpipe.data.model.SmsMessageResponse +import sh.sar.textpipe.service.SmsSender +import sh.sar.textpipe.sim.SimManager + +class SmsRepository( + private val dao: SmsMessageDao, + private val smsSender: SmsSender, + private val simManager: SimManager +) { + suspend fun sendSms(to: String, text: String, apiKey: String): SendSmsResponse? { + val subscriptionId = simManager.getSubscriptionIdForApiKey(apiKey) ?: return null + val simSlot = simManager.getSimSlotForApiKey(apiKey) ?: return null + + val messageId = smsSender.send(to, text, subscriptionId, simSlot) + + return SendSmsResponse( + id = messageId, + status = "pending", + simSlot = simSlot + ) + } + + suspend fun getAllMessages(type: String? = null): List { + val messages = if (type != null) { + dao.getByType(type) + } else { + dao.getAll() + } + return messages.map { it.toResponse() } + } + + suspend fun getMessageById(id: Long): SmsMessageResponse? { + return dao.getById(id)?.toResponse() + } + + suspend fun insertReceivedSms(from: String, text: String, simSlot: Int): Long { + val message = SmsMessageEntity( + type = "received", + address = from, + text = text, + simSlot = simSlot, + status = "received", + timestamp = System.currentTimeMillis() + ) + return dao.insert(message) + } + + suspend fun getMessageCount(type: String? = null): Int { + return if (type != null) { + dao.getCountByType(type) + } else { + dao.getCount() + } + } + + private fun SmsMessageEntity.toResponse() = SmsMessageResponse( + id = id, + type = type, + address = address, + text = text, + simSlot = simSlot, + status = status, + timestamp = timestamp, + deliveryTimestamp = deliveryTimestamp + ) +} diff --git a/app/src/main/java/sh/sar/textpipe/root/RootManager.kt b/app/src/main/java/sh/sar/textpipe/root/RootManager.kt new file mode 100644 index 0000000..880db9c --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/root/RootManager.kt @@ -0,0 +1,101 @@ +package sh.sar.textpipe.root + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull +import java.io.BufferedReader +import java.io.InputStreamReader +import java.util.concurrent.TimeUnit + +object RootManager { + + suspend fun isRootAvailable(): Boolean = withContext(Dispatchers.IO) { + withTimeoutOrNull(3000L) { + try { + val process = Runtime.getRuntime().exec(arrayOf("su", "-c", "id")) + val completed = process.waitFor(2, TimeUnit.SECONDS) + if (completed) { + process.exitValue() == 0 + } else { + process.destroyForcibly() + false + } + } catch (e: Exception) { + false + } + } ?: false + } + + suspend fun setupPortRedirect(fromPort: Int, toPort: Int): Boolean = withContext(Dispatchers.IO) { + withTimeoutOrNull(5000L) { + try { + val command = "iptables -t nat -A PREROUTING -p tcp --dport $fromPort -j REDIRECT --to-port $toPort" + val process = Runtime.getRuntime().exec(arrayOf("su", "-c", command)) + val completed = process.waitFor(4, TimeUnit.SECONDS) + if (completed) { + process.exitValue() == 0 + } else { + process.destroyForcibly() + false + } + } catch (e: Exception) { + false + } + } ?: false + } + + suspend fun clearPortRedirect(fromPort: Int, toPort: Int): Boolean = withContext(Dispatchers.IO) { + withTimeoutOrNull(5000L) { + try { + val command = "iptables -t nat -D PREROUTING -p tcp --dport $fromPort -j REDIRECT --to-port $toPort" + val process = Runtime.getRuntime().exec(arrayOf("su", "-c", command)) + val completed = process.waitFor(4, TimeUnit.SECONDS) + if (completed) { + process.exitValue() == 0 + } else { + process.destroyForcibly() + false + } + } catch (e: Exception) { + false + } + } ?: false + } + + suspend fun clearAllRedirects(): Boolean = withContext(Dispatchers.IO) { + withTimeoutOrNull(5000L) { + try { + val command = "iptables -t nat -F PREROUTING" + val process = Runtime.getRuntime().exec(arrayOf("su", "-c", command)) + val completed = process.waitFor(4, TimeUnit.SECONDS) + if (completed) { + process.exitValue() == 0 + } else { + process.destroyForcibly() + false + } + } catch (e: Exception) { + false + } + } ?: false + } + + suspend fun executeCommand(command: String): Pair = withContext(Dispatchers.IO) { + withTimeoutOrNull(10000L) { + try { + val process = Runtime.getRuntime().exec(arrayOf("su", "-c", command)) + val reader = BufferedReader(InputStreamReader(process.inputStream)) + val output = reader.readText() + val completed = process.waitFor(8, TimeUnit.SECONDS) + if (completed) { + Pair(process.exitValue() == 0, output) + } else { + process.destroyForcibly() + Pair(false, "Timeout") + } + } catch (e: Exception) { + Pair(false, e.message ?: "Unknown error") + } + } ?: Pair(false, "Timeout") + } +} diff --git a/app/src/main/java/sh/sar/textpipe/server/TextpipeServer.kt b/app/src/main/java/sh/sar/textpipe/server/TextpipeServer.kt new file mode 100644 index 0000000..0bfd407 --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/server/TextpipeServer.kt @@ -0,0 +1,167 @@ +package sh.sar.textpipe.server + +import android.util.Log +import io.ktor.http.* +import io.ktor.serialization.kotlinx.json.* +import io.ktor.server.application.* +import io.ktor.server.cio.* +import io.ktor.server.engine.* +import io.ktor.server.plugins.contentnegotiation.* +import io.ktor.server.plugins.cors.routing.* +import io.ktor.server.plugins.statuspages.* +import io.ktor.server.response.* +import io.ktor.server.routing.* +import kotlinx.coroutines.CoroutineExceptionHandler +import kotlinx.coroutines.delay +import kotlinx.coroutines.withTimeoutOrNull +import kotlinx.serialization.json.Json +import sh.sar.textpipe.data.model.ErrorResponse +import sh.sar.textpipe.data.repository.SmsRepository +import sh.sar.textpipe.server.auth.configureAuth +import sh.sar.textpipe.server.routes.smsRoutes +import sh.sar.textpipe.server.routes.statusRoutes +import sh.sar.textpipe.sim.SimManager +import java.net.BindException +import java.net.ServerSocket + +class TextpipeServer( + private val smsRepository: SmsRepository, + private val simManager: SimManager +) { + companion object { + private const val TAG = "TextpipeServer" + } + + private var server: EmbeddedServer? = null + private var startTime: Long = 0 + private var currentPort: Int = 8080 + @Volatile + private var lastError: Throwable? = null + + suspend fun start(port: Int): Boolean { + // Stop any existing server first + stop() + + // Wait a bit for port to be released + delay(300) + + // Check if port is available before trying to bind + if (!isPortAvailable(port)) { + Log.e(TAG, "Port $port is not available") + // Try waiting longer + delay(1000) + if (!isPortAvailable(port)) { + Log.e(TAG, "Port $port still not available after waiting") + return false + } + } + + currentPort = port + startTime = System.currentTimeMillis() + lastError = null + + return try { + val exceptionHandler = CoroutineExceptionHandler { _, throwable -> + Log.e(TAG, "Server coroutine exception", throwable) + lastError = throwable + } + + server = embeddedServer(CIO, port = port) { + configurePlugins() + configureAuth(simManager) + configureRouting() + } + + server?.start(wait = false) + + // Wait a bit and check if server actually started + delay(500) + + if (lastError != null) { + Log.e(TAG, "Server failed to start", lastError) + server?.stop(100, 100) + server = null + return false + } + + // Verify server is actually running by checking the port again + if (isPortAvailable(port)) { + // Port is still available means server didn't bind + Log.e(TAG, "Server didn't bind to port $port") + server?.stop(100, 100) + server = null + return false + } + + Log.i(TAG, "Server started on port $port") + true + } catch (e: Exception) { + Log.e(TAG, "Failed to start server on port $port", e) + server?.stop(100, 100) + server = null + false + } + } + + private fun isPortAvailable(port: Int): Boolean { + return try { + ServerSocket(port).use { true } + } catch (e: Exception) { + false + } + } + + private fun Application.configurePlugins() { + install(ContentNegotiation) { + json(Json { + prettyPrint = true + isLenient = true + ignoreUnknownKeys = true + }) + } + + install(StatusPages) { + exception { call, cause -> + Log.e(TAG, "Request error", cause) + call.respond( + HttpStatusCode.InternalServerError, + ErrorResponse("Internal server error: ${cause.message}") + ) + } + } + + install(CORS) { + anyHost() + allowHeader(HttpHeaders.ContentType) + allowHeader(HttpHeaders.Authorization) + allowHeader("X-API-Key") + allowMethod(HttpMethod.Get) + allowMethod(HttpMethod.Post) + allowMethod(HttpMethod.Options) + } + } + + private fun Application.configureRouting() { + routing { + statusRoutes(simManager, { startTime }, { currentPort }) + smsRoutes(smsRepository) + } + } + + fun stop() { + try { + server?.stop(1000, 3000) + Log.i(TAG, "Server stopped") + } catch (e: Exception) { + Log.e(TAG, "Error stopping server", e) + } finally { + server = null + } + } + + fun isRunning(): Boolean = server != null + + fun getPort(): Int = currentPort + + fun getStartTime(): Long = startTime +} diff --git a/app/src/main/java/sh/sar/textpipe/server/auth/ApiKeyAuth.kt b/app/src/main/java/sh/sar/textpipe/server/auth/ApiKeyAuth.kt new file mode 100644 index 0000000..e4e6521 --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/server/auth/ApiKeyAuth.kt @@ -0,0 +1,78 @@ +package sh.sar.textpipe.server.auth + +import io.ktor.http.* +import io.ktor.server.application.* +import io.ktor.server.response.* +import io.ktor.util.* +import sh.sar.textpipe.data.model.ErrorResponse +import sh.sar.textpipe.sim.SimManager + +val ApiKeyAttributeKey = AttributeKey("ApiKey") +val SimSlotAttributeKey = AttributeKey("SimSlot") +val SubscriptionIdAttributeKey = AttributeKey("SubscriptionId") + +fun Application.configureAuth(simManager: SimManager) { + intercept(ApplicationCallPipeline.Plugins) { + val path = call.request.local.uri + + // Skip auth for status endpoint + if (path == "/api/status" || path == "/") { + return@intercept + } + + // Only require auth for /api/sms/* endpoints + if (!path.startsWith("/api/sms")) { + return@intercept + } + + val apiKey = extractApiKey(call) + + if (apiKey == null) { + call.respond(HttpStatusCode.Unauthorized, ErrorResponse("Missing API key")) + finish() + return@intercept + } + + if (!simManager.isValidApiKey(apiKey)) { + call.respond(HttpStatusCode.Unauthorized, ErrorResponse("Invalid API key")) + finish() + return@intercept + } + + val subscriptionId = simManager.getSubscriptionIdForApiKey(apiKey) + val simSlot = simManager.getSimSlotForApiKey(apiKey) + + if (subscriptionId == null || simSlot == null) { + call.respond(HttpStatusCode.Unauthorized, ErrorResponse("SIM not available for this API key")) + finish() + return@intercept + } + + // Store auth info in call attributes for route handlers + call.attributes.put(ApiKeyAttributeKey, apiKey) + call.attributes.put(SimSlotAttributeKey, simSlot) + call.attributes.put(SubscriptionIdAttributeKey, subscriptionId) + } +} + +private fun extractApiKey(call: ApplicationCall): String? { + // Try Authorization: Bearer + val authHeader = call.request.headers["Authorization"] + if (authHeader != null && authHeader.startsWith("Bearer ", ignoreCase = true)) { + return authHeader.substring(7).trim() + } + + // Try X-API-Key header + val xApiKey = call.request.headers["X-API-Key"] + if (xApiKey != null) { + return xApiKey.trim() + } + + // Try query parameter as fallback + val queryKey = call.request.queryParameters["api_key"] + if (queryKey != null) { + return queryKey.trim() + } + + return null +} diff --git a/app/src/main/java/sh/sar/textpipe/server/routes/SmsRoutes.kt b/app/src/main/java/sh/sar/textpipe/server/routes/SmsRoutes.kt new file mode 100644 index 0000000..7e4ec69 --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/server/routes/SmsRoutes.kt @@ -0,0 +1,81 @@ +package sh.sar.textpipe.server.routes + +import io.ktor.http.* +import io.ktor.server.request.* +import io.ktor.server.response.* +import io.ktor.server.routing.* +import sh.sar.textpipe.data.model.ErrorResponse +import sh.sar.textpipe.data.model.MessagesResponse +import sh.sar.textpipe.data.model.SendSmsRequest +import sh.sar.textpipe.data.repository.SmsRepository +import sh.sar.textpipe.server.auth.ApiKeyAttributeKey + +fun Route.smsRoutes(smsRepository: SmsRepository) { + post("/api/sms/send") { + val apiKey = call.attributes.getOrNull(ApiKeyAttributeKey) + if (apiKey == null) { + call.respond(HttpStatusCode.Unauthorized, ErrorResponse("Missing API key")) + return@post + } + + val request = try { + call.receive() + } catch (e: Exception) { + call.respond(HttpStatusCode.BadRequest, ErrorResponse("Invalid request body: ${e.message}")) + return@post + } + + // Validate request + if (request.to.isBlank()) { + call.respond(HttpStatusCode.BadRequest, ErrorResponse("'to' field is required")) + return@post + } + if (request.text.isBlank()) { + call.respond(HttpStatusCode.BadRequest, ErrorResponse("'text' field is required")) + return@post + } + + val response = smsRepository.sendSms(request.to, request.text, apiKey) + if (response == null) { + call.respond(HttpStatusCode.InternalServerError, ErrorResponse("Failed to send SMS")) + return@post + } + + call.respond(HttpStatusCode.OK, response) + } + + get("/api/sms/messages") { + val type = call.request.queryParameters["type"] + + // Validate type if provided + if (type != null && type !in listOf("sent", "received")) { + call.respond(HttpStatusCode.BadRequest, ErrorResponse("Invalid type. Must be 'sent' or 'received'")) + return@get + } + + val messages = smsRepository.getAllMessages(type) + val response = MessagesResponse( + messages = messages, + total = messages.size + ) + call.respond(response) + } + + get("/api/sms/status/{id}") { + val idParam = call.parameters["id"] + val id = idParam?.toLongOrNull() + + if (id == null) { + call.respond(HttpStatusCode.BadRequest, ErrorResponse("Invalid message ID")) + return@get + } + + val message = smsRepository.getMessageById(id) + if (message == null) { + call.respond(HttpStatusCode.NotFound, ErrorResponse("Message not found")) + return@get + } + + call.respond(message) + } +} diff --git a/app/src/main/java/sh/sar/textpipe/server/routes/StatusRoutes.kt b/app/src/main/java/sh/sar/textpipe/server/routes/StatusRoutes.kt new file mode 100644 index 0000000..5b292c4 --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/server/routes/StatusRoutes.kt @@ -0,0 +1,23 @@ +package sh.sar.textpipe.server.routes + +import io.ktor.server.response.* +import io.ktor.server.routing.* +import sh.sar.textpipe.data.model.StatusResponse +import sh.sar.textpipe.sim.SimManager + +fun Route.statusRoutes(simManager: SimManager, getStartTime: () -> Long, getPort: () -> Int) { + get("/") { + call.respondText("Textpipe SMS Gateway API") + } + + get("/api/status") { + val uptime = System.currentTimeMillis() - getStartTime() + val response = StatusResponse( + running = true, + port = getPort(), + uptime = uptime, + sims = simManager.getSimInfoList() + ) + call.respond(response) + } +} diff --git a/app/src/main/java/sh/sar/textpipe/service/BootReceiver.kt b/app/src/main/java/sh/sar/textpipe/service/BootReceiver.kt new file mode 100644 index 0000000..25c1d36 --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/service/BootReceiver.kt @@ -0,0 +1,31 @@ +package sh.sar.textpipe.service + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent + +class BootReceiver : BroadcastReceiver() { + + companion object { + private const val PREFS_NAME = "textpipe_settings" + private const val KEY_AUTO_START = "auto_start" + + fun isAutoStartEnabled(context: Context): Boolean { + val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + return prefs.getBoolean(KEY_AUTO_START, true) + } + + fun setAutoStartEnabled(context: Context, enabled: Boolean) { + val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + prefs.edit().putBoolean(KEY_AUTO_START, enabled).apply() + } + } + + override fun onReceive(context: Context, intent: Intent) { + if (intent.action != Intent.ACTION_BOOT_COMPLETED) return + + if (isAutoStartEnabled(context)) { + TextpipeService.start(context) + } + } +} diff --git a/app/src/main/java/sh/sar/textpipe/service/SmsReceiver.kt b/app/src/main/java/sh/sar/textpipe/service/SmsReceiver.kt new file mode 100644 index 0000000..077f046 --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/service/SmsReceiver.kt @@ -0,0 +1,94 @@ +package sh.sar.textpipe.service + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.os.Build +import android.provider.Telephony +import android.telephony.SubscriptionManager +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import sh.sar.textpipe.data.db.AppDatabase +import sh.sar.textpipe.data.db.SmsMessageEntity + +class SmsReceiver : BroadcastReceiver() { + + override fun onReceive(context: Context, intent: Intent) { + if (intent.action != Telephony.Sms.Intents.SMS_RECEIVED_ACTION) return + + val pendingResult = goAsync() + val scope = CoroutineScope(Dispatchers.IO) + + scope.launch { + try { + val messages = Telephony.Sms.Intents.getMessagesFromIntent(intent) + if (messages.isNullOrEmpty()) { + pendingResult.finish() + return@launch + } + + // Get SIM slot from intent extras + val simSlot = getSimSlot(intent) + + // Combine message parts (multipart SMS) + val from = messages[0].displayOriginatingAddress ?: messages[0].originatingAddress ?: "Unknown" + val fullText = messages.joinToString("") { it.displayMessageBody ?: it.messageBody ?: "" } + + // Insert into database + val dao = AppDatabase.getInstance(context).smsMessageDao() + val entity = SmsMessageEntity( + type = "received", + address = from, + text = fullText, + simSlot = simSlot, + status = "received", + timestamp = System.currentTimeMillis() + ) + dao.insert(entity) + + } catch (e: Exception) { + e.printStackTrace() + } finally { + pendingResult.finish() + } + } + } + + private fun getSimSlot(intent: Intent): Int { + // Different OEMs use different extra names + val extras = intent.extras ?: return 0 + + // Try common extra names for SIM slot + val slotKeys = listOf("slot", "simId", "simSlot", "phone", "subscription") + for (key in slotKeys) { + if (extras.containsKey(key)) { + val value = extras.getInt(key, -1) + if (value >= 0) return value + } + } + + // Try to get subscription ID and convert to slot + val subscriptionId = extras.getInt("subscription", -1) + if (subscriptionId >= 0) { + return getSlotFromSubscriptionId(intent, subscriptionId) + } + + return 0 + } + + private fun getSlotFromSubscriptionId(intent: Intent, subscriptionId: Int): Int { + return try { + val context = intent.extras?.get("android.intent.extra.PHONE") as? Context + ?: return 0 + val subscriptionManager = context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as? SubscriptionManager + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + subscriptionManager?.getActiveSubscriptionInfo(subscriptionId)?.simSlotIndex ?: 0 + } else { + 0 + } + } catch (e: Exception) { + 0 + } + } +} diff --git a/app/src/main/java/sh/sar/textpipe/service/SmsSender.kt b/app/src/main/java/sh/sar/textpipe/service/SmsSender.kt new file mode 100644 index 0000000..9427e88 --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/service/SmsSender.kt @@ -0,0 +1,154 @@ +package sh.sar.textpipe.service + +import android.app.PendingIntent +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.os.Build +import android.telephony.SmsManager +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import sh.sar.textpipe.data.db.SmsMessageDao +import sh.sar.textpipe.data.db.SmsMessageEntity + +class SmsSender( + private val context: Context, + private val dao: SmsMessageDao +) { + companion object { + private const val ACTION_SMS_SENT = "sh.sar.textpipe.SMS_SENT" + private const val ACTION_SMS_DELIVERED = "sh.sar.textpipe.SMS_DELIVERED" + private const val EXTRA_MESSAGE_ID = "message_id" + } + + private val scope = CoroutineScope(Dispatchers.IO) + + private val sentReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + val messageId = intent.getLongExtra(EXTRA_MESSAGE_ID, -1) + if (messageId == -1L) return + + val status = when (resultCode) { + android.app.Activity.RESULT_OK -> "sent" + SmsManager.RESULT_ERROR_GENERIC_FAILURE -> "failed" + SmsManager.RESULT_ERROR_NO_SERVICE -> "failed" + SmsManager.RESULT_ERROR_NULL_PDU -> "failed" + SmsManager.RESULT_ERROR_RADIO_OFF -> "failed" + else -> "failed" + } + + scope.launch { + dao.updateStatus(messageId, status) + } + } + } + + private val deliveryReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + val messageId = intent.getLongExtra(EXTRA_MESSAGE_ID, -1) + if (messageId == -1L) return + + scope.launch { + dao.updateStatus(messageId, "delivered", System.currentTimeMillis()) + } + } + } + + private var isRegistered = false + + fun register() { + if (isRegistered) return + + val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + Context.RECEIVER_NOT_EXPORTED + } else { + 0 + } + + context.registerReceiver(sentReceiver, IntentFilter(ACTION_SMS_SENT), flags) + context.registerReceiver(deliveryReceiver, IntentFilter(ACTION_SMS_DELIVERED), flags) + isRegistered = true + } + + fun unregister() { + if (!isRegistered) return + + try { + context.unregisterReceiver(sentReceiver) + context.unregisterReceiver(deliveryReceiver) + } catch (e: Exception) { + // Ignore if not registered + } + isRegistered = false + } + + suspend fun send(to: String, text: String, subscriptionId: Int, simSlot: Int): Long { + // Insert pending message into database + val message = SmsMessageEntity( + type = "sent", + address = to, + text = text, + simSlot = simSlot, + status = "pending", + timestamp = System.currentTimeMillis() + ) + val messageId = dao.insert(message) + + // Get SmsManager for specific subscription + val smsManager = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + context.getSystemService(SmsManager::class.java).createForSubscriptionId(subscriptionId) + } else { + @Suppress("DEPRECATION") + SmsManager.getSmsManagerForSubscriptionId(subscriptionId) + } + + // Create PendingIntents + val sentIntent = createPendingIntent(ACTION_SMS_SENT, messageId) + val deliveryIntent = createPendingIntent(ACTION_SMS_DELIVERED, messageId) + + // Check if message needs to be split + val parts = smsManager.divideMessage(text) + + if (parts.size == 1) { + smsManager.sendTextMessage( + to, + null, + text, + sentIntent, + deliveryIntent + ) + } else { + val sentIntents = ArrayList() + val deliveryIntents = ArrayList() + repeat(parts.size) { + sentIntents.add(createPendingIntent(ACTION_SMS_SENT, messageId)) + deliveryIntents.add(createPendingIntent(ACTION_SMS_DELIVERED, messageId)) + } + smsManager.sendMultipartTextMessage( + to, + null, + parts, + sentIntents, + deliveryIntents + ) + } + + return messageId + } + + private fun createPendingIntent(action: String, messageId: Long): PendingIntent { + val intent = Intent(action).apply { + putExtra(EXTRA_MESSAGE_ID, messageId) + setPackage(context.packageName) + } + val flags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + return PendingIntent.getBroadcast( + context, + messageId.toInt(), + intent, + flags + ) + } +} diff --git a/app/src/main/java/sh/sar/textpipe/service/TextpipeService.kt b/app/src/main/java/sh/sar/textpipe/service/TextpipeService.kt new file mode 100644 index 0000000..fa6df48 --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/service/TextpipeService.kt @@ -0,0 +1,220 @@ +package sh.sar.textpipe.service + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.os.Build +import android.os.IBinder +import android.util.Log +import androidx.core.app.NotificationCompat +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import sh.sar.textpipe.MainActivity +import sh.sar.textpipe.TextpipeApplication +import sh.sar.textpipe.data.repository.SmsRepository +import sh.sar.textpipe.root.RootManager +import sh.sar.textpipe.server.TextpipeServer + +class TextpipeService : Service() { + + companion object { + private const val TAG = "TextpipeService" + private const val CHANNEL_ID = "textpipe_service" + private const val NOTIFICATION_ID = 1 + private const val PREFS_NAME = "textpipe_settings" + private const val KEY_PORT = "server_port" + private const val KEY_REDIRECT_PORT = "redirect_port" + private const val DEFAULT_PORT = 8080 + private const val ACTION_STOP = "sh.sar.textpipe.STOP" + + private val _isRunning = MutableStateFlow(false) + val isRunning: StateFlow = _isRunning + + private val _serverPort = MutableStateFlow(DEFAULT_PORT) + val serverPort: StateFlow = _serverPort + + fun start(context: Context) { + val intent = Intent(context, TextpipeService::class.java) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + context.startForegroundService(intent) + } else { + context.startService(intent) + } + } + + fun stop(context: Context) { + context.stopService(Intent(context, TextpipeService::class.java)) + } + + fun getConfiguredPort(context: Context): Int { + val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + return prefs.getInt(KEY_PORT, DEFAULT_PORT) + } + + fun setConfiguredPort(context: Context, port: Int) { + val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + prefs.edit().putInt(KEY_PORT, port).apply() + } + + fun getRedirectPort(context: Context): Int { + val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + return prefs.getInt(KEY_REDIRECT_PORT, 0) + } + + fun setRedirectPort(context: Context, port: Int) { + val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + prefs.edit().putInt(KEY_REDIRECT_PORT, port).apply() + } + } + + private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.Main) + + private var textpipeServer: TextpipeServer? = null + private lateinit var smsRepository: SmsRepository + private lateinit var smsSender: SmsSender + + private var redirectPort: Int = 0 + + override fun onCreate() { + super.onCreate() + Log.i(TAG, "Service onCreate") + createNotificationChannel() + + val app = application as TextpipeApplication + val dao = app.database.smsMessageDao() + val simManager = app.simManager + + // Refresh SIM info + simManager.refreshSims() + + smsSender = SmsSender(this, dao) + smsSender.register() + + smsRepository = SmsRepository(dao, smsSender, simManager) + textpipeServer = TextpipeServer(smsRepository, simManager) + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + Log.i(TAG, "Service onStartCommand, action: ${intent?.action}") + + // Handle stop action from notification + if (intent?.action == ACTION_STOP) { + Log.i(TAG, "Stop action received") + stopSelf() + return START_NOT_STICKY + } + + val notification = createNotification("Starting...") + startForeground(NOTIFICATION_ID, notification) + + val port = getConfiguredPort(this) + _serverPort.value = port + + serviceScope.launch { + // Setup port redirect if configured + redirectPort = getRedirectPort(this@TextpipeService) + if (redirectPort > 0 && redirectPort != port) { + val success = RootManager.setupPortRedirect(redirectPort, port) + if (!success) { + Log.w(TAG, "Failed to setup port redirect from $redirectPort to $port") + setRedirectPort(this@TextpipeService, 0) + redirectPort = 0 + } + } + + // Start HTTP server + val started = textpipeServer?.start(port) ?: false + if (started) { + _isRunning.value = true + val displayPort = if (redirectPort > 0) redirectPort else port + updateNotification("Running on port $displayPort") + Log.i(TAG, "Server started successfully on port $port") + } else { + updateNotification("Failed to start on port $port") + Log.e(TAG, "Failed to start server on port $port") + } + } + + return START_STICKY + } + + override fun onDestroy() { + Log.i(TAG, "Service onDestroy") + + // Clear port redirect synchronously before stopping + if (redirectPort > 0) { + runBlocking { + RootManager.clearPortRedirect(redirectPort, textpipeServer?.getPort() ?: 8080) + } + } + + textpipeServer?.stop() + textpipeServer = null + smsSender.unregister() + _isRunning.value = false + serviceScope.cancel() + + super.onDestroy() + } + + override fun onBind(intent: Intent?): IBinder? = null + + private fun createNotificationChannel() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + val channel = NotificationChannel( + CHANNEL_ID, + "Textpipe Service", + NotificationManager.IMPORTANCE_LOW + ).apply { + description = "SMS Gateway server status" + setShowBadge(false) + } + + val notificationManager = getSystemService(NotificationManager::class.java) + notificationManager.createNotificationChannel(channel) + } + } + + private fun createNotification(content: String): Notification { + val pendingIntent = PendingIntent.getActivity( + this, + 0, + Intent(this, MainActivity::class.java), + PendingIntent.FLAG_IMMUTABLE + ) + + val stopIntent = PendingIntent.getService( + this, + 1, + Intent(this, TextpipeService::class.java).apply { + action = ACTION_STOP + }, + PendingIntent.FLAG_IMMUTABLE + ) + + return NotificationCompat.Builder(this, CHANNEL_ID) + .setContentTitle("Textpipe SMS Gateway") + .setContentText(content) + .setSmallIcon(android.R.drawable.ic_dialog_info) + .setContentIntent(pendingIntent) + .setOngoing(true) + .addAction(android.R.drawable.ic_media_pause, "Stop", stopIntent) + .build() + } + + private fun updateNotification(content: String) { + val notification = createNotification(content) + val notificationManager = getSystemService(NotificationManager::class.java) + notificationManager.notify(NOTIFICATION_ID, notification) + } +} diff --git a/app/src/main/java/sh/sar/textpipe/sim/SimManager.kt b/app/src/main/java/sh/sar/textpipe/sim/SimManager.kt new file mode 100644 index 0000000..d6f4441 --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/sim/SimManager.kt @@ -0,0 +1,123 @@ +package sh.sar.textpipe.sim + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import android.telephony.SubscriptionInfo +import android.telephony.SubscriptionManager +import androidx.core.content.ContextCompat +import sh.sar.textpipe.data.model.SimInfo +import java.util.UUID + +data class SimSlotInfo( + val slotIndex: Int, + val subscriptionId: Int, + val carrierName: String?, + val phoneNumber: String?, + val apiKey: String +) + +class SimManager(private val context: Context) { + private val prefs = context.getSharedPreferences("textpipe_keys", Context.MODE_PRIVATE) + private val subscriptionManager: SubscriptionManager? = + context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as? SubscriptionManager + + private var cachedSims: List = emptyList() + + fun refreshSims(): List { + if (!hasPhonePermission()) { + cachedSims = emptyList() + return cachedSims + } + + val activeSubscriptions = try { + subscriptionManager?.activeSubscriptionInfoList ?: emptyList() + } catch (e: SecurityException) { + emptyList() + } + + cachedSims = activeSubscriptions.map { info -> + val slotIndex = info.simSlotIndex + val apiKey = getOrCreateApiKey(slotIndex) + SimSlotInfo( + slotIndex = slotIndex, + subscriptionId = info.subscriptionId, + carrierName = info.carrierName?.toString(), + phoneNumber = getPhoneNumber(info), + apiKey = apiKey + ) + } + + return cachedSims + } + + private fun getPhoneNumber(info: SubscriptionInfo): String? { + return try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + subscriptionManager?.getPhoneNumber(info.subscriptionId) + } else { + @Suppress("DEPRECATION") + info.number + } + } catch (e: SecurityException) { + null + } + } + + private fun hasPhonePermission(): Boolean { + return ContextCompat.checkSelfPermission( + context, + Manifest.permission.READ_PHONE_STATE + ) == PackageManager.PERMISSION_GRANTED + } + + private fun getOrCreateApiKey(slotIndex: Int): String { + val key = "api_key_sim_$slotIndex" + return prefs.getString(key, null) ?: run { + val newKey = UUID.randomUUID().toString().replace("-", "") + prefs.edit().putString(key, newKey).apply() + newKey + } + } + + fun getApiKeyForSlot(slot: Int): String? { + return prefs.getString("api_key_sim_$slot", null) + } + + fun getSubscriptionIdForApiKey(apiKey: String): Int? { + return cachedSims.find { it.apiKey == apiKey }?.subscriptionId + } + + fun getSimSlotForApiKey(apiKey: String): Int? { + return cachedSims.find { it.apiKey == apiKey }?.slotIndex + } + + fun getAllApiKeys(): Map { + return cachedSims.associate { it.slotIndex to it.apiKey } + } + + fun isValidApiKey(apiKey: String): Boolean { + return cachedSims.any { it.apiKey == apiKey } + } + + fun getSimInfoList(): List { + return cachedSims.map { sim -> + SimInfo( + slot = sim.slotIndex, + carrier = sim.carrierName, + number = sim.phoneNumber, + hasApiKey = true + ) + } + } + + fun getCachedSims(): List = cachedSims + + fun regenerateApiKey(slotIndex: Int): String { + val key = "api_key_sim_$slotIndex" + val newKey = UUID.randomUUID().toString().replace("-", "") + prefs.edit().putString(key, newKey).apply() + return newKey + } +} diff --git a/app/src/main/java/sh/sar/textpipe/ui/MainScreen.kt b/app/src/main/java/sh/sar/textpipe/ui/MainScreen.kt new file mode 100644 index 0000000..20efa8d --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/ui/MainScreen.kt @@ -0,0 +1,464 @@ +package sh.sar.textpipe.ui + +import android.app.Activity +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.fillMaxSize +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.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +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.platform.LocalClipboardManager +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import sh.sar.textpipe.sim.SimSlotInfo + +@Composable +fun MainScreen(viewModel: MainViewModel) { + val isRunning by viewModel.isServerRunning.collectAsState() + val serverPort by viewModel.serverPort.collectAsState() + val simSlots by viewModel.simSlots.collectAsState() + val isRootAvailable by viewModel.isRootAvailable.collectAsState() + val portInput by viewModel.portInput.collectAsState() + val redirectPortInput by viewModel.redirectPortInput.collectAsState() + val autoStartEnabled by viewModel.autoStartEnabled.collectAsState() + val isBatteryOptimized by viewModel.isBatteryOptimized.collectAsState() + + val context = LocalContext.current + val activity = context as? Activity + + Scaffold { padding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(padding) + .padding(16.dp) + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + // Server Status Card + ServerStatusCard( + isRunning = isRunning, + serverPort = serverPort, + onToggle = { viewModel.toggleServer() } + ) + + // SIM Cards + Text( + text = "SIM Cards", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold + ) + if (simSlots.isEmpty()) { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.errorContainer + ) + ) { + Text( + text = "No SIM cards detected. Grant phone permissions and refresh.", + modifier = Modifier.padding(16.dp), + color = MaterialTheme.colorScheme.onErrorContainer + ) + Button( + onClick = { viewModel.refreshSimInfo() }, + modifier = Modifier.padding(start = 16.dp, bottom = 16.dp) + ) { + Text("Refresh") + } + } + } else { + simSlots.forEach { sim -> + SimCard( + sim = sim, + onRegenerateApiKey = { slotIndex -> + viewModel.regenerateApiKey(slotIndex) + } + ) + } + } + + // Settings + Text( + text = "Settings", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold + ) + + // Port Configuration Card + PortConfigCard( + portInput = portInput, + redirectPortInput = redirectPortInput, + isRootAvailable = isRootAvailable, + isRunning = isRunning, + onPortChange = { viewModel.setPort(it) }, + onRedirectPortChange = { viewModel.setRedirectPort(it) }, + onApply = { viewModel.applyPortSettings() } + ) + + // Other Settings Card + SettingsCard( + autoStartEnabled = autoStartEnabled, + isBatteryOptimized = isBatteryOptimized, + onAutoStartChange = { viewModel.setAutoStart(it) }, + onRequestBatteryExemption = { + activity?.let { viewModel.requestBatteryOptimizationExemption(it) } + }, + onRefreshBatteryStatus = { viewModel.refreshBatteryOptimizationStatus() } + ) + } + } +} + +@Composable +private fun ServerStatusCard( + isRunning: Boolean, + serverPort: Int, + onToggle: () -> Unit +) { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors( + containerColor = if (isRunning) { + MaterialTheme.colorScheme.primaryContainer + } else { + MaterialTheme.colorScheme.surfaceVariant + } + ) + ) { + Column( + modifier = Modifier.padding(16.dp) + ) { + Row( + verticalAlignment = Alignment.CenterVertically + ) { + Box( + modifier = Modifier + .size(12.dp) + .clip(CircleShape) + .background(if (isRunning) Color(0xFF4CAF50) else Color(0xFFF44336)) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = if (isRunning) "Server Running" else "Server Stopped", + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold + ) + } + + Spacer(modifier = Modifier.height(8.dp)) + Text( + text = if (isRunning) "Port: $serverPort" else " ", + style = MaterialTheme.typography.bodyLarge + ) + + Spacer(modifier = Modifier.height(16.dp)) + + Button( + onClick = onToggle, + modifier = Modifier.fillMaxWidth(), + colors = if (isRunning) { + ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.error + ) + } else { + ButtonDefaults.buttonColors() + } + ) { + Text(if (isRunning) "Stop Server" else "Start Server") + } + } + } +} + +@Composable +private fun PortConfigCard( + portInput: String, + redirectPortInput: String, + isRootAvailable: Boolean, + isRunning: Boolean, + onPortChange: (String) -> Unit, + onRedirectPortChange: (String) -> Unit, + onApply: () -> Unit +) { + Card( + modifier = Modifier.fillMaxWidth() + ) { + Column( + modifier = Modifier.padding(16.dp) + ) { + Text( + text = "Port Configuration", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold + ) + + Spacer(modifier = Modifier.height(12.dp)) + + OutlinedTextField( + value = portInput, + onValueChange = { onPortChange(it.filter { c -> c.isDigit() }) }, + label = { Text("Server Port") }, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + modifier = Modifier.fillMaxWidth(), + singleLine = true + ) + + if (isRootAvailable) { + Spacer(modifier = Modifier.height(8.dp)) + + OutlinedTextField( + value = redirectPortInput, + onValueChange = { onRedirectPortChange(it.filter { c -> c.isDigit() }) }, + label = { Text("Redirect Port (requires root)") }, + placeholder = { Text("e.g., 80 or 443") }, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + modifier = Modifier.fillMaxWidth(), + singleLine = true + ) + + Text( + text = "Traffic on redirect port will be forwarded to server port via iptables", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 4.dp) + ) + } + + Spacer(modifier = Modifier.height(12.dp)) + + OutlinedButton( + onClick = onApply, + modifier = Modifier.fillMaxWidth() + ) { + Text(if (isRunning) "Apply & Restart" else "Save") + } + } + } +} + +@Composable +private fun SimCard( + sim: SimSlotInfo, + onRegenerateApiKey: (Int) -> Unit +) { + val clipboardManager = LocalClipboardManager.current + var showConfirmDialog by remember { mutableStateOf(false) } + + if (showConfirmDialog) { + AlertDialog( + onDismissRequest = { showConfirmDialog = false }, + title = { Text("Regenerate API Key?") }, + text = { + Text("This will invalidate the current API key for SIM ${sim.slotIndex + 1}. Any applications using this key will need to be updated.") + }, + confirmButton = { + Button( + onClick = { + onRegenerateApiKey(sim.slotIndex) + showConfirmDialog = false + }, + colors = ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.error + ) + ) { + Text("Regenerate") + } + }, + dismissButton = { + TextButton(onClick = { showConfirmDialog = false }) { + Text("Cancel") + } + } + ) + } + + Card( + modifier = Modifier.fillMaxWidth() + ) { + Column( + modifier = Modifier.padding(16.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = "SIM ${sim.slotIndex + 1}", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold + ) + Text( + text = sim.carrierName ?: "Unknown Carrier", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + if (sim.phoneNumber != null) { + Text( + text = sim.phoneNumber, + style = MaterialTheme.typography.bodyMedium, + modifier = Modifier.padding(top = 4.dp) + ) + } + + HorizontalDivider(modifier = Modifier.padding(vertical = 12.dp)) + + Text( + text = "API Key", + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + + Spacer(modifier = Modifier.height(4.dp)) + + SelectionContainer { + Text( + text = sim.apiKey, + style = MaterialTheme.typography.bodyMedium, + fontFamily = FontFamily.Monospace + ) + } + + Spacer(modifier = Modifier.height(12.dp)) + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + OutlinedButton( + onClick = { + clipboardManager.setText(AnnotatedString(sim.apiKey)) + }, + modifier = Modifier.weight(1f) + ) { + Text("Copy") + } + + OutlinedButton( + onClick = { showConfirmDialog = true }, + modifier = Modifier.weight(1f) + ) { + Text("Regenerate") + } + } + } + } +} + +@Composable +private fun SettingsCard( + autoStartEnabled: Boolean, + isBatteryOptimized: Boolean, + onAutoStartChange: (Boolean) -> Unit, + onRequestBatteryExemption: () -> Unit, + onRefreshBatteryStatus: () -> Unit +) { + Card( + modifier = Modifier.fillMaxWidth() + ) { + Column( + modifier = Modifier.padding(16.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = "Auto-start on boot", + style = MaterialTheme.typography.bodyLarge + ) + Text( + text = "Start server automatically when device boots", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Switch( + checked = autoStartEnabled, + onCheckedChange = onAutoStartChange + ) + } + + HorizontalDivider(modifier = Modifier.padding(vertical = 12.dp)) + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = "Battery Optimization", + style = MaterialTheme.typography.bodyLarge + ) + Text( + text = if (isBatteryOptimized) { + "Optimized - server may be killed in background" + } else { + "Unrestricted - server will stay running" + }, + style = MaterialTheme.typography.bodySmall, + color = if (isBatteryOptimized) { + MaterialTheme.colorScheme.error + } else { + MaterialTheme.colorScheme.primary + } + ) + } + + if (isBatteryOptimized) { + Button(onClick = onRequestBatteryExemption) { + Text("Disable") + } + } else { + OutlinedButton(onClick = onRefreshBatteryStatus) { + Text("Refresh") + } + } + } + } + } +} diff --git a/app/src/main/java/sh/sar/textpipe/ui/MainViewModel.kt b/app/src/main/java/sh/sar/textpipe/ui/MainViewModel.kt new file mode 100644 index 0000000..4be11af --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/ui/MainViewModel.kt @@ -0,0 +1,151 @@ +package sh.sar.textpipe.ui + +import android.app.Activity +import android.app.Application +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.PowerManager +import android.provider.Settings +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.viewModelScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import sh.sar.textpipe.TextpipeApplication +import sh.sar.textpipe.root.RootManager +import sh.sar.textpipe.service.BootReceiver +import sh.sar.textpipe.service.TextpipeService +import sh.sar.textpipe.sim.SimSlotInfo + +class MainViewModel(application: Application) : AndroidViewModel(application) { + + private val app = application as TextpipeApplication + + val isServerRunning: StateFlow = TextpipeService.isRunning + val serverPort: StateFlow = TextpipeService.serverPort + + private val _simSlots = MutableStateFlow>(emptyList()) + val simSlots: StateFlow> = _simSlots.asStateFlow() + + private val _isRootAvailable = MutableStateFlow(false) + val isRootAvailable: StateFlow = _isRootAvailable.asStateFlow() + + private val _portInput = MutableStateFlow(TextpipeService.getConfiguredPort(application).toString()) + val portInput: StateFlow = _portInput.asStateFlow() + + private val _redirectPortInput = MutableStateFlow("") + val redirectPortInput: StateFlow = _redirectPortInput.asStateFlow() + + private val _autoStartEnabled = MutableStateFlow(BootReceiver.isAutoStartEnabled(application)) + val autoStartEnabled: StateFlow = _autoStartEnabled.asStateFlow() + + private val _isBatteryOptimized = MutableStateFlow(true) + val isBatteryOptimized: StateFlow = _isBatteryOptimized.asStateFlow() + + init { + viewModelScope.launch { + refreshSimInfo() + } + checkRootAvailability() + checkBatteryOptimization() + + val redirectPort = TextpipeService.getRedirectPort(application) + if (redirectPort > 0) { + _redirectPortInput.value = redirectPort.toString() + } + } + + fun refreshSimInfo() { + viewModelScope.launch(Dispatchers.IO) { + val sims = app.simManager.refreshSims() + _simSlots.value = sims + } + } + + private fun checkRootAvailability() { + viewModelScope.launch { + _isRootAvailable.value = RootManager.isRootAvailable() + } + } + + private fun checkBatteryOptimization() { + val powerManager = getApplication().getSystemService(Context.POWER_SERVICE) as PowerManager + _isBatteryOptimized.value = !powerManager.isIgnoringBatteryOptimizations( + getApplication().packageName + ) + } + + fun setPort(port: String) { + _portInput.value = port + } + + fun setRedirectPort(port: String) { + _redirectPortInput.value = port + } + + fun applyPortSettings() { + val port = _portInput.value.toIntOrNull() ?: return + if (port !in 1..65535) return + + TextpipeService.setConfiguredPort(getApplication(), port) + + val redirectPort = _redirectPortInput.value.toIntOrNull() ?: 0 + if (redirectPort in 1..65535 && redirectPort != port) { + TextpipeService.setRedirectPort(getApplication(), redirectPort) + } else { + TextpipeService.setRedirectPort(getApplication(), 0) + } + + // Restart service if running + if (isServerRunning.value) { + stopServer() + startServer() + } + } + + fun startServer() { + applyPortSettings() + TextpipeService.start(getApplication()) + } + + fun stopServer() { + TextpipeService.stop(getApplication()) + } + + fun toggleServer() { + if (isServerRunning.value) { + stopServer() + } else { + startServer() + } + } + + fun setAutoStart(enabled: Boolean) { + BootReceiver.setAutoStartEnabled(getApplication(), enabled) + _autoStartEnabled.value = enabled + } + + fun requestBatteryOptimizationExemption(activity: Activity) { + val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply { + data = Uri.parse("package:${activity.packageName}") + } + activity.startActivity(intent) + } + + fun openBatteryOptimizationSettings(activity: Activity) { + val intent = Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS) + activity.startActivity(intent) + } + + fun refreshBatteryOptimizationStatus() { + checkBatteryOptimization() + } + + fun regenerateApiKey(slotIndex: Int) { + app.simManager.regenerateApiKey(slotIndex) + refreshSimInfo() + } +} diff --git a/app/src/main/java/sh/sar/textpipe/ui/theme/Color.kt b/app/src/main/java/sh/sar/textpipe/ui/theme/Color.kt new file mode 100644 index 0000000..e353723 --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/ui/theme/Color.kt @@ -0,0 +1,21 @@ +package sh.sar.textpipe.ui.theme + +import androidx.compose.ui.graphics.Color + +// Accent orange +val Orange = Color(0xFFFFA31A) +val OrangeDark = Color(0xFFCC8215) + +// Dark backgrounds +val DarkBackground = Color(0xFF1B1B1B) +val DarkSurface = Color(0xFF292929) +val DarkSurfaceVariant = Color(0xFF363636) + +// Text colors +val TextWhite = Color(0xFFFFFFFF) +val TextGray = Color(0xFFB3B3B3) +val TextDarkGray = Color(0xFF8C8C8C) + +// Status colors +val StatusGreen = Color(0xFF4CAF50) +val StatusRed = Color(0xFFF44336) diff --git a/app/src/main/java/sh/sar/textpipe/ui/theme/Theme.kt b/app/src/main/java/sh/sar/textpipe/ui/theme/Theme.kt new file mode 100644 index 0000000..c34d9d5 --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/ui/theme/Theme.kt @@ -0,0 +1,65 @@ +package sh.sar.textpipe.ui.theme + +import android.app.Activity +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.SideEffect +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.platform.LocalView +import androidx.core.view.WindowCompat + +private val TextpipeColorScheme = darkColorScheme( + primary = Orange, + onPrimary = DarkBackground, + primaryContainer = OrangeDark, + onPrimaryContainer = TextWhite, + secondary = Orange, + onSecondary = DarkBackground, + secondaryContainer = DarkSurfaceVariant, + onSecondaryContainer = TextWhite, + tertiary = Orange, + onTertiary = DarkBackground, + background = DarkBackground, + onBackground = TextWhite, + surface = DarkSurface, + onSurface = TextWhite, + surfaceVariant = DarkSurfaceVariant, + onSurfaceVariant = TextGray, + error = StatusRed, + onError = TextWhite, + errorContainer = Color(0xFF93000A), + onErrorContainer = TextWhite, + outline = TextDarkGray, + outlineVariant = DarkSurfaceVariant, + inverseSurface = TextWhite, + inverseOnSurface = DarkBackground, + inversePrimary = OrangeDark, + surfaceTint = Orange +) + +@Composable +fun TextpipeTheme( + content: @Composable () -> Unit +) { + val colorScheme = TextpipeColorScheme + val view = LocalView.current + + if (!view.isInEditMode) { + SideEffect { + val window = (view.context as Activity).window + window.statusBarColor = DarkBackground.toArgb() + window.navigationBarColor = DarkBackground.toArgb() + WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = false + WindowCompat.getInsetsController(window, view).isAppearanceLightNavigationBars = false + } + } + + MaterialTheme( + colorScheme = colorScheme, + typography = Typography, + content = content + ) +} diff --git a/app/src/main/java/sh/sar/textpipe/ui/theme/Type.kt b/app/src/main/java/sh/sar/textpipe/ui/theme/Type.kt new file mode 100644 index 0000000..0ee4877 --- /dev/null +++ b/app/src/main/java/sh/sar/textpipe/ui/theme/Type.kt @@ -0,0 +1,34 @@ +package sh.sar.textpipe.ui.theme + +import androidx.compose.material3.Typography +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 + +// Set of Material typography styles to start with +val Typography = Typography( + bodyLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 16.sp, + lineHeight = 24.sp, + letterSpacing = 0.5.sp + ) + /* Other default text styles to override + titleLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 22.sp, + lineHeight = 28.sp, + letterSpacing = 0.sp + ), + labelSmall = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Medium, + fontSize = 11.sp, + lineHeight = 16.sp, + letterSpacing = 0.5.sp + ) + */ +) \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..07d5da9 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..2b068d1 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..6f3b755 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..6f3b755 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/app/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 0000000..c209e78 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 0000000..b2dfe3d Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/app/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 0000000..4f0f1d6 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 0000000..62b611d Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 0000000..948a307 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..1b9a695 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 0000000..28d4b77 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..9287f50 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 0000000..aa7d642 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..9126ae3 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..f8c6127 --- /dev/null +++ b/app/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..f968f38 --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + Textpipe + \ No newline at end of file diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..e101205 --- /dev/null +++ b/app/src/main/res/values/themes.xml @@ -0,0 +1,5 @@ + + + +