adjusted for uptime-kuma
@@ -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 <key>` or `X-API-Key: <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
|
||||||
|
<!-- SMS -->
|
||||||
|
<uses-permission android:name="android.permission.SEND_SMS" />
|
||||||
|
<uses-permission android:name="android.permission.RECEIVE_SMS" />
|
||||||
|
<uses-permission android:name="android.permission.READ_SMS" />
|
||||||
|
|
||||||
|
<!-- Phone/SIM -->
|
||||||
|
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.READ_PHONE_NUMBERS" />
|
||||||
|
|
||||||
|
<!-- Network -->
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
|
||||||
|
<!-- Background Service -->
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||||
|
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||||
|
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||||
|
|
||||||
|
<!-- Battery -->
|
||||||
|
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||||
|
|
||||||
|
<!-- Notifications -->
|
||||||
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
# Textpipe - SMS API Gateway
|
||||||
|
|
||||||
|
An Android app that turns your phone into an SMS API gateway with a web interface.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- **REST API** - Send and receive SMS via HTTP endpoints
|
||||||
|
- **Dual SIM Support** - Each SIM gets its own API key
|
||||||
|
- **Web UI** - Google Messages-like interface accessible from any browser
|
||||||
|
- **Local Database** - All messages stored locally with delivery tracking
|
||||||
|
- **Background Service** - Runs as a foreground service with persistent notification
|
||||||
|
- **Auto-start** - Optionally start on device boot
|
||||||
|
- **Root Support** - Bind directly to ports 80/443 with root access
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
- Android 7.0+ (API 24+)
|
||||||
|
- SMS permissions
|
||||||
|
- Phone state permissions (for dual SIM)
|
||||||
|
- (Optional) Root access for privileged ports
|
||||||
|
|
||||||
|
## Building
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
- Android Studio or command line with Android SDK
|
||||||
|
- JDK 11+
|
||||||
|
|
||||||
|
### Build Steps
|
||||||
|
|
||||||
|
1. **Clone the repository**
|
||||||
|
```bash
|
||||||
|
git clone https://git.shihaam.dev/shihaam/textpipe
|
||||||
|
cd textpipe
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Build the Android App**
|
||||||
|
```bash
|
||||||
|
./gradlew assembleDebug
|
||||||
|
```
|
||||||
|
The APK will be at `app/build/outputs/apk/debug/app-debug.apk`
|
||||||
|
|
||||||
|
3. **Install on device**
|
||||||
|
```bash
|
||||||
|
adb install app/build/outputs/apk/debug/app-debug.apk
|
||||||
|
```
|
||||||
|
|
||||||
|
### Release Build
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./gradlew assembleRelease
|
||||||
|
```
|
||||||
|
|
||||||
|
Note: You'll need to configure signing in `app/build.gradle.kts` for release builds.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
### Initial Setup
|
||||||
|
|
||||||
|
1. Install and open the app
|
||||||
|
2. Grant all requested permissions (SMS, Phone, Notifications)
|
||||||
|
3. Note the API key(s) shown for each SIM card
|
||||||
|
4. Configure the port (default: 8080)
|
||||||
|
5. Tap "Start Server"
|
||||||
|
6. (Optional) Disable battery optimization for reliable background operation
|
||||||
|
|
||||||
|
### API Endpoints
|
||||||
|
|
||||||
|
Base URL: `http://<phone-ip>:<port>`
|
||||||
|
|
||||||
|
#### Status (No auth required)
|
||||||
|
```
|
||||||
|
GET /api/status
|
||||||
|
```
|
||||||
|
Returns server status and SIM information.
|
||||||
|
|
||||||
|
#### Send SMS
|
||||||
|
```
|
||||||
|
POST /api/sms/send
|
||||||
|
Header: X-API-Key: <your-api-key>
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"to": "+1234567890",
|
||||||
|
"text": "Hello from Textpipe!"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Response:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"status": "pending",
|
||||||
|
"simSlot": 0
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### List Messages
|
||||||
|
```
|
||||||
|
GET /api/sms/messages
|
||||||
|
Header: X-API-Key: <your-api-key>
|
||||||
|
```
|
||||||
|
|
||||||
|
Optional query parameter: `?type=sent` or `?type=received`
|
||||||
|
|
||||||
|
Response:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"messages": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"type": "sent",
|
||||||
|
"address": "+1234567890",
|
||||||
|
"text": "Hello!",
|
||||||
|
"simSlot": 0,
|
||||||
|
"status": "delivered",
|
||||||
|
"timestamp": 1707148800000,
|
||||||
|
"deliveryTimestamp": 1707148805000
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"total": 1
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Get Message Status
|
||||||
|
```
|
||||||
|
GET /api/sms/status/{id}
|
||||||
|
Header: X-API-Key: <your-api-key>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Authentication
|
||||||
|
|
||||||
|
Pass your API key in one of these ways:
|
||||||
|
- Header: `Authorization: Bearer <key>`
|
||||||
|
- Header: `X-API-Key: <key>`
|
||||||
|
- Query param: `?api_key=<key>`
|
||||||
|
|
||||||
|
Each SIM card has its own unique API key. The API key determines which SIM sends the message.
|
||||||
|
|
||||||
|
### Web Interface
|
||||||
|
|
||||||
|
Open `http://<phone-ip>:<port>/` in any browser to access the web UI.
|
||||||
|
|
||||||
|
1. Enter your API key to login
|
||||||
|
2. View conversations grouped by contact
|
||||||
|
3. Send new messages using the + button
|
||||||
|
4. Click on a conversation to view message thread
|
||||||
|
|
||||||
|
### cURL Examples
|
||||||
|
|
||||||
|
**Send SMS:**
|
||||||
|
```bash
|
||||||
|
curl -X POST http://10.0.1.12:8080/api/sms/send \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-H "X-API-Key: your-api-key-here" \
|
||||||
|
-d '{"to": "+1234567890", "text": "Hello!"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
**Check status:**
|
||||||
|
```bash
|
||||||
|
curl http://10.0.1.12:8080/api/status
|
||||||
|
```
|
||||||
|
|
||||||
|
**List messages:**
|
||||||
|
```bash
|
||||||
|
curl -H "X-API-Key: your-api-key-here" \
|
||||||
|
http://10.0.1.12:8080/api/sms/messages
|
||||||
|
```
|
||||||
|
|
||||||
|
**Get specific message:**
|
||||||
|
```bash
|
||||||
|
curl -H "X-API-Key: your-api-key-here" \
|
||||||
|
http://10.0.1.12:8080/api/sms/status/1
|
||||||
|
```
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
### Port Configuration
|
||||||
|
|
||||||
|
- Default port: 8080
|
||||||
|
- Can be changed in the app UI
|
||||||
|
- For ports below 1024 (like 80 or 443), root access is required
|
||||||
|
- With root, the app uses sysctl to allow binding to privileged ports directly
|
||||||
|
|
||||||
|
### Auto-start
|
||||||
|
|
||||||
|
Enable "Auto-start on boot" in Settings to automatically start the server when the device boots.
|
||||||
|
|
||||||
|
### Battery Optimization
|
||||||
|
|
||||||
|
For reliable background operation, disable battery optimization for Textpipe:
|
||||||
|
1. Go to Settings in the app
|
||||||
|
2. Tap "Disable" next to Battery Optimization
|
||||||
|
3. Confirm in the system dialog
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
textpipe/
|
||||||
|
├── app/ # Android app
|
||||||
|
│ └── src/main/
|
||||||
|
│ ├── java/sh/sar/textpipe/
|
||||||
|
│ │ ├── MainActivity.kt
|
||||||
|
│ │ ├── TextpipeApplication.kt
|
||||||
|
│ │ ├── data/
|
||||||
|
│ │ │ ├── db/ # Room database
|
||||||
|
│ │ │ ├── model/ # API models
|
||||||
|
│ │ │ └── repository/ # Data repository
|
||||||
|
│ │ ├── server/ # Ktor HTTP server
|
||||||
|
│ │ │ ├── TextpipeServer.kt
|
||||||
|
│ │ │ ├── auth/ # API key auth
|
||||||
|
│ │ │ └── routes/ # API endpoints
|
||||||
|
│ │ ├── service/ # Android services
|
||||||
|
│ │ │ ├── TextpipeService.kt
|
||||||
|
│ │ │ ├── SmsSender.kt
|
||||||
|
│ │ │ ├── SmsReceiver.kt
|
||||||
|
│ │ │ └── BootReceiver.kt
|
||||||
|
│ │ ├── sim/ # SIM management
|
||||||
|
│ │ ├── root/ # Root utilities
|
||||||
|
│ │ └── ui/ # Compose UI
|
||||||
|
│ ├── assets/webui/ # Web UI (vanilla HTML/CSS/JS)
|
||||||
|
│ │ └── index.html
|
||||||
|
│ └── AndroidManifest.xml
|
||||||
|
├── gradle/
|
||||||
|
│ └── libs.versions.toml # Dependency versions
|
||||||
|
└── build.gradle.kts
|
||||||
|
```
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
|
||||||
|
### Android App
|
||||||
|
- Kotlin
|
||||||
|
- Jetpack Compose (UI)
|
||||||
|
- Ktor CIO (HTTP server)
|
||||||
|
- Room (Database)
|
||||||
|
- Kotlin Coroutines
|
||||||
|
- kotlinx.serialization (JSON)
|
||||||
|
|
||||||
|
### Web UI
|
||||||
|
- Vanilla HTML/CSS/JS (no build step required)
|
||||||
|
|
||||||
|
## Message Status Flow
|
||||||
|
|
||||||
|
```
|
||||||
|
pending → sent → delivered
|
||||||
|
↘ failed
|
||||||
|
```
|
||||||
|
|
||||||
|
- **pending** - Message queued, sending in progress
|
||||||
|
- **sent** - Message sent successfully
|
||||||
|
- **delivered** - Delivery confirmation received
|
||||||
|
- **failed** - Send failed
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### "Address already in use" error
|
||||||
|
The port is still bound from a previous instance. Either:
|
||||||
|
- Wait a few seconds and try again
|
||||||
|
- Change to a different port
|
||||||
|
- Force stop the app and restart
|
||||||
|
|
||||||
|
### Server doesn't start
|
||||||
|
- Check that no other app is using the port
|
||||||
|
- Verify all permissions are granted
|
||||||
|
- Check logcat for errors: `adb logcat -s TextpipeServer TextpipeService`
|
||||||
|
|
||||||
|
### Messages not sending
|
||||||
|
- Verify SMS permission is granted
|
||||||
|
- Check you have cellular signal
|
||||||
|
- Ensure the API key matches an active SIM
|
||||||
|
|
||||||
|
### Web UI not loading
|
||||||
|
- Verify the server is running (check app status)
|
||||||
|
- Check you're using the correct IP and port
|
||||||
|
- Try accessing `/api/status` directly
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
/build
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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
|
||||||
@@ -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')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:tools="http://schemas.android.com/tools">
|
||||||
|
|
||||||
|
<!-- SMS Permissions -->
|
||||||
|
<uses-permission android:name="android.permission.SEND_SMS" />
|
||||||
|
<uses-permission android:name="android.permission.RECEIVE_SMS" />
|
||||||
|
<uses-permission android:name="android.permission.READ_SMS" />
|
||||||
|
|
||||||
|
<!-- Phone/SIM Permissions -->
|
||||||
|
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.READ_PHONE_NUMBERS" />
|
||||||
|
|
||||||
|
<!-- Contacts -->
|
||||||
|
<uses-permission android:name="android.permission.READ_CONTACTS" />
|
||||||
|
|
||||||
|
<!-- Network -->
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
|
||||||
|
<!-- Background Service -->
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||||
|
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||||
|
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||||
|
|
||||||
|
<!-- Battery Optimization -->
|
||||||
|
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||||
|
|
||||||
|
<!-- Notifications -->
|
||||||
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
|
||||||
|
<application
|
||||||
|
android:name=".TextpipeApplication"
|
||||||
|
android:allowBackup="true"
|
||||||
|
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||||
|
android:fullBackupContent="@xml/backup_rules"
|
||||||
|
android:icon="@mipmap/ic_launcher"
|
||||||
|
android:label="@string/app_name"
|
||||||
|
android:roundIcon="@mipmap/ic_launcher_round"
|
||||||
|
android:supportsRtl="true"
|
||||||
|
android:theme="@style/Theme.Textpipe">
|
||||||
|
|
||||||
|
<activity
|
||||||
|
android:name=".MainActivity"
|
||||||
|
android:exported="true"
|
||||||
|
android:label="@string/app_name"
|
||||||
|
android:theme="@style/Theme.Textpipe">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
|
||||||
|
<!-- Foreground Service -->
|
||||||
|
<service
|
||||||
|
android:name=".service.TextpipeService"
|
||||||
|
android:foregroundServiceType="specialUse"
|
||||||
|
android:exported="false">
|
||||||
|
<property
|
||||||
|
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||||
|
android:value="HTTP SMS Gateway Server" />
|
||||||
|
</service>
|
||||||
|
|
||||||
|
<!-- Boot Receiver -->
|
||||||
|
<receiver
|
||||||
|
android:name=".service.BootReceiver"
|
||||||
|
android:enabled="true"
|
||||||
|
android:exported="true"
|
||||||
|
android:directBootAware="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||||
|
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
|
||||||
|
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
|
||||||
|
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
|
||||||
|
</intent-filter>
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
<!-- SMS Receiver -->
|
||||||
|
<receiver
|
||||||
|
android:name=".service.SmsReceiver"
|
||||||
|
android:enabled="true"
|
||||||
|
android:exported="true"
|
||||||
|
android:permission="android.permission.BROADCAST_SMS">
|
||||||
|
<intent-filter android:priority="999">
|
||||||
|
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
|
||||||
|
</intent-filter>
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
</application>
|
||||||
|
|
||||||
|
</manifest>
|
||||||
@@ -0,0 +1,534 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Textpipe</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
--bg-primary: #1B1B1B;
|
||||||
|
--bg-secondary: #292929;
|
||||||
|
--bg-card: #333333;
|
||||||
|
--accent: #FFA31A;
|
||||||
|
--text-primary: #FFFFFF;
|
||||||
|
--text-secondary: #AAAAAA;
|
||||||
|
--error: #FF5252;
|
||||||
|
--success: #4CAF50;
|
||||||
|
}
|
||||||
|
|
||||||
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||||
|
background: var(--bg-primary);
|
||||||
|
color: var(--text-primary);
|
||||||
|
min-height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Login */
|
||||||
|
#login-screen {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-height: 100vh;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#login-screen h1 { color: var(--accent); margin-bottom: 8px; font-size: 2.5rem; }
|
||||||
|
#login-screen .subtitle { color: var(--text-secondary); margin-bottom: 30px; }
|
||||||
|
|
||||||
|
.login-form { width: 100%; max-width: 360px; }
|
||||||
|
|
||||||
|
input, textarea {
|
||||||
|
width: 100%;
|
||||||
|
padding: 14px 16px;
|
||||||
|
border: 1px solid #444;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-size: 1rem;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
input:focus, textarea:focus { outline: none; border-color: var(--accent); }
|
||||||
|
|
||||||
|
button {
|
||||||
|
width: 100%;
|
||||||
|
padding: 14px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--accent);
|
||||||
|
color: #000;
|
||||||
|
font-size: 1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover { opacity: 0.9; }
|
||||||
|
.error-msg { color: var(--error); margin-top: 10px; text-align: center; font-size: 0.9rem; }
|
||||||
|
|
||||||
|
/* Main App */
|
||||||
|
#main-app { display: none; height: 100vh; display: none; flex-direction: column; }
|
||||||
|
|
||||||
|
/* Header */
|
||||||
|
header {
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
padding: 12px 16px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
border-bottom: 1px solid #444;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-left { display: flex; align-items: center; gap: 12px; }
|
||||||
|
.header-left h1 { color: var(--accent); font-size: 1.3rem; }
|
||||||
|
.sim-info { color: var(--text-secondary); font-size: 0.85rem; }
|
||||||
|
|
||||||
|
.header-right { display: flex; align-items: center; gap: 8px; }
|
||||||
|
|
||||||
|
.icon-btn {
|
||||||
|
background: transparent;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
padding: 0;
|
||||||
|
border-radius: 50%;
|
||||||
|
font-size: 1.2rem;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-btn:hover { background: rgba(255,255,255,0.1); color: var(--text-primary); }
|
||||||
|
|
||||||
|
/* Conversations */
|
||||||
|
#conversations {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.conversation-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
padding: 14px;
|
||||||
|
background: var(--bg-card);
|
||||||
|
border-radius: 12px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.conversation-item:hover { background: #3a3a3a; }
|
||||||
|
|
||||||
|
.avatar {
|
||||||
|
width: 48px;
|
||||||
|
height: 48px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--accent);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #000;
|
||||||
|
margin-right: 14px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.conv-info { flex: 1; min-width: 0; }
|
||||||
|
.conv-address { font-weight: 600; margin-bottom: 2px; }
|
||||||
|
.conv-number { color: var(--text-secondary); font-size: 0.8rem; margin-bottom: 2px; }
|
||||||
|
.conv-preview { color: var(--text-secondary); font-size: 0.9rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.conv-time { color: var(--text-secondary); font-size: 0.8rem; flex-shrink: 0; margin-left: 10px; }
|
||||||
|
|
||||||
|
.empty-state { text-align: center; padding: 60px 20px; color: var(--text-secondary); }
|
||||||
|
|
||||||
|
/* FAB */
|
||||||
|
.fab {
|
||||||
|
position: fixed;
|
||||||
|
bottom: 24px;
|
||||||
|
right: 24px;
|
||||||
|
width: 56px;
|
||||||
|
height: 56px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--accent);
|
||||||
|
color: #000;
|
||||||
|
font-size: 1.8rem;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
box-shadow: 0 4px 12px rgba(0,0,0,0.4);
|
||||||
|
cursor: pointer;
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.fab:hover { transform: scale(1.05); }
|
||||||
|
|
||||||
|
/* Thread View */
|
||||||
|
#thread-view {
|
||||||
|
display: none;
|
||||||
|
flex-direction: column;
|
||||||
|
height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-header {
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
padding: 12px 16px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
border-bottom: 1px solid #444;
|
||||||
|
}
|
||||||
|
|
||||||
|
.back-btn {
|
||||||
|
background: transparent;
|
||||||
|
color: var(--text-primary);
|
||||||
|
width: 40px;
|
||||||
|
padding: 0;
|
||||||
|
font-size: 1.4rem;
|
||||||
|
margin-right: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#thread-address { line-height: 1.3; }
|
||||||
|
|
||||||
|
.thread-messages {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-bubble {
|
||||||
|
max-width: 80%;
|
||||||
|
padding: 10px 14px;
|
||||||
|
border-radius: 18px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
word-wrap: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.msg-in { background: var(--bg-card); border-bottom-left-radius: 4px; }
|
||||||
|
.msg-out { background: var(--accent); color: #000; margin-left: auto; border-bottom-right-radius: 4px; }
|
||||||
|
.msg-time { font-size: 0.7rem; opacity: 0.7; margin-top: 4px; }
|
||||||
|
|
||||||
|
.thread-compose {
|
||||||
|
padding: 12px;
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
border-top: 1px solid #444;
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-compose input {
|
||||||
|
flex: 1;
|
||||||
|
margin: 0;
|
||||||
|
border-radius: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.send-btn {
|
||||||
|
width: 48px;
|
||||||
|
height: 48px;
|
||||||
|
border-radius: 50%;
|
||||||
|
padding: 0;
|
||||||
|
font-size: 1.2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Compose Modal */
|
||||||
|
.modal-overlay {
|
||||||
|
display: none;
|
||||||
|
position: fixed;
|
||||||
|
top: 0; left: 0; right: 0; bottom: 0;
|
||||||
|
background: rgba(0,0,0,0.7);
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
z-index: 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal {
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
border-radius: 16px;
|
||||||
|
padding: 24px;
|
||||||
|
width: 90%;
|
||||||
|
max-width: 400px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal h2 { color: var(--accent); margin-bottom: 20px; }
|
||||||
|
.modal textarea { min-height: 100px; resize: vertical; }
|
||||||
|
.modal-actions { display: flex; gap: 10px; margin-top: 16px; }
|
||||||
|
.modal-actions button { flex: 1; }
|
||||||
|
|
||||||
|
.cancel-btn {
|
||||||
|
background: transparent;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
border: 1px solid #444;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* About Modal */
|
||||||
|
.about-content { color: var(--text-secondary); line-height: 1.6; }
|
||||||
|
.about-content h2 { color: var(--accent); margin-bottom: 8px; }
|
||||||
|
.about-content a { color: var(--accent); }
|
||||||
|
.about-content ul { margin: 16px 0 16px 20px; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<!-- Login -->
|
||||||
|
<div id="login-screen">
|
||||||
|
<h1>Textpipe</h1>
|
||||||
|
<p class="subtitle">SMS Gateway</p>
|
||||||
|
<div class="login-form">
|
||||||
|
<input type="password" id="api-key" placeholder="Enter API Key">
|
||||||
|
<button onclick="login()">Login</button>
|
||||||
|
<p class="error-msg" id="login-error"></p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Main App -->
|
||||||
|
<div id="main-app">
|
||||||
|
<header>
|
||||||
|
<div class="header-left">
|
||||||
|
<h1>Textpipe</h1>
|
||||||
|
<span class="sim-info" id="sim-info">Loading...</span>
|
||||||
|
</div>
|
||||||
|
<div class="header-right">
|
||||||
|
<button class="icon-btn" onclick="showAbout()" title="About">i</button>
|
||||||
|
<button class="icon-btn" onclick="logout()" title="Logout">x</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div id="conversations"></div>
|
||||||
|
|
||||||
|
<button class="fab" onclick="showCompose()">+</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Thread View -->
|
||||||
|
<div id="thread-view">
|
||||||
|
<div class="thread-header">
|
||||||
|
<button class="back-btn" onclick="closeThread()">←</button>
|
||||||
|
<span id="thread-address"></span>
|
||||||
|
</div>
|
||||||
|
<div class="thread-messages" id="thread-messages"></div>
|
||||||
|
<div class="thread-compose">
|
||||||
|
<input type="text" id="thread-input" placeholder="Message" onkeypress="if(event.key==='Enter')sendInThread()">
|
||||||
|
<button class="send-btn" onclick="sendInThread()">→</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Compose Modal -->
|
||||||
|
<div class="modal-overlay" id="compose-modal" onclick="if(event.target===this)closeCompose()">
|
||||||
|
<div class="modal">
|
||||||
|
<h2>New Message</h2>
|
||||||
|
<input type="tel" id="compose-to" placeholder="Phone number">
|
||||||
|
<textarea id="compose-msg" placeholder="Message"></textarea>
|
||||||
|
<p class="error-msg" id="compose-error"></p>
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button class="cancel-btn" onclick="closeCompose()">Cancel</button>
|
||||||
|
<button onclick="sendCompose()">Send</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- About Modal -->
|
||||||
|
<div class="modal-overlay" id="about-modal" onclick="if(event.target===this)closeAbout()">
|
||||||
|
<div class="modal about-content">
|
||||||
|
<h2>Textpipe</h2>
|
||||||
|
<p>SMS API Gateway for Android</p>
|
||||||
|
<p style="margin-top:16px"><a href="https://git.shihaam.dev/shihaam/textpipe" target="_blank">git.shihaam.dev/shihaam/textpipe</a></p>
|
||||||
|
<div class="modal-actions" style="margin-top:24px">
|
||||||
|
<button onclick="closeAbout()">Close</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
let apiKey = localStorage.getItem('apiKey') || '';
|
||||||
|
let allMessages = [];
|
||||||
|
let currentAddress = '';
|
||||||
|
|
||||||
|
if (apiKey) checkAuth();
|
||||||
|
|
||||||
|
async function login() {
|
||||||
|
apiKey = document.getElementById('api-key').value.trim();
|
||||||
|
if (!apiKey) { document.getElementById('login-error').textContent = 'Enter API key'; return; }
|
||||||
|
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/status', { headers: { 'X-API-Key': apiKey } });
|
||||||
|
if (r.ok) {
|
||||||
|
localStorage.setItem('apiKey', apiKey);
|
||||||
|
showApp();
|
||||||
|
} else {
|
||||||
|
document.getElementById('login-error').textContent = 'Invalid API key';
|
||||||
|
}
|
||||||
|
} catch (e) { document.getElementById('login-error').textContent = 'Connection error'; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function checkAuth() {
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/status', { headers: { 'X-API-Key': apiKey } });
|
||||||
|
if (r.ok) showApp();
|
||||||
|
else logout();
|
||||||
|
} catch (e) { logout(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
function showApp() {
|
||||||
|
document.getElementById('login-screen').style.display = 'none';
|
||||||
|
document.getElementById('main-app').style.display = 'flex';
|
||||||
|
loadStatus();
|
||||||
|
loadMessages();
|
||||||
|
}
|
||||||
|
|
||||||
|
function logout() {
|
||||||
|
apiKey = '';
|
||||||
|
localStorage.removeItem('apiKey');
|
||||||
|
document.getElementById('login-screen').style.display = 'flex';
|
||||||
|
document.getElementById('main-app').style.display = 'none';
|
||||||
|
document.getElementById('thread-view').style.display = 'none';
|
||||||
|
document.getElementById('api-key').value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadStatus() {
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/status', { headers: { 'X-API-Key': apiKey } });
|
||||||
|
const sim = await r.json();
|
||||||
|
document.getElementById('sim-info').textContent = sim.slot !== undefined
|
||||||
|
? `SIM ${sim.slot + 1} - ${sim.number || sim.carrier || 'Unknown'}`
|
||||||
|
: 'No SIM';
|
||||||
|
} catch (e) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadMessages() {
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/sms/messages', { headers: { 'X-API-Key': apiKey } });
|
||||||
|
const d = await r.json();
|
||||||
|
allMessages = d.messages || [];
|
||||||
|
renderConversations();
|
||||||
|
} catch (e) { console.error('Failed to load messages:', e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderConversations() {
|
||||||
|
const grouped = {};
|
||||||
|
allMessages.forEach(m => {
|
||||||
|
if (!grouped[m.address]) grouped[m.address] = { msgs: [], contactName: m.contactName };
|
||||||
|
grouped[m.address].msgs.push(m);
|
||||||
|
// Use first non-null contact name
|
||||||
|
if (m.contactName && !grouped[m.address].contactName) {
|
||||||
|
grouped[m.address].contactName = m.contactName;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const convs = Object.entries(grouped).map(([addr, data]) => {
|
||||||
|
data.msgs.sort((a, b) => b.timestamp - a.timestamp);
|
||||||
|
return { address: addr, contactName: data.contactName, latest: data.msgs[0] };
|
||||||
|
}).sort((a, b) => b.latest.timestamp - a.latest.timestamp);
|
||||||
|
|
||||||
|
const el = document.getElementById('conversations');
|
||||||
|
if (!convs.length) {
|
||||||
|
el.innerHTML = '<div class="empty-state">No messages yet<br>Tap + to send one</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
el.innerHTML = convs.map(c => {
|
||||||
|
const displayName = c.contactName || c.address;
|
||||||
|
const avatarText = c.contactName ? c.contactName.slice(0, 2).toUpperCase() : c.address.slice(-2);
|
||||||
|
return `
|
||||||
|
<div class="conversation-item" onclick="openThread('${c.address}')">
|
||||||
|
<div class="avatar">${avatarText}</div>
|
||||||
|
<div class="conv-info">
|
||||||
|
<div class="conv-address">${displayName}</div>
|
||||||
|
${c.contactName ? `<div class="conv-number">${c.address}</div>` : ''}
|
||||||
|
<div class="conv-preview">${c.latest.text}</div>
|
||||||
|
</div>
|
||||||
|
<span class="conv-time">${formatTime(c.latest.timestamp)}</span>
|
||||||
|
</div>
|
||||||
|
`}).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
function openThread(addr) {
|
||||||
|
currentAddress = addr;
|
||||||
|
document.getElementById('main-app').style.display = 'none';
|
||||||
|
document.getElementById('thread-view').style.display = 'flex';
|
||||||
|
|
||||||
|
// Find contact name for this address
|
||||||
|
const contactMsg = allMessages.find(m => m.address === addr && m.contactName);
|
||||||
|
const displayName = contactMsg?.contactName || addr;
|
||||||
|
document.getElementById('thread-address').innerHTML = contactMsg?.contactName
|
||||||
|
? `${displayName}<br><span style="font-size:0.8rem;color:var(--text-secondary)">${addr}</span>`
|
||||||
|
: displayName;
|
||||||
|
|
||||||
|
const msgs = allMessages.filter(m => m.address === addr).sort((a,b) => a.timestamp - b.timestamp);
|
||||||
|
const el = document.getElementById('thread-messages');
|
||||||
|
el.innerHTML = msgs.map(m => `
|
||||||
|
<div class="message-bubble ${m.type === 'received' ? 'msg-in' : 'msg-out'}">
|
||||||
|
${m.text}
|
||||||
|
<div class="msg-time">${formatTime(m.timestamp)}</div>
|
||||||
|
</div>
|
||||||
|
`).join('');
|
||||||
|
el.scrollTop = el.scrollHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeThread() {
|
||||||
|
document.getElementById('thread-view').style.display = 'none';
|
||||||
|
document.getElementById('main-app').style.display = 'flex';
|
||||||
|
currentAddress = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendInThread() {
|
||||||
|
const input = document.getElementById('thread-input');
|
||||||
|
const text = input.value.trim();
|
||||||
|
if (!text) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await fetch('/api/sms/send', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', 'X-API-Key': apiKey },
|
||||||
|
body: JSON.stringify({ to: currentAddress, text })
|
||||||
|
});
|
||||||
|
input.value = '';
|
||||||
|
await loadMessages();
|
||||||
|
openThread(currentAddress);
|
||||||
|
} catch (e) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
function showCompose() { document.getElementById('compose-modal').style.display = 'flex'; }
|
||||||
|
function closeCompose() {
|
||||||
|
document.getElementById('compose-modal').style.display = 'none';
|
||||||
|
document.getElementById('compose-to').value = '';
|
||||||
|
document.getElementById('compose-msg').value = '';
|
||||||
|
document.getElementById('compose-error').textContent = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendCompose() {
|
||||||
|
const to = document.getElementById('compose-to').value.trim();
|
||||||
|
const text = document.getElementById('compose-msg').value.trim();
|
||||||
|
if (!to || !text) { document.getElementById('compose-error').textContent = 'Fill all fields'; return; }
|
||||||
|
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/sms/send', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', 'X-API-Key': apiKey },
|
||||||
|
body: JSON.stringify({ to, text })
|
||||||
|
});
|
||||||
|
if (r.ok) {
|
||||||
|
closeCompose();
|
||||||
|
await loadMessages();
|
||||||
|
openThread(to);
|
||||||
|
} else {
|
||||||
|
const e = await r.json();
|
||||||
|
document.getElementById('compose-error').textContent = e.error || 'Failed';
|
||||||
|
}
|
||||||
|
} catch (e) { document.getElementById('compose-error').textContent = 'Error'; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function showAbout() { document.getElementById('about-modal').style.display = 'flex'; }
|
||||||
|
function closeAbout() { document.getElementById('about-modal').style.display = 'none'; }
|
||||||
|
|
||||||
|
function formatTime(ts) {
|
||||||
|
const d = new Date(ts), now = new Date();
|
||||||
|
const diff = Math.floor((now - d) / 86400000);
|
||||||
|
if (diff === 0) return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||||
|
if (diff === 1) return 'Yesterday';
|
||||||
|
if (diff < 7) return d.toLocaleDateString([], { weekday: 'short' });
|
||||||
|
return d.toLocaleDateString([], { month: 'short', day: 'numeric' });
|
||||||
|
}
|
||||||
|
|
||||||
|
setInterval(() => { if (apiKey) { loadMessages(); } }, 15000);
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
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)
|
||||||
|
add(Manifest.permission.READ_CONTACTS)
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package sh.sar.textpipe.contacts
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.Uri
|
||||||
|
import android.provider.ContactsContract
|
||||||
|
|
||||||
|
class ContactsHelper(private val context: Context) {
|
||||||
|
|
||||||
|
private val cache = mutableMapOf<String, String?>()
|
||||||
|
|
||||||
|
fun getContactName(phoneNumber: String): String? {
|
||||||
|
// Check cache first
|
||||||
|
cache[phoneNumber]?.let { return it }
|
||||||
|
|
||||||
|
val name = lookupContactName(phoneNumber)
|
||||||
|
cache[phoneNumber] = name
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun lookupContactName(phoneNumber: String): String? {
|
||||||
|
return try {
|
||||||
|
val uri = Uri.withAppendedPath(
|
||||||
|
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
|
||||||
|
Uri.encode(phoneNumber)
|
||||||
|
)
|
||||||
|
|
||||||
|
context.contentResolver.query(
|
||||||
|
uri,
|
||||||
|
arrayOf(ContactsContract.PhoneLookup.DISPLAY_NAME),
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null
|
||||||
|
)?.use { cursor ->
|
||||||
|
if (cursor.moveToFirst()) {
|
||||||
|
cursor.getString(0)
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clearCache() {
|
||||||
|
cache.clear()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
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<SmsMessageEntity>
|
||||||
|
|
||||||
|
@Query("SELECT * FROM sms_messages WHERE type = :type ORDER BY timestamp DESC")
|
||||||
|
suspend fun getByType(type: String): List<SmsMessageEntity>
|
||||||
|
|
||||||
|
@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<SmsMessageEntity>
|
||||||
|
|
||||||
|
@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
|
||||||
|
|
||||||
|
@Query("SELECT * FROM sms_messages WHERE simSlot = :simSlot ORDER BY timestamp DESC")
|
||||||
|
suspend fun getBySimSlot(simSlot: Int): List<SmsMessageEntity>
|
||||||
|
|
||||||
|
@Query("SELECT * FROM sms_messages WHERE simSlot = :simSlot AND type = :type ORDER BY timestamp DESC")
|
||||||
|
suspend fun getBySimSlotAndType(simSlot: Int, type: String): List<SmsMessageEntity>
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
)
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package sh.sar.textpipe.data.model
|
||||||
|
|
||||||
|
import kotlinx.serialization.KSerializer
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import kotlinx.serialization.SerializationException
|
||||||
|
import kotlinx.serialization.descriptors.PrimitiveKind
|
||||||
|
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
|
||||||
|
import kotlinx.serialization.descriptors.SerialDescriptor
|
||||||
|
import kotlinx.serialization.encoding.Decoder
|
||||||
|
import kotlinx.serialization.encoding.Encoder
|
||||||
|
import kotlinx.serialization.json.JsonArray
|
||||||
|
import kotlinx.serialization.json.JsonDecoder
|
||||||
|
import kotlinx.serialization.json.JsonEncoder
|
||||||
|
import kotlinx.serialization.json.JsonPrimitive
|
||||||
|
import kotlinx.serialization.json.jsonPrimitive
|
||||||
|
|
||||||
|
object StringOrListSerializer : KSerializer<List<String>> {
|
||||||
|
|
||||||
|
override val descriptor: SerialDescriptor =
|
||||||
|
PrimitiveSerialDescriptor("StringOrList", PrimitiveKind.STRING)
|
||||||
|
|
||||||
|
override fun deserialize(decoder: Decoder): List<String> {
|
||||||
|
val jsonDecoder = decoder as? JsonDecoder
|
||||||
|
?: throw SerializationException("This serializer only supports JSON")
|
||||||
|
|
||||||
|
return when (val element = jsonDecoder.decodeJsonElement()) {
|
||||||
|
is JsonPrimitive -> listOf(element.content)
|
||||||
|
is JsonArray -> element.map { it.jsonPrimitive.content }
|
||||||
|
else -> throw SerializationException(
|
||||||
|
"'to' must be a phone number string or an array of phone numbers"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun serialize(
|
||||||
|
encoder: Encoder,
|
||||||
|
value: List<String>
|
||||||
|
) {
|
||||||
|
val jsonEncoder = encoder as? JsonEncoder
|
||||||
|
?: throw SerializationException("This serializer only supports JSON")
|
||||||
|
|
||||||
|
jsonEncoder.encodeJsonElement(
|
||||||
|
JsonArray(value.map { JsonPrimitive(it) })
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class SendSmsRequest(
|
||||||
|
@Serializable(with = StringOrListSerializer::class)
|
||||||
|
val to: List<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 contactName: String? = null,
|
||||||
|
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<SimInfo>
|
||||||
|
)
|
||||||
|
|
||||||
|
@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<SmsMessageResponse>,
|
||||||
|
val total: Int
|
||||||
|
)
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package sh.sar.textpipe.data.repository
|
||||||
|
|
||||||
|
import sh.sar.textpipe.contacts.ContactsHelper
|
||||||
|
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,
|
||||||
|
private val contactsHelper: ContactsHelper
|
||||||
|
) {
|
||||||
|
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 getMessagesBySimSlot(simSlot: Int, type: String? = null): List<SmsMessageResponse> {
|
||||||
|
val messages = if (type != null) {
|
||||||
|
dao.getBySimSlotAndType(simSlot, type)
|
||||||
|
} else {
|
||||||
|
dao.getBySimSlot(simSlot)
|
||||||
|
}
|
||||||
|
return messages.map { it.toResponse() }
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun getMessageById(id: Long, simSlot: Int): SmsMessageResponse? {
|
||||||
|
val message = dao.getById(id) ?: return null
|
||||||
|
// Only return if message belongs to this SIM slot
|
||||||
|
if (message.simSlot != simSlot) return null
|
||||||
|
return message.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,
|
||||||
|
contactName = contactsHelper.getContactName(address),
|
||||||
|
text = text,
|
||||||
|
simSlot = simSlot,
|
||||||
|
status = status,
|
||||||
|
timestamp = timestamp,
|
||||||
|
deliveryTimestamp = deliveryTimestamp
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
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<Boolean, String> = 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")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Allow binding to privileged ports by lowering the unprivileged port start.
|
||||||
|
* This uses sysctl to set net.ipv4.ip_unprivileged_port_start to the specified port.
|
||||||
|
*/
|
||||||
|
suspend fun allowPrivilegedPort(port: Int): Boolean = withContext(Dispatchers.IO) {
|
||||||
|
withTimeoutOrNull(5000L) {
|
||||||
|
try {
|
||||||
|
val command = "sysctl -w net.ipv4.ip_unprivileged_port_start=$port"
|
||||||
|
val process = Runtime.getRuntime().exec(arrayOf("su", "-c", command))
|
||||||
|
val completed = process.waitFor(4, TimeUnit.SECONDS)
|
||||||
|
if (completed) {
|
||||||
|
val success = process.exitValue() == 0
|
||||||
|
if (success) {
|
||||||
|
android.util.Log.i("RootManager", "Allowed binding to ports >= $port")
|
||||||
|
}
|
||||||
|
success
|
||||||
|
} else {
|
||||||
|
process.destroyForcibly()
|
||||||
|
false
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
android.util.Log.e("RootManager", "Failed to allow privileged port", e)
|
||||||
|
false
|
||||||
|
}
|
||||||
|
} ?: false
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reset the unprivileged port start back to default (1024).
|
||||||
|
*/
|
||||||
|
suspend fun resetPrivilegedPorts(): Boolean = withContext(Dispatchers.IO) {
|
||||||
|
withTimeoutOrNull(5000L) {
|
||||||
|
try {
|
||||||
|
val command = "sysctl -w net.ipv4.ip_unprivileged_port_start=1024"
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
package sh.sar.textpipe.server
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
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.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.server.routes.webUIRoutes
|
||||||
|
import sh.sar.textpipe.sim.SimManager
|
||||||
|
import java.net.ServerSocket
|
||||||
|
|
||||||
|
sealed class ServerStartResult {
|
||||||
|
data object Success : ServerStartResult()
|
||||||
|
data class Error(val message: String) : ServerStartResult()
|
||||||
|
}
|
||||||
|
|
||||||
|
class TextpipeServer(
|
||||||
|
private val context: Context,
|
||||||
|
private val smsRepository: SmsRepository,
|
||||||
|
private val simManager: SimManager
|
||||||
|
) {
|
||||||
|
companion object {
|
||||||
|
private const val TAG = "TextpipeServer"
|
||||||
|
}
|
||||||
|
|
||||||
|
private var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null
|
||||||
|
private var startTime: Long = 0
|
||||||
|
private var currentPort: Int = 8080
|
||||||
|
@Volatile
|
||||||
|
private var lastError: Throwable? = null
|
||||||
|
|
||||||
|
suspend fun start(port: Int): ServerStartResult {
|
||||||
|
// 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 ServerStartResult.Error("Port $port is already in use. Try a different port or wait a moment.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 ServerStartResult.Error("Server error: ${lastError?.message ?: "Unknown error"}")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 ServerStartResult.Error("Server failed to bind to port $port")
|
||||||
|
}
|
||||||
|
|
||||||
|
Log.i(TAG, "Server started on port $port")
|
||||||
|
ServerStartResult.Success
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "Failed to start server on port $port", e)
|
||||||
|
server?.stop(100, 100)
|
||||||
|
server = null
|
||||||
|
ServerStartResult.Error("Failed to start: ${e.message ?: "Unknown error"}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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<Throwable> { 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 {
|
||||||
|
// Web UI routes (served from assets)
|
||||||
|
webUIRoutes(context)
|
||||||
|
|
||||||
|
// API routes
|
||||||
|
statusRoutes(simManager)
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
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<String>("ApiKey")
|
||||||
|
val SimSlotAttributeKey = AttributeKey<Int>("SimSlot")
|
||||||
|
val SubscriptionIdAttributeKey = AttributeKey<Int>("SubscriptionId")
|
||||||
|
|
||||||
|
fun Application.configureAuth(simManager: SimManager) {
|
||||||
|
intercept(ApplicationCallPipeline.Plugins) {
|
||||||
|
val path = call.request.local.uri
|
||||||
|
|
||||||
|
// Skip auth for web UI
|
||||||
|
if (path == "/" || path.startsWith("/assets") || !path.startsWith("/api/")) {
|
||||||
|
return@intercept
|
||||||
|
}
|
||||||
|
|
||||||
|
// All /api/* endpoints require auth
|
||||||
|
|
||||||
|
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 <key>
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
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
|
||||||
|
import sh.sar.textpipe.server.auth.SimSlotAttributeKey
|
||||||
|
|
||||||
|
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<SendSmsRequest>()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
call.respond(HttpStatusCode.BadRequest, ErrorResponse("Invalid request body: ${e.message}"))
|
||||||
|
return@post
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate request
|
||||||
|
if (request.to.isEmpty()) {
|
||||||
|
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 responses = request.to.mapNotNull { number ->
|
||||||
|
smsRepository.sendSms(number, request.text, apiKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (responses.isEmpty()) {
|
||||||
|
call.respond(
|
||||||
|
HttpStatusCode.InternalServerError,
|
||||||
|
ErrorResponse("Failed to send SMS")
|
||||||
|
)
|
||||||
|
return@post
|
||||||
|
}
|
||||||
|
|
||||||
|
call.respond(HttpStatusCode.OK, responses)
|
||||||
|
}
|
||||||
|
|
||||||
|
get("/api/sms/messages") {
|
||||||
|
val simSlot = call.attributes.getOrNull(SimSlotAttributeKey)
|
||||||
|
if (simSlot == null) {
|
||||||
|
call.respond(HttpStatusCode.Unauthorized, ErrorResponse("Missing API key"))
|
||||||
|
return@get
|
||||||
|
}
|
||||||
|
|
||||||
|
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.getMessagesBySimSlot(simSlot, type)
|
||||||
|
val response = MessagesResponse(
|
||||||
|
messages = messages,
|
||||||
|
total = messages.size
|
||||||
|
)
|
||||||
|
call.respond(response)
|
||||||
|
}
|
||||||
|
|
||||||
|
get("/api/sms/status/{id}") {
|
||||||
|
val simSlot = call.attributes.getOrNull(SimSlotAttributeKey)
|
||||||
|
if (simSlot == null) {
|
||||||
|
call.respond(HttpStatusCode.Unauthorized, ErrorResponse("Missing API key"))
|
||||||
|
return@get
|
||||||
|
}
|
||||||
|
|
||||||
|
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, simSlot)
|
||||||
|
if (message == null) {
|
||||||
|
call.respond(HttpStatusCode.NotFound, ErrorResponse("Message not found"))
|
||||||
|
return@get
|
||||||
|
}
|
||||||
|
|
||||||
|
call.respond(message)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package sh.sar.textpipe.server.routes
|
||||||
|
|
||||||
|
import io.ktor.http.*
|
||||||
|
import io.ktor.server.response.*
|
||||||
|
import io.ktor.server.routing.*
|
||||||
|
import sh.sar.textpipe.data.model.ErrorResponse
|
||||||
|
import sh.sar.textpipe.data.model.SimInfo
|
||||||
|
import sh.sar.textpipe.server.auth.ApiKeyAttributeKey
|
||||||
|
import sh.sar.textpipe.sim.SimManager
|
||||||
|
|
||||||
|
fun Route.statusRoutes(simManager: SimManager) {
|
||||||
|
get("/api/status") {
|
||||||
|
val apiKey = call.attributes.getOrNull(ApiKeyAttributeKey)
|
||||||
|
if (apiKey == null) {
|
||||||
|
call.respond(HttpStatusCode.Unauthorized, ErrorResponse("Missing API key"))
|
||||||
|
return@get
|
||||||
|
}
|
||||||
|
|
||||||
|
val simInfo = simManager.getSimInfoForApiKey(apiKey)
|
||||||
|
if (simInfo == null) {
|
||||||
|
call.respond(HttpStatusCode.NotFound, ErrorResponse("SIM not found"))
|
||||||
|
return@get
|
||||||
|
}
|
||||||
|
|
||||||
|
call.respond(simInfo)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package sh.sar.textpipe.server.routes
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import io.ktor.http.*
|
||||||
|
import io.ktor.server.response.*
|
||||||
|
import io.ktor.server.routing.*
|
||||||
|
import java.io.IOException
|
||||||
|
|
||||||
|
fun Route.webUIRoutes(context: Context) {
|
||||||
|
get("/") {
|
||||||
|
serveAsset(context, call, "index.html", ContentType.Text.Html)
|
||||||
|
}
|
||||||
|
|
||||||
|
get("/assets/{file}") {
|
||||||
|
val fileName = call.parameters["file"] ?: return@get
|
||||||
|
val contentType = getContentType(fileName)
|
||||||
|
serveAsset(context, call, "assets/$fileName", contentType)
|
||||||
|
}
|
||||||
|
|
||||||
|
get("/favicon.svg") {
|
||||||
|
serveAsset(context, call, "favicon.svg", ContentType.Image.SVG)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun serveAsset(
|
||||||
|
context: Context,
|
||||||
|
call: io.ktor.server.application.ApplicationCall,
|
||||||
|
path: String,
|
||||||
|
contentType: ContentType
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
val inputStream = context.assets.open("webui/$path")
|
||||||
|
val bytes = inputStream.readBytes()
|
||||||
|
inputStream.close()
|
||||||
|
call.respondBytes(bytes, contentType)
|
||||||
|
} catch (e: IOException) {
|
||||||
|
call.respond(HttpStatusCode.NotFound, "File not found: $path")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getContentType(fileName: String): ContentType {
|
||||||
|
return when {
|
||||||
|
fileName.endsWith(".js") -> ContentType.Application.JavaScript
|
||||||
|
fileName.endsWith(".css") -> ContentType.Text.CSS
|
||||||
|
fileName.endsWith(".html") -> ContentType.Text.Html
|
||||||
|
fileName.endsWith(".svg") -> ContentType.Image.SVG
|
||||||
|
fileName.endsWith(".png") -> ContentType.Image.PNG
|
||||||
|
fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") -> ContentType.Image.JPEG
|
||||||
|
fileName.endsWith(".json") -> ContentType.Application.Json
|
||||||
|
else -> ContentType.Application.OctetStream
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package sh.sar.textpipe.service
|
||||||
|
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.util.Log
|
||||||
|
|
||||||
|
class BootReceiver : BroadcastReceiver() {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val TAG = "BootReceiver"
|
||||||
|
private const val PREFS_NAME = "textpipe_settings"
|
||||||
|
private const val KEY_AUTO_START = "auto_start"
|
||||||
|
private const val START_DELAY_MS = 5000L // Wait 5 seconds after boot
|
||||||
|
|
||||||
|
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) {
|
||||||
|
val action = intent.action
|
||||||
|
if (action != Intent.ACTION_BOOT_COMPLETED &&
|
||||||
|
action != Intent.ACTION_LOCKED_BOOT_COMPLETED &&
|
||||||
|
action != "android.intent.action.QUICKBOOT_POWERON" &&
|
||||||
|
action != "com.htc.intent.action.QUICKBOOT_POWERON") {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
Log.i(TAG, "Boot completed received: $action")
|
||||||
|
|
||||||
|
if (isAutoStartEnabled(context)) {
|
||||||
|
// Delay start slightly to let system settle
|
||||||
|
Handler(Looper.getMainLooper()).postDelayed({
|
||||||
|
Log.i(TAG, "Starting TextpipeService after boot")
|
||||||
|
try {
|
||||||
|
TextpipeService.start(context.applicationContext)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "Failed to start service on boot", e)
|
||||||
|
}
|
||||||
|
}, START_DELAY_MS)
|
||||||
|
} else {
|
||||||
|
Log.i(TAG, "Auto-start is disabled, not starting service")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<PendingIntent>()
|
||||||
|
val deliveryIntents = ArrayList<PendingIntent>()
|
||||||
|
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
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
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.Handler
|
||||||
|
import android.os.IBinder
|
||||||
|
import android.os.Looper
|
||||||
|
import android.util.Log
|
||||||
|
import android.widget.Toast
|
||||||
|
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.GlobalScope
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import sh.sar.textpipe.MainActivity
|
||||||
|
import sh.sar.textpipe.TextpipeApplication
|
||||||
|
import sh.sar.textpipe.contacts.ContactsHelper
|
||||||
|
import sh.sar.textpipe.data.repository.SmsRepository
|
||||||
|
import sh.sar.textpipe.root.RootManager
|
||||||
|
import sh.sar.textpipe.server.ServerStartResult
|
||||||
|
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_SSL_ENABLED = "ssl_enabled"
|
||||||
|
private const val KEY_SSL_CERT_PATH = "ssl_cert_path"
|
||||||
|
private const val KEY_SSL_KEY_PATH = "ssl_key_path"
|
||||||
|
private const val DEFAULT_PORT = 8080
|
||||||
|
private const val ACTION_STOP = "sh.sar.textpipe.STOP"
|
||||||
|
|
||||||
|
private val _isRunning = MutableStateFlow(false)
|
||||||
|
val isRunning: StateFlow<Boolean> = _isRunning
|
||||||
|
|
||||||
|
private val _serverPort = MutableStateFlow(DEFAULT_PORT)
|
||||||
|
val serverPort: StateFlow<Int> = _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 isSslEnabled(context: Context): Boolean {
|
||||||
|
val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||||
|
return prefs.getBoolean(KEY_SSL_ENABLED, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setSslEnabled(context: Context, enabled: Boolean) {
|
||||||
|
val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||||
|
prefs.edit().putBoolean(KEY_SSL_ENABLED, enabled).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getSslCertPath(context: Context): String {
|
||||||
|
val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||||
|
return prefs.getString(KEY_SSL_CERT_PATH, "") ?: ""
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setSslCertPath(context: Context, path: String) {
|
||||||
|
val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||||
|
prefs.edit().putString(KEY_SSL_CERT_PATH, path).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getSslKeyPath(context: Context): String {
|
||||||
|
val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||||
|
return prefs.getString(KEY_SSL_KEY_PATH, "") ?: ""
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setSslKeyPath(context: Context, path: String) {
|
||||||
|
val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||||
|
prefs.edit().putString(KEY_SSL_KEY_PATH, path).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 usedPrivilegedPort = false
|
||||||
|
|
||||||
|
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()
|
||||||
|
|
||||||
|
val contactsHelper = ContactsHelper(this)
|
||||||
|
smsRepository = SmsRepository(dao, smsSender, simManager, contactsHelper)
|
||||||
|
textpipeServer = TextpipeServer(this, 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(Dispatchers.IO) {
|
||||||
|
// If port < 1024, we need root to allow binding
|
||||||
|
if (port < 1024) {
|
||||||
|
Log.i(TAG, "Port $port requires root access")
|
||||||
|
val allowed = RootManager.allowPrivilegedPort(port)
|
||||||
|
if (allowed) {
|
||||||
|
usedPrivilegedPort = true
|
||||||
|
Log.i(TAG, "Privileged port access granted for port $port")
|
||||||
|
} else {
|
||||||
|
updateNotification("Error: Root required for port $port")
|
||||||
|
showToast("Root access required for port $port")
|
||||||
|
Log.e(TAG, "Failed to get root access for port $port")
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start HTTP server
|
||||||
|
when (val result = textpipeServer?.start(port)) {
|
||||||
|
is ServerStartResult.Success -> {
|
||||||
|
_isRunning.value = true
|
||||||
|
updateNotification("Running on port $port")
|
||||||
|
showToast("Server started on port $port")
|
||||||
|
Log.i(TAG, "Server started successfully on port $port")
|
||||||
|
}
|
||||||
|
is ServerStartResult.Error -> {
|
||||||
|
updateNotification("Error: ${result.message}")
|
||||||
|
showToast(result.message)
|
||||||
|
Log.e(TAG, "Failed to start server: ${result.message}")
|
||||||
|
}
|
||||||
|
null -> {
|
||||||
|
updateNotification("Error: Server not initialized")
|
||||||
|
showToast("Server not initialized")
|
||||||
|
Log.e(TAG, "Server is null, cannot start")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return START_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
Log.i(TAG, "Service onDestroy")
|
||||||
|
|
||||||
|
// Reset privileged port setting if we used it
|
||||||
|
if (usedPrivilegedPort) {
|
||||||
|
GlobalScope.launch(Dispatchers.IO) {
|
||||||
|
RootManager.resetPrivilegedPorts()
|
||||||
|
}
|
||||||
|
usedPrivilegedPort = false
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showToast(message: String) {
|
||||||
|
Handler(Looper.getMainLooper()).post {
|
||||||
|
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
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<SimSlotInfo> = emptyList()
|
||||||
|
|
||||||
|
fun refreshSims(): List<SimSlotInfo> {
|
||||||
|
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<Int, String> {
|
||||||
|
return cachedSims.associate { it.slotIndex to it.apiKey }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isValidApiKey(apiKey: String): Boolean {
|
||||||
|
return cachedSims.any { it.apiKey == apiKey }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getSimInfoList(): List<SimInfo> {
|
||||||
|
return cachedSims.map { sim ->
|
||||||
|
SimInfo(
|
||||||
|
slot = sim.slotIndex,
|
||||||
|
carrier = sim.carrierName,
|
||||||
|
number = sim.phoneNumber,
|
||||||
|
hasApiKey = true
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getSimInfoForApiKey(apiKey: String): SimInfo? {
|
||||||
|
val sim = cachedSims.find { it.apiKey == apiKey } ?: return null
|
||||||
|
return SimInfo(
|
||||||
|
slot = sim.slotIndex,
|
||||||
|
carrier = sim.carrierName,
|
||||||
|
number = sim.phoneNumber,
|
||||||
|
hasApiKey = true
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getCachedSims(): List<SimSlotInfo> = 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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,626 @@
|
|||||||
|
package sh.sar.textpipe.ui
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.Uri
|
||||||
|
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.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.text.style.TextDecoration
|
||||||
|
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 autoStartEnabled by viewModel.autoStartEnabled.collectAsState()
|
||||||
|
val isBatteryOptimized by viewModel.isBatteryOptimized.collectAsState()
|
||||||
|
val sslEnabled by viewModel.sslEnabled.collectAsState()
|
||||||
|
val sslCertPath by viewModel.sslCertPath.collectAsState()
|
||||||
|
val sslKeyPath by viewModel.sslKeyPath.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)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Server Configuration
|
||||||
|
Text(
|
||||||
|
text = "Server Configuration",
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
|
||||||
|
// Port Configuration Card
|
||||||
|
PortConfigCard(
|
||||||
|
portInput = portInput,
|
||||||
|
isRootAvailable = isRootAvailable,
|
||||||
|
isRunning = isRunning,
|
||||||
|
onPortChange = { viewModel.setPort(it) },
|
||||||
|
onApply = { viewModel.applyPortSettings() }
|
||||||
|
)
|
||||||
|
|
||||||
|
// SSL Configuration Card
|
||||||
|
SslConfigCard(
|
||||||
|
sslEnabled = sslEnabled,
|
||||||
|
certPath = sslCertPath,
|
||||||
|
keyPath = sslKeyPath,
|
||||||
|
isRunning = isRunning,
|
||||||
|
onSslEnabledChange = { viewModel.setSslEnabled(it) },
|
||||||
|
onCertPathChange = { viewModel.setSslCertPath(it) },
|
||||||
|
onKeyPathChange = { viewModel.setSslKeyPath(it) },
|
||||||
|
onApply = { viewModel.applySslSettings() }
|
||||||
|
)
|
||||||
|
|
||||||
|
// Settings
|
||||||
|
Text(
|
||||||
|
text = "Settings",
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
|
||||||
|
// Other Settings Card
|
||||||
|
SettingsCard(
|
||||||
|
autoStartEnabled = autoStartEnabled,
|
||||||
|
isBatteryOptimized = isBatteryOptimized,
|
||||||
|
onAutoStartChange = { viewModel.setAutoStart(it) },
|
||||||
|
onRequestBatteryExemption = {
|
||||||
|
activity?.let { viewModel.requestBatteryOptimizationExemption(it) }
|
||||||
|
},
|
||||||
|
onRefreshBatteryStatus = { viewModel.refreshBatteryOptimizationStatus() }
|
||||||
|
)
|
||||||
|
|
||||||
|
// About
|
||||||
|
Text(
|
||||||
|
text = "About",
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
|
||||||
|
AboutCard()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@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,
|
||||||
|
isRootAvailable: Boolean,
|
||||||
|
isRunning: Boolean,
|
||||||
|
onPortChange: (String) -> Unit,
|
||||||
|
onApply: () -> Unit
|
||||||
|
) {
|
||||||
|
val port = portInput.toIntOrNull() ?: 0
|
||||||
|
val needsRoot = port in 1..1023
|
||||||
|
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.padding(16.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Port",
|
||||||
|
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") },
|
||||||
|
placeholder = { Text("e.g., 80, 443, 8080") },
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
singleLine = true
|
||||||
|
)
|
||||||
|
|
||||||
|
if (needsRoot) {
|
||||||
|
Text(
|
||||||
|
text = if (isRootAvailable) {
|
||||||
|
"Port $port requires root access (available)"
|
||||||
|
} else {
|
||||||
|
"Port $port requires root access (not available)"
|
||||||
|
},
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = if (isRootAvailable) {
|
||||||
|
MaterialTheme.colorScheme.primary
|
||||||
|
} else {
|
||||||
|
MaterialTheme.colorScheme.error
|
||||||
|
},
|
||||||
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun SslConfigCard(
|
||||||
|
sslEnabled: Boolean,
|
||||||
|
certPath: String,
|
||||||
|
keyPath: String,
|
||||||
|
isRunning: Boolean,
|
||||||
|
onSslEnabledChange: (Boolean) -> Unit,
|
||||||
|
onCertPathChange: (String) -> Unit,
|
||||||
|
onKeyPathChange: (String) -> Unit,
|
||||||
|
onApply: () -> Unit
|
||||||
|
) {
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.padding(16.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "SSL / HTTPS",
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
|
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
text = "Enable SSL",
|
||||||
|
style = MaterialTheme.typography.bodyLarge
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "Coming soon",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Switch(
|
||||||
|
checked = sslEnabled,
|
||||||
|
onCheckedChange = onSslEnabledChange,
|
||||||
|
enabled = false
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sslEnabled) {
|
||||||
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
|
|
||||||
|
OutlinedTextField(
|
||||||
|
value = certPath,
|
||||||
|
onValueChange = onCertPathChange,
|
||||||
|
label = { Text("Certificate Path") },
|
||||||
|
placeholder = { Text("/sdcard/cert.pem") },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
singleLine = true
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
|
||||||
|
OutlinedTextField(
|
||||||
|
value = keyPath,
|
||||||
|
onValueChange = onKeyPathChange,
|
||||||
|
label = { Text("Private Key Path") },
|
||||||
|
placeholder = { Text("/sdcard/key.pem") },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
singleLine = true
|
||||||
|
)
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = "Provide paths to PEM-encoded certificate and private key files",
|
||||||
|
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(),
|
||||||
|
enabled = certPath.isNotBlank() && keyPath.isNotBlank()
|
||||||
|
) {
|
||||||
|
Text(if (isRunning) "Apply & Restart" else "Save")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun AboutCard() {
|
||||||
|
val context = LocalContext.current
|
||||||
|
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.padding(16.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Textpipe",
|
||||||
|
style = MaterialTheme.typography.titleLarge,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = "SMS API Gateway for Android. Send and receive SMS messages via REST API with dual SIM support.",
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = "git.shihaam.dev/shihaam/textpipe",
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.primary,
|
||||||
|
textDecoration = TextDecoration.Underline,
|
||||||
|
modifier = Modifier.clickable {
|
||||||
|
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://git.shihaam.dev/shihaam/textpipe"))
|
||||||
|
context.startActivity(intent)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
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.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.os.PowerManager
|
||||||
|
import android.provider.Settings
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.lifecycle.AndroidViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
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<Boolean> = TextpipeService.isRunning
|
||||||
|
val serverPort: StateFlow<Int> = TextpipeService.serverPort
|
||||||
|
|
||||||
|
private val _simSlots = MutableStateFlow<List<SimSlotInfo>>(emptyList())
|
||||||
|
val simSlots: StateFlow<List<SimSlotInfo>> = _simSlots.asStateFlow()
|
||||||
|
|
||||||
|
private val _isRootAvailable = MutableStateFlow(false)
|
||||||
|
val isRootAvailable: StateFlow<Boolean> = _isRootAvailable.asStateFlow()
|
||||||
|
|
||||||
|
private val _portInput = MutableStateFlow(TextpipeService.getConfiguredPort(application).toString())
|
||||||
|
val portInput: StateFlow<String> = _portInput.asStateFlow()
|
||||||
|
|
||||||
|
private val _autoStartEnabled = MutableStateFlow(BootReceiver.isAutoStartEnabled(application))
|
||||||
|
val autoStartEnabled: StateFlow<Boolean> = _autoStartEnabled.asStateFlow()
|
||||||
|
|
||||||
|
private val _isBatteryOptimized = MutableStateFlow(true)
|
||||||
|
val isBatteryOptimized: StateFlow<Boolean> = _isBatteryOptimized.asStateFlow()
|
||||||
|
|
||||||
|
private val _sslEnabled = MutableStateFlow(TextpipeService.isSslEnabled(application))
|
||||||
|
val sslEnabled: StateFlow<Boolean> = _sslEnabled.asStateFlow()
|
||||||
|
|
||||||
|
private val _sslCertPath = MutableStateFlow(TextpipeService.getSslCertPath(application))
|
||||||
|
val sslCertPath: StateFlow<String> = _sslCertPath.asStateFlow()
|
||||||
|
|
||||||
|
private val _sslKeyPath = MutableStateFlow(TextpipeService.getSslKeyPath(application))
|
||||||
|
val sslKeyPath: StateFlow<String> = _sslKeyPath.asStateFlow()
|
||||||
|
|
||||||
|
init {
|
||||||
|
viewModelScope.launch {
|
||||||
|
refreshSimInfo()
|
||||||
|
}
|
||||||
|
checkRootAvailability()
|
||||||
|
checkBatteryOptimization()
|
||||||
|
}
|
||||||
|
|
||||||
|
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<Application>().getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||||
|
_isBatteryOptimized.value = !powerManager.isIgnoringBatteryOptimizations(
|
||||||
|
getApplication<Application>().packageName
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setPort(port: String) {
|
||||||
|
_portInput.value = port
|
||||||
|
}
|
||||||
|
|
||||||
|
fun applyPortSettings() {
|
||||||
|
val port = _portInput.value.toIntOrNull() ?: return
|
||||||
|
if (port !in 1..65535) return
|
||||||
|
|
||||||
|
TextpipeService.setConfiguredPort(getApplication(), port)
|
||||||
|
|
||||||
|
// Restart service if running, otherwise just save
|
||||||
|
if (isServerRunning.value) {
|
||||||
|
stopServer()
|
||||||
|
// Small delay to let service stop before restarting
|
||||||
|
viewModelScope.launch {
|
||||||
|
delay(500)
|
||||||
|
TextpipeService.start(getApplication())
|
||||||
|
showToast("Settings applied, server restarting...")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
showToast("Settings saved")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun startServer() {
|
||||||
|
savePortSettings()
|
||||||
|
TextpipeService.start(getApplication())
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun savePortSettings() {
|
||||||
|
val port = _portInput.value.toIntOrNull() ?: return
|
||||||
|
if (port !in 1..65535) return
|
||||||
|
TextpipeService.setConfiguredPort(getApplication(), port)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stopServer() {
|
||||||
|
TextpipeService.stop(getApplication())
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showToast(message: String) {
|
||||||
|
Handler(Looper.getMainLooper()).post {
|
||||||
|
Toast.makeText(getApplication(), message, Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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()
|
||||||
|
showToast("API key regenerated for SIM ${slotIndex + 1}")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setSslEnabled(enabled: Boolean) {
|
||||||
|
_sslEnabled.value = enabled
|
||||||
|
TextpipeService.setSslEnabled(getApplication(), enabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setSslCertPath(path: String) {
|
||||||
|
_sslCertPath.value = path
|
||||||
|
TextpipeService.setSslCertPath(getApplication(), path)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setSslKeyPath(path: String) {
|
||||||
|
_sslKeyPath.value = path
|
||||||
|
TextpipeService.setSslKeyPath(getApplication(), path)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun applySslSettings() {
|
||||||
|
// Restart service if running to apply SSL changes
|
||||||
|
if (isServerRunning.value) {
|
||||||
|
stopServer()
|
||||||
|
viewModelScope.launch {
|
||||||
|
delay(500)
|
||||||
|
TextpipeService.start(getApplication())
|
||||||
|
showToast("SSL settings applied, server restarting...")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
showToast("SSL settings saved")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
@@ -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
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
)
|
||||||
|
*/
|
||||||
|
)
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="108dp"
|
||||||
|
android:height="108dp"
|
||||||
|
android:viewportWidth="108"
|
||||||
|
android:viewportHeight="108">
|
||||||
|
<path
|
||||||
|
android:fillColor="#3DDC84"
|
||||||
|
android:pathData="M0,0h108v108h-108z" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M9,0L9,108"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M19,0L19,108"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M29,0L29,108"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M39,0L39,108"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M49,0L49,108"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M59,0L59,108"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M69,0L69,108"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M79,0L79,108"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M89,0L89,108"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M99,0L99,108"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M0,9L108,9"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M0,19L108,19"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M0,29L108,29"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M0,39L108,39"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M0,49L108,49"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M0,59L108,59"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M0,69L108,69"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M0,79L108,79"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M0,89L108,89"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M0,99L108,99"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M19,29L89,29"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M19,39L89,39"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M19,49L89,49"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M19,59L89,59"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M19,69L89,69"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M19,79L89,79"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M29,19L29,89"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M39,19L39,89"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M49,19L49,89"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M59,19L59,89"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M69,19L69,89"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M79,19L79,89"
|
||||||
|
android:strokeWidth="0.8"
|
||||||
|
android:strokeColor="#33FFFFFF" />
|
||||||
|
</vector>
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:aapt="http://schemas.android.com/aapt"
|
||||||
|
android:width="108dp"
|
||||||
|
android:height="108dp"
|
||||||
|
android:viewportWidth="108"
|
||||||
|
android:viewportHeight="108">
|
||||||
|
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
|
||||||
|
<aapt:attr name="android:fillColor">
|
||||||
|
<gradient
|
||||||
|
android:endX="85.84757"
|
||||||
|
android:endY="92.4963"
|
||||||
|
android:startX="42.9492"
|
||||||
|
android:startY="49.59793"
|
||||||
|
android:type="linear">
|
||||||
|
<item
|
||||||
|
android:color="#44000000"
|
||||||
|
android:offset="0.0" />
|
||||||
|
<item
|
||||||
|
android:color="#00000000"
|
||||||
|
android:offset="1.0" />
|
||||||
|
</gradient>
|
||||||
|
</aapt:attr>
|
||||||
|
</path>
|
||||||
|
<path
|
||||||
|
android:fillColor="#FFFFFF"
|
||||||
|
android:fillType="nonZero"
|
||||||
|
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
|
||||||
|
android:strokeWidth="1"
|
||||||
|
android:strokeColor="#00000000" />
|
||||||
|
</vector>
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<background android:drawable="@drawable/ic_launcher_background" />
|
||||||
|
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||||
|
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
|
||||||
|
</adaptive-icon>
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<background android:drawable="@drawable/ic_launcher_background" />
|
||||||
|
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||||
|
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
|
||||||
|
</adaptive-icon>
|
||||||
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 2.8 KiB |
|
After Width: | Height: | Size: 982 B |
|
After Width: | Height: | Size: 1.7 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 3.8 KiB |
|
After Width: | Height: | Size: 2.8 KiB |
|
After Width: | Height: | Size: 5.8 KiB |
|
After Width: | Height: | Size: 3.8 KiB |
|
After Width: | Height: | Size: 7.6 KiB |
@@ -0,0 +1,10 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<color name="purple_200">#FFBB86FC</color>
|
||||||
|
<color name="purple_500">#FF6200EE</color>
|
||||||
|
<color name="purple_700">#FF3700B3</color>
|
||||||
|
<color name="teal_200">#FF03DAC5</color>
|
||||||
|
<color name="teal_700">#FF018786</color>
|
||||||
|
<color name="black">#FF000000</color>
|
||||||
|
<color name="white">#FFFFFFFF</color>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<resources>
|
||||||
|
<string name="app_name">Textpipe</string>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
|
||||||
|
<style name="Theme.Textpipe" parent="android:Theme.Material.Light.NoActionBar" />
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?><!--
|
||||||
|
Sample backup rules file; uncomment and customize as necessary.
|
||||||
|
See https://developer.android.com/guide/topics/data/autobackup
|
||||||
|
for details.
|
||||||
|
Note: This file is ignored for devices older than API 31
|
||||||
|
See https://developer.android.com/about/versions/12/backup-restore
|
||||||
|
-->
|
||||||
|
<full-backup-content>
|
||||||
|
<!--
|
||||||
|
<include domain="sharedpref" path="."/>
|
||||||
|
<exclude domain="sharedpref" path="device.xml"/>
|
||||||
|
-->
|
||||||
|
</full-backup-content>
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?><!--
|
||||||
|
Sample data extraction rules file; uncomment and customize as necessary.
|
||||||
|
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
|
||||||
|
for details.
|
||||||
|
-->
|
||||||
|
<data-extraction-rules>
|
||||||
|
<cloud-backup>
|
||||||
|
<!-- TODO: Use <include> and <exclude> to control what is backed up.
|
||||||
|
<include .../>
|
||||||
|
<exclude .../>
|
||||||
|
-->
|
||||||
|
</cloud-backup>
|
||||||
|
<!--
|
||||||
|
<device-transfer>
|
||||||
|
<include .../>
|
||||||
|
<exclude .../>
|
||||||
|
</device-transfer>
|
||||||
|
-->
|
||||||
|
</data-extraction-rules>
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package sh.sar.textpipe
|
||||||
|
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
import org.junit.Assert.*
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example local unit test, which will execute on the development machine (host).
|
||||||
|
*
|
||||||
|
* See [testing documentation](http://d.android.com/tools/testing).
|
||||||
|
*/
|
||||||
|
class ExampleUnitTest {
|
||||||
|
@Test
|
||||||
|
fun addition_isCorrect() {
|
||||||
|
assertEquals(4, 2 + 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
||||||
|
plugins {
|
||||||
|
alias(libs.plugins.android.application) apply false
|
||||||
|
alias(libs.plugins.kotlin.compose) apply false
|
||||||
|
alias(libs.plugins.kotlin.serialization) apply false
|
||||||
|
alias(libs.plugins.ksp) apply false
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Project-wide Gradle settings.
|
||||||
|
# IDE (e.g. Android Studio) users:
|
||||||
|
# Gradle settings configured through the IDE *will override*
|
||||||
|
# any settings specified in this file.
|
||||||
|
# For more details on how to configure your build environment visit
|
||||||
|
# http://www.gradle.org/docs/current/userguide/build_environment.html
|
||||||
|
# Specifies the JVM arguments used for the daemon process.
|
||||||
|
# The setting is particularly useful for tweaking memory settings.
|
||||||
|
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||||
|
# When configured, Gradle will run in incubating parallel mode.
|
||||||
|
# This option should only be used with decoupled projects. For more details, visit
|
||||||
|
# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects
|
||||||
|
# org.gradle.parallel=true
|
||||||
|
# AndroidX package structure to make it clearer which packages are bundled with the
|
||||||
|
# Android operating system, and which are packaged with your app's APK
|
||||||
|
# https://developer.android.com/topic/libraries/support-library/androidx-rn
|
||||||
|
android.useAndroidX=true
|
||||||
|
# Kotlin code style for this project: "official" or "obsolete":
|
||||||
|
kotlin.code.style=official
|
||||||
|
# Enables namespacing of each library's R class so that its R class includes only the
|
||||||
|
# resources declared in the library itself and none from the library's dependencies,
|
||||||
|
# thereby reducing the size of the R class for that library
|
||||||
|
android.nonTransitiveRClass=true
|
||||||
|
# Allow KSP to add Kotlin source sets (needed for Room code generation)
|
||||||
|
android.disallowKotlinSourceSets=false
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
[versions]
|
||||||
|
agp = "9.0.0"
|
||||||
|
coreKtx = "1.10.1"
|
||||||
|
junit = "4.13.2"
|
||||||
|
junitVersion = "1.1.5"
|
||||||
|
espressoCore = "3.5.1"
|
||||||
|
lifecycleRuntimeKtx = "2.6.1"
|
||||||
|
activityCompose = "1.8.0"
|
||||||
|
kotlin = "2.0.21"
|
||||||
|
composeBom = "2024.09.00"
|
||||||
|
ktor = "3.0.3"
|
||||||
|
room = "2.7.0"
|
||||||
|
kotlinxSerialization = "1.7.3"
|
||||||
|
datastorePreferences = "1.1.1"
|
||||||
|
ksp = "2.0.21-1.0.27"
|
||||||
|
coroutines = "1.9.0"
|
||||||
|
|
||||||
|
[libraries]
|
||||||
|
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
|
||||||
|
junit = { group = "junit", name = "junit", version.ref = "junit" }
|
||||||
|
androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
|
||||||
|
androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
|
||||||
|
androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" }
|
||||||
|
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
|
||||||
|
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
|
||||||
|
androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" }
|
||||||
|
androidx-compose-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
|
||||||
|
androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
|
||||||
|
androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
|
||||||
|
androidx-compose-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" }
|
||||||
|
androidx-compose-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }
|
||||||
|
androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
|
||||||
|
|
||||||
|
# Ktor server
|
||||||
|
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
|
||||||
|
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
|
||||||
|
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinxSerialization" }
|
||||||
|
|
||||||
|
# DataStore
|
||||||
|
datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastorePreferences" }
|
||||||
|
|
||||||
|
# Coroutines
|
||||||
|
kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" }
|
||||||
|
|
||||||
|
[plugins]
|
||||||
|
android-application = { id = "com.android.application", version.ref = "agp" }
|
||||||
|
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
|
||||||
|
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
|
||||||
|
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
#Thu Feb 05 01:46:34 GMT+05:00 2026
|
||||||
|
distributionBase=GRADLE_USER_HOME
|
||||||
|
distributionPath=wrapper/dists
|
||||||
|
distributionSha256Sum=a17ddd85a26b6a7f5ddb71ff8b05fc5104c0202c6e64782429790c933686c806
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-bin.zip
|
||||||
|
networkTimeout=10000
|
||||||
|
validateDistributionUrl=true
|
||||||
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
zipStorePath=wrapper/dists
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
#
|
||||||
|
# Copyright © 2015 the original authors.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
#
|
||||||
|
# Gradle start up script for POSIX generated by Gradle.
|
||||||
|
#
|
||||||
|
# Important for running:
|
||||||
|
#
|
||||||
|
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||||
|
# noncompliant, but you have some other compliant shell such as ksh or
|
||||||
|
# bash, then to run this script, type that shell name before the whole
|
||||||
|
# command line, like:
|
||||||
|
#
|
||||||
|
# ksh Gradle
|
||||||
|
#
|
||||||
|
# Busybox and similar reduced shells will NOT work, because this script
|
||||||
|
# requires all of these POSIX shell features:
|
||||||
|
# * functions;
|
||||||
|
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||||
|
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||||
|
# * compound commands having a testable exit status, especially «case»;
|
||||||
|
# * various built-in commands including «command», «set», and «ulimit».
|
||||||
|
#
|
||||||
|
# Important for patching:
|
||||||
|
#
|
||||||
|
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||||
|
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||||
|
#
|
||||||
|
# The "traditional" practice of packing multiple parameters into a
|
||||||
|
# space-separated string is a well documented source of bugs and security
|
||||||
|
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||||
|
# options in "$@", and eventually passing that to Java.
|
||||||
|
#
|
||||||
|
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||||
|
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||||
|
# see the in-line comments for details.
|
||||||
|
#
|
||||||
|
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||||
|
# Darwin, MinGW, and NonStop.
|
||||||
|
#
|
||||||
|
# (3) This script is generated from the Groovy template
|
||||||
|
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
|
# within the Gradle project.
|
||||||
|
#
|
||||||
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
|
#
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
# Attempt to set APP_HOME
|
||||||
|
|
||||||
|
# Resolve links: $0 may be a link
|
||||||
|
app_path=$0
|
||||||
|
|
||||||
|
# Need this for daisy-chained symlinks.
|
||||||
|
while
|
||||||
|
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||||
|
[ -h "$app_path" ]
|
||||||
|
do
|
||||||
|
ls=$( ls -ld "$app_path" )
|
||||||
|
link=${ls#*' -> '}
|
||||||
|
case $link in #(
|
||||||
|
/*) app_path=$link ;; #(
|
||||||
|
*) app_path=$APP_HOME$link ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# This is normally unused
|
||||||
|
# shellcheck disable=SC2034
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
|
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||||
|
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||||
|
|
||||||
|
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||||
|
MAX_FD=maximum
|
||||||
|
|
||||||
|
warn () {
|
||||||
|
echo "$*"
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
die () {
|
||||||
|
echo
|
||||||
|
echo "$*"
|
||||||
|
echo
|
||||||
|
exit 1
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
# OS specific support (must be 'true' or 'false').
|
||||||
|
cygwin=false
|
||||||
|
msys=false
|
||||||
|
darwin=false
|
||||||
|
nonstop=false
|
||||||
|
case "$( uname )" in #(
|
||||||
|
CYGWIN* ) cygwin=true ;; #(
|
||||||
|
Darwin* ) darwin=true ;; #(
|
||||||
|
MSYS* | MINGW* ) msys=true ;; #(
|
||||||
|
NONSTOP* ) nonstop=true ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
CLASSPATH="\\\"\\\""
|
||||||
|
|
||||||
|
|
||||||
|
# Determine the Java command to use to start the JVM.
|
||||||
|
if [ -n "$JAVA_HOME" ] ; then
|
||||||
|
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||||
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
|
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||||
|
else
|
||||||
|
JAVACMD=$JAVA_HOME/bin/java
|
||||||
|
fi
|
||||||
|
if [ ! -x "$JAVACMD" ] ; then
|
||||||
|
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
JAVACMD=java
|
||||||
|
if ! command -v java >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Increase the maximum file descriptors if we can.
|
||||||
|
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||||
|
case $MAX_FD in #(
|
||||||
|
max*)
|
||||||
|
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
|
warn "Could not query maximum file descriptor limit"
|
||||||
|
esac
|
||||||
|
case $MAX_FD in #(
|
||||||
|
'' | soft) :;; #(
|
||||||
|
*)
|
||||||
|
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
ulimit -n "$MAX_FD" ||
|
||||||
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Collect all arguments for the java command, stacking in reverse order:
|
||||||
|
# * args from the command line
|
||||||
|
# * the main class name
|
||||||
|
# * -classpath
|
||||||
|
# * -D...appname settings
|
||||||
|
# * --module-path (only if needed)
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||||
|
|
||||||
|
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||||
|
if "$cygwin" || "$msys" ; then
|
||||||
|
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||||
|
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||||
|
|
||||||
|
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||||
|
|
||||||
|
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||||
|
for arg do
|
||||||
|
if
|
||||||
|
case $arg in #(
|
||||||
|
-*) false ;; # don't mess with options #(
|
||||||
|
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||||
|
[ -e "$t" ] ;; #(
|
||||||
|
*) false ;;
|
||||||
|
esac
|
||||||
|
then
|
||||||
|
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||||
|
fi
|
||||||
|
# Roll the args list around exactly as many times as the number of
|
||||||
|
# args, so each arg winds up back in the position where it started, but
|
||||||
|
# possibly modified.
|
||||||
|
#
|
||||||
|
# NB: a `for` loop captures its iteration list before it begins, so
|
||||||
|
# changing the positional parameters here affects neither the number of
|
||||||
|
# iterations, nor the values presented in `arg`.
|
||||||
|
shift # remove old arg
|
||||||
|
set -- "$@" "$arg" # push replacement arg
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
|
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
|
||||||
|
# Collect all arguments for the java command:
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||||
|
# and any embedded shellness will be escaped.
|
||||||
|
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||||
|
# treated as '${Hostname}' itself on the command line.
|
||||||
|
|
||||||
|
set -- \
|
||||||
|
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||||
|
-classpath "$CLASSPATH" \
|
||||||
|
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||||
|
"$@"
|
||||||
|
|
||||||
|
# Stop when "xargs" is not available.
|
||||||
|
if ! command -v xargs >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "xargs is not available"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Use "xargs" to parse quoted args.
|
||||||
|
#
|
||||||
|
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||||
|
#
|
||||||
|
# In Bash we could simply go:
|
||||||
|
#
|
||||||
|
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||||
|
# set -- "${ARGS[@]}" "$@"
|
||||||
|
#
|
||||||
|
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||||
|
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||||
|
# character that might be a shell metacharacter, then use eval to reverse
|
||||||
|
# that process (while maintaining the separation between arguments), and wrap
|
||||||
|
# the whole thing up as a single "set" statement.
|
||||||
|
#
|
||||||
|
# This will of course break if any of these variables contains a newline or
|
||||||
|
# an unmatched quote.
|
||||||
|
#
|
||||||
|
|
||||||
|
eval "set -- $(
|
||||||
|
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||||
|
xargs -n1 |
|
||||||
|
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||||
|
tr '\n' ' '
|
||||||
|
)" '"$@"'
|
||||||
|
|
||||||
|
exec "$JAVACMD" "$@"
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
@rem
|
||||||
|
@rem Copyright 2015 the original author or authors.
|
||||||
|
@rem
|
||||||
|
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
@rem you may not use this file except in compliance with the License.
|
||||||
|
@rem You may obtain a copy of the License at
|
||||||
|
@rem
|
||||||
|
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
@rem
|
||||||
|
@rem Unless required by applicable law or agreed to in writing, software
|
||||||
|
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
@rem See the License for the specific language governing permissions and
|
||||||
|
@rem limitations under the License.
|
||||||
|
@rem
|
||||||
|
@rem SPDX-License-Identifier: Apache-2.0
|
||||||
|
@rem
|
||||||
|
|
||||||
|
@if "%DEBUG%"=="" @echo off
|
||||||
|
@rem ##########################################################################
|
||||||
|
@rem
|
||||||
|
@rem Gradle startup script for Windows
|
||||||
|
@rem
|
||||||
|
@rem ##########################################################################
|
||||||
|
|
||||||
|
@rem Set local scope for the variables with windows NT shell
|
||||||
|
if "%OS%"=="Windows_NT" setlocal
|
||||||
|
|
||||||
|
set DIRNAME=%~dp0
|
||||||
|
if "%DIRNAME%"=="" set DIRNAME=.
|
||||||
|
@rem This is normally unused
|
||||||
|
set APP_BASE_NAME=%~n0
|
||||||
|
set APP_HOME=%DIRNAME%
|
||||||
|
|
||||||
|
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||||
|
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||||
|
|
||||||
|
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||||
|
|
||||||
|
@rem Find java.exe
|
||||||
|
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||||
|
|
||||||
|
set JAVA_EXE=java.exe
|
||||||
|
%JAVA_EXE% -version >NUL 2>&1
|
||||||
|
if %ERRORLEVEL% equ 0 goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:findJavaFromJavaHome
|
||||||
|
set JAVA_HOME=%JAVA_HOME:"=%
|
||||||
|
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||||
|
|
||||||
|
if exist "%JAVA_EXE%" goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:execute
|
||||||
|
@rem Setup the command line
|
||||||
|
|
||||||
|
set CLASSPATH=
|
||||||
|
|
||||||
|
|
||||||
|
@rem Execute Gradle
|
||||||
|
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||||
|
|
||||||
|
:end
|
||||||
|
@rem End local scope for the variables with windows NT shell
|
||||||
|
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||||
|
|
||||||
|
:fail
|
||||||
|
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||||
|
rem the _cmd.exe /c_ return code!
|
||||||
|
set EXIT_CODE=%ERRORLEVEL%
|
||||||
|
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||||
|
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||||
|
exit /b %EXIT_CODE%
|
||||||
|
|
||||||
|
:mainEnd
|
||||||
|
if "%OS%"=="Windows_NT" endlocal
|
||||||
|
|
||||||
|
:omega
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
pluginManagement {
|
||||||
|
repositories {
|
||||||
|
google {
|
||||||
|
content {
|
||||||
|
includeGroupByRegex("com\\.android.*")
|
||||||
|
includeGroupByRegex("com\\.google.*")
|
||||||
|
includeGroupByRegex("androidx.*")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mavenCentral()
|
||||||
|
gradlePluginPortal()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dependencyResolutionManagement {
|
||||||
|
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||||
|
repositories {
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
maven { url = uri("https://jitpack.io") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rootProject.name = "Textpipe"
|
||||||
|
include(":app")
|
||||||
|
|
||||||