ML Intern deploy commited on
Commit
83a59ca
·
0 Parent(s):

Deploy httpSMS gateway to Hugging Face Spaces (Docker SDK): nginx :7860 -> Go API :8000, Nuxt SPA, Android APK, bootstrap-mode entrypoint

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. .github/CODEOWNERS +2 -0
  3. .github/FUNDING.yml +3 -0
  4. .github/copilot-instructions.md +146 -0
  5. .github/dependabot.yml +51 -0
  6. .github/ghbadge.png +0 -0
  7. .github/workflows/api.yml +135 -0
  8. .github/workflows/web.yml +92 -0
  9. .gitignore +25 -0
  10. .mcp.json +9 -0
  11. .pre-commit-config.yaml +20 -0
  12. CODE_OF_CONDUCT.md +131 -0
  13. Dockerfile +42 -0
  14. LICENSE +661 -0
  15. README.md +54 -0
  16. SECURITY.md +13 -0
  17. android/.gitignore +16 -0
  18. android/app/.gitignore +1 -0
  19. android/app/build.gradle.kts +79 -0
  20. android/app/google-services.json +29 -0
  21. android/app/proguard-rules.pro +21 -0
  22. android/app/src/androidTest/java/com/httpsms/ExampleInstrumentedTest.kt +24 -0
  23. android/app/src/main/AndroidManifest.xml +122 -0
  24. android/app/src/main/ic_launcher-playstore.png +0 -0
  25. android/app/src/main/java/com/httpsms/Constants.kt +25 -0
  26. android/app/src/main/java/com/httpsms/DeliveredReceiver.kt +110 -0
  27. android/app/src/main/java/com/httpsms/Encrypter.kt +44 -0
  28. android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt +451 -0
  29. android/app/src/main/java/com/httpsms/HttpSmsApiService.kt +300 -0
  30. android/app/src/main/java/com/httpsms/LoginActivity.kt +178 -0
  31. android/app/src/main/java/com/httpsms/LogzTree.kt +82 -0
  32. android/app/src/main/java/com/httpsms/MainActivity.kt +245 -0
  33. android/app/src/main/java/com/httpsms/Models.kt +91 -0
  34. android/app/src/main/java/com/httpsms/ReceivedReceiver.kt +229 -0
  35. android/app/src/main/java/com/httpsms/Receiver.kt +73 -0
  36. android/app/src/main/java/com/httpsms/SentReceiver.kt +137 -0
  37. android/app/src/main/java/com/httpsms/Settings.kt +380 -0
  38. android/app/src/main/java/com/httpsms/SettingsActivity.kt +67 -0
  39. android/app/src/main/java/com/httpsms/SmsManagerService.kt +122 -0
  40. android/app/src/main/java/com/httpsms/receivers/BootReceiver.kt +31 -0
  41. android/app/src/main/java/com/httpsms/receivers/PhoneStateReceiver.kt +174 -0
  42. android/app/src/main/java/com/httpsms/services/StickyNotificationService.kt +75 -0
  43. android/app/src/main/java/com/httpsms/ui/login/LoginActivityContent.kt +217 -0
  44. android/app/src/main/java/com/httpsms/ui/login/LoginViewModel.kt +221 -0
  45. android/app/src/main/java/com/httpsms/ui/main/MainActivityContent.kt +243 -0
  46. android/app/src/main/java/com/httpsms/ui/main/MainViewModel.kt +116 -0
  47. android/app/src/main/java/com/httpsms/ui/settings/SettingsActivityContent.kt +221 -0
  48. android/app/src/main/java/com/httpsms/ui/settings/SettingsViewModel.kt +114 -0
  49. android/app/src/main/java/com/httpsms/ui/theme/Theme.kt +75 -0
  50. android/app/src/main/java/com/httpsms/ui/theme/Typography.kt +17 -0
.gitattributes ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ web/public/HttpSms.apk filter=lfs diff=lfs merge=lfs -text
2
+ web/public/*.png filter=lfs diff=lfs merge=lfs -text
3
+ web/public/img/**/*.png filter=lfs diff=lfs merge=lfs -text
.github/CODEOWNERS ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Require review/approval for any changes to GitHub Actions workflows
2
+ /.github/workflows/ @AchoArnold
.github/FUNDING.yml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # These are supported funding model platforms
2
+
3
+ github: [NdoleStudio]
.github/copilot-instructions.md ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copilot Instructions for httpSMS
2
+
3
+ httpSMS is a service that turns an Android phone into an SMS gateway via an HTTP API. This is a monorepo with three components:
4
+
5
+ - **`api/`** — Go backend (Fiber, GORM, PostgreSQL)
6
+ - **`web/`** — Nuxt 2 frontend (Vue 2, Vuetify 2, TypeScript)
7
+ - **`android/`** — Native Android app (Kotlin)
8
+
9
+ ## Build, Test, and Lint Commands
10
+
11
+ ### API (Go)
12
+
13
+ ```bash
14
+ cd api
15
+
16
+ # Development with hot-reload
17
+ air
18
+
19
+ # Build
20
+ go build -o ./tmp/main.exe .
21
+
22
+ # Run tests
23
+ go test ./...
24
+
25
+ # Run a single test
26
+ go test ./pkg/services/ -run TestMessageService
27
+
28
+ # Generate Swagger docs (required after changing API annotations)
29
+ swag init --requiredByDefault --parseDependency --parseInternal
30
+
31
+ # Pre-commit hooks run: go-fumpt, go-imports, go-lint, go-mod-tidy
32
+ ```
33
+
34
+ ### Web (Nuxt/Vue)
35
+
36
+ ```bash
37
+ cd web
38
+
39
+ # Install dependencies
40
+ pnpm install
41
+
42
+ # Development server (port 3000)
43
+ pnpm dev
44
+
45
+ # Lint (eslint + stylelint + prettier)
46
+ pnpm lint
47
+
48
+ # Auto-fix lint issues
49
+ pnpm lintfix
50
+
51
+ # Run tests (Jest)
52
+ pnpm test
53
+
54
+ # Static site generation (production build)
55
+ pnpm run generate
56
+
57
+ # Regenerate TypeScript API models from Swagger
58
+ pnpm api:models
59
+ ```
60
+
61
+ ### Android (Kotlin)
62
+
63
+ ```bash
64
+ cd android
65
+
66
+ # Build
67
+ ./gradlew build
68
+
69
+ # Debug APK
70
+ ./gradlew assembleDebug
71
+
72
+ # Release APK
73
+ ./gradlew assembleRelease
74
+ ```
75
+
76
+ ### Docker (full stack)
77
+
78
+ ```bash
79
+ # Start all services (PostgreSQL, Redis, API, Web)
80
+ docker compose up --build
81
+ # API at localhost:8000, Web at localhost:3000
82
+ ```
83
+
84
+ ## Architecture
85
+
86
+ ### API — Layered Architecture with Event-Driven Processing
87
+
88
+ The API uses a **DI container** (`pkg/di/container.go`) that lazily initializes all services as singletons. The layered architecture flows as:
89
+
90
+ **Handlers → Services → Repositories → GORM/PostgreSQL**
91
+
92
+ - **Handlers** (`pkg/handlers/`) — Fiber HTTP handlers. Each has a `RegisterRoutes()` method and embeds a base `handler` struct with standardized response methods (`responseBadRequest`, `responseNotFound`, etc.).
93
+ - **Services** (`pkg/services/`) — Business logic. Orchestrate repositories and dispatch events.
94
+ - **Repositories** (`pkg/repositories/`) — Data access via GORM. Interfaces defined alongside GORM implementations (prefixed `gorm*`).
95
+ - **Validators** (`pkg/validators/`) — One validator per handler, return `url.Values` for field errors.
96
+ - **Entities** (`pkg/entities/`) — Domain models, auto-migrated by GORM.
97
+
98
+ **Event system**: Uses CloudEvents spec (`cloudevents/sdk-go`). Events defined in `pkg/events/` (31 event types). Listeners in `pkg/listeners/` process events either synchronously or via Google Cloud Tasks queue (emulator mode for local dev).
99
+
100
+ **Entry point**: `main.go` loads `.env` in local mode, creates the DI container, and starts Fiber on `APP_PORT`.
101
+
102
+ ### Web — Nuxt 2 Static SPA
103
+
104
+ - **State management**: Single Vuex store (`store/index.ts`) — actions make API calls via Axios, mutations update state, getters expose computed values.
105
+ - **Components**: Use `vue-property-decorator` class syntax with `@Component`, `@Prop`, `@Watch` decorators.
106
+ - **API client**: Axios configured in `plugins/axios.ts` with Firebase bearer token auth and `x-api-key` header support.
107
+ - **API models**: TypeScript types in `models/` are auto-generated from the Swagger spec via `swagger-typescript-api`.
108
+ - **Auth**: Firebase Authentication (Email/Password, Google, GitHub) with `auth` and `guest` middleware for route guards.
109
+ - **Real-time**: Pusher.js for live message updates.
110
+
111
+ ### Android — Task-Oriented, Event-Driven
112
+
113
+ - **No MVVM/Clean Architecture** — uses a flat package structure with Activities, Services, BroadcastReceivers, and WorkManager tasks.
114
+ - **FCM integration**: `MyFirebaseMessagingService` receives push notifications → schedules `SendSmsWorker` via WorkManager → fetches message from API → sends SMS.
115
+ - **Dual SIM support**: Independent settings per SIM via `Settings` singleton (SharedPreferences).
116
+ - **HTTP client**: OkHttp with `x-api-key` authentication against the API.
117
+ - **Encryption**: AES-256/CFB with SHA-256 key derivation (`Encrypter.kt`).
118
+
119
+ ## Documentation & PR Workflow
120
+
121
+ - **Superpowers docs (`docs/superpowers/`) are never committed to git** — the directory is gitignored. Do not remove it from `.gitignore` or add its files with `git add -f`.
122
+ - When a change is driven by a superpowers SPEC, include a **summarized version of the SPEC in the PR description** (goal, key decisions, scope) instead of the full doc, so reviewers/agents can understand the change without needing the uncommitted file.
123
+
124
+ ## Key Conventions
125
+
126
+ ### API (Go)
127
+
128
+ - **Error handling**: Use `github.com/palantir/stacktrace` — wrap errors with `stacktrace.Propagate(err, "context")` or `stacktrace.PropagateWithCode()`. Never return bare errors.
129
+ - **Database queries**: Always use GORM query builder with context propagation (`repository.db.WithContext(ctx)`). No raw SQL.
130
+ - **Route registration**: Each handler defines `RegisterRoutes()` called from the DI container. Routes follow REST conventions under `/v1/`.
131
+ - **Middleware chain**: HTTP Logger → OpenTelemetry → CORS → Request Logger → Bearer Auth → API Key Auth.
132
+ - **Observability**: All layers are instrumented with OpenTelemetry (Fiber, GORM, Redis). Pass `logger` and `tracer` to constructors.
133
+ - **Code formatting**: `go-fumpt` (not `gofmt`), enforced via pre-commit hooks.
134
+
135
+ ### Web (Vue/TypeScript)
136
+
137
+ - **Formatting**: No semicolons, single quotes, 2-space indentation (Prettier + ESLint).
138
+ - **Component style**: Class-based with `vue-property-decorator`, not Options API (though some pages use `Vue.extend()`).
139
+ - **Store pattern**: Actions handle async API calls and commit mutations. Access store from components via `this.$store`.
140
+
141
+ ### Android (Kotlin)
142
+
143
+ - **API calls**: Use `HttpSmsApiService` singleton (static `create()` factory). OkHttp client with `x-api-key` header.
144
+ - **Background work**: Use WorkManager for tasks that must survive process death. Direct `Thread { }` for lightweight background ops.
145
+ - **State**: `Settings` object (SharedPreferences singleton) for all persistent state.
146
+ - **Phone number formatting**: Use `libphonenumber` for E.164 format validation.
.github/dependabot.yml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: 2
2
+ updates:
3
+ # Fetch and update latest `npm` packages
4
+ - package-ecosystem: npm
5
+ directory: "/web"
6
+ schedule:
7
+ interval: monthly
8
+ time: "00:00"
9
+ # Keep version updates beyond pnpm's 24-hour release-age guard.
10
+ # Security updates bypass cooldown; transitive resolution also needs the workspace gate.
11
+ cooldown:
12
+ default-days: 3
13
+ open-pull-requests-limit: 10
14
+ reviewers:
15
+ - AchoArnold
16
+ assignees:
17
+ - AchoArnold
18
+ commit-message:
19
+ prefix: fix
20
+ prefix-development: chore
21
+ include: scope
22
+ # Fetch and update latest `github-actions` pkgs
23
+ - package-ecosystem: github-actions
24
+ directory: "/"
25
+ schedule:
26
+ interval: monthly
27
+ time: "00:00"
28
+ open-pull-requests-limit: 10
29
+ reviewers:
30
+ - AchoArnold
31
+ assignees:
32
+ - AchoArnold
33
+ commit-message:
34
+ prefix: fix
35
+ prefix-development: chore
36
+ include: scope
37
+ # Fetch and update latest `go` packages
38
+ - package-ecosystem: gomod
39
+ directory: "/api"
40
+ schedule:
41
+ interval: monthly
42
+ time: "00:00"
43
+ open-pull-requests-limit: 10
44
+ reviewers:
45
+ - AchoArnold
46
+ assignees:
47
+ - AchoArnold
48
+ commit-message:
49
+ prefix: fix
50
+ prefix-development: chore
51
+ include: scope
.github/ghbadge.png ADDED
.github/workflows/api.yml ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: api
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ pull_request:
8
+ branches:
9
+ - main
10
+
11
+ permissions:
12
+ contents: read
13
+ id-token: write
14
+
15
+ jobs:
16
+ test:
17
+ name: Integration Tests
18
+ runs-on: ubuntu-latest
19
+ steps:
20
+ - name: Checkout
21
+ uses: actions/checkout@v7
22
+
23
+ - name: Set up Go
24
+ uses: actions/setup-go@v7
25
+ with:
26
+ go-version: stable
27
+
28
+ - name: Generate Firebase credentials
29
+ run: |
30
+ bash tests/generate-firebase-credentials.sh tests/firebase-credentials.json
31
+ echo "FIREBASE_CREDENTIALS=$(jq -c . tests/firebase-credentials.json)" >> $GITHUB_ENV
32
+
33
+ - name: Generate adapter certificates
34
+ run: bash tests/generate-adapter-certificates.sh tests/certs
35
+
36
+ - name: Start Services
37
+ working-directory: ./tests
38
+ run: docker compose up -d --build
39
+
40
+ - name: Wait for services to be healthy
41
+ working-directory: ./tests
42
+ run: |
43
+ echo "Waiting for MongoDB to be healthy..."
44
+ for i in $(seq 1 20); do
45
+ if docker compose exec mongodb mongosh --eval "db.runCommand('ping').ok" --quiet >/dev/null 2>&1; then
46
+ echo "MongoDB is healthy!"
47
+ break
48
+ fi
49
+ if [ $i -eq 20 ]; then
50
+ echo "MongoDB failed to become healthy"
51
+ docker compose logs mongodb
52
+ exit 1
53
+ fi
54
+ echo "MongoDB attempt $i/20 - waiting 3s..."
55
+ sleep 3
56
+ done
57
+
58
+ echo "Waiting for API to be healthy..."
59
+ for i in $(seq 1 40); do
60
+ if docker compose exec api curl -sf http://localhost:8000/health >/dev/null 2>&1; then
61
+ echo "API is healthy!"
62
+ break
63
+ fi
64
+ if [ $i -eq 40 ]; then
65
+ echo "API failed to become healthy"
66
+ docker compose logs api
67
+ exit 1
68
+ fi
69
+ echo "Attempt $i/40 - waiting 5s..."
70
+ sleep 5
71
+ done
72
+
73
+ - name: Seed Database
74
+ working-directory: ./tests
75
+ run: |
76
+ echo "Waiting for seed container to finish..."
77
+ docker compose wait seed || true
78
+ sleep 2
79
+
80
+ - name: Run Handler Integration Tests
81
+ working-directory: ./api
82
+ env:
83
+ USER_API_KEY: test-user-api-key
84
+ run: go test -tags integration -v -timeout 60s ./pkg/handlers
85
+
86
+ - name: Run Integration Tests
87
+ working-directory: ./tests
88
+ run: go test -v -timeout 300s ./...
89
+
90
+ - name: Collect Logs on Failure
91
+ if: failure()
92
+ working-directory: ./tests
93
+ run: |
94
+ docker compose logs --tail 200
95
+
96
+ - name: Stop Services
97
+ if: always()
98
+ working-directory: ./tests
99
+ run: docker compose down -v
100
+
101
+ deploy:
102
+ name: Deploy
103
+ runs-on: ubuntu-latest
104
+ needs: test
105
+ if: github.event_name == 'push' && github.ref == 'refs/heads/main'
106
+ steps:
107
+ - name: Authenticate to Google Cloud
108
+ uses: google-github-actions/auth@v3
109
+ with:
110
+ workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
111
+ service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
112
+
113
+ - name: Set up Cloud SDK
114
+ uses: google-github-actions/setup-gcloud@v3
115
+
116
+ - name: Trigger Cloud Build Deploy
117
+ run: |
118
+ BUILD_ID=$(gcloud builds triggers run api-httpsms-com \
119
+ --region=global \
120
+ --project=httpsms-86c51 \
121
+ --sha=${{ github.sha }} \
122
+ --format="value(metadata.build.id)")
123
+ echo -e "Cloud Build: \033[34mhttps://console.cloud.google.com/cloud-build/builds/$BUILD_ID?project=httpsms-86c51\033[0m"
124
+ echo ""
125
+ echo "Polling Cloud Build Status..."
126
+ while true; do
127
+ STATUS=$(gcloud builds describe "$BUILD_ID" --region=global --project=httpsms-86c51 --format="value(status)")
128
+ LOCAL_TIME=$(date -u '+%Y-%m-%d %H:%M:%S UTC')
129
+ echo -e " \033[90m${LOCAL_TIME}\033[0m status=\033[36m${STATUS}\033[0m"
130
+ case "$STATUS" in
131
+ SUCCESS) echo -e "\033[32mBuild succeeded!\033[0m"; exit 0 ;;
132
+ FAILURE|TIMEOUT|CANCELLED|EXPIRED|INTERNAL_ERROR) echo -e "\033[31mBuild failed with status: $STATUS\033[0m"; exit 1 ;;
133
+ esac
134
+ sleep 30
135
+ done
.github/workflows/web.yml ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: web
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ pull_request:
8
+ branches:
9
+ - main
10
+
11
+ permissions:
12
+ contents: read
13
+ pull-requests: write
14
+ deployments: write
15
+
16
+ defaults:
17
+ run:
18
+ working-directory: ./web
19
+
20
+ jobs:
21
+ validate:
22
+ name: Validate
23
+ runs-on: ${{ matrix.os }}
24
+
25
+ strategy:
26
+ matrix:
27
+ os: [ubuntu-latest]
28
+ node: [24]
29
+
30
+ steps:
31
+ - name: Checkout 🛎
32
+ uses: actions/checkout@master
33
+
34
+ - uses: pnpm/action-setup@v6
35
+ name: Install pnpm
36
+ with:
37
+ version: 11.11.0
38
+
39
+ - name: Install dependencies 📦
40
+ run: pnpm install --trust-lockfile
41
+
42
+ - name: Run linter 👀
43
+ run: pnpm lint
44
+
45
+ - name: Run tests 🧪
46
+ run: pnpm test
47
+
48
+ - name: Build 🏗️
49
+ run: mv .env.production .env && echo "GITHUB_SHA=${GITHUB_SHA}" >> .env && pnpm run generate
50
+
51
+ deploy:
52
+ name: Deploy
53
+ needs: validate
54
+ if: github.event_name == 'push' && github.ref == 'refs/heads/main'
55
+ runs-on: ubuntu-latest
56
+
57
+ steps:
58
+ - name: Checkout 🛎
59
+ uses: actions/checkout@master
60
+
61
+ - name: Setup Node 🟢
62
+ uses: actions/setup-node@v7
63
+ with:
64
+ node-version: '24.18'
65
+
66
+ - uses: pnpm/action-setup@v6
67
+ name: Install pnpm
68
+ with:
69
+ version: 11.11.0
70
+
71
+ - name: Install dependencies 📦
72
+ run: pnpm install --trust-lockfile
73
+
74
+ - name: Build 🏗️
75
+ run: mv .env.production .env && echo "GITHUB_SHA=${GITHUB_SHA}" >> .env && pnpm run generate
76
+
77
+ - name: Cloudflare Deploy 🚀
78
+ uses: cloudflare/wrangler-action@v4
79
+ with:
80
+ apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
81
+ accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
82
+ command: pages deploy web/.output/public --project-name=httpsms
83
+ gitHubToken: ${{ secrets.GITHUB_TOKEN }}
84
+
85
+ - name: Firebase Deploy 🚀
86
+ uses: FirebaseExtended/action-hosting-deploy@500ac625ca2dd40cbd15f7659af953801858032a
87
+ with:
88
+ repoToken: "${{ secrets.GITHUB_TOKEN }}"
89
+ channelId: live
90
+ entryPoint: "./web"
91
+ firebaseServiceAccount: "${{ secrets.FIREBASE_SERVICE_ACCOUNT_HTTPSMS_86C51 }}"
92
+ projectId: httpsms-86c51
.gitignore ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .idea
2
+ .env*
3
+ !.env.docker
4
+ !.env.production
5
+ *serviceAccountKey.json
6
+ android/app/debug/
7
+ *main.exe*
8
+ android/app/release/
9
+
10
+ tests/firebase-credentials.json
11
+ tests/certs/
12
+ tests/emulator/emulator.exe
13
+ SECURITY_AUDIT_REPORT.md
14
+
15
+ *.exe
16
+
17
+ .output
18
+ .agents/
19
+ skills-lock.json
20
+ .worktrees/
21
+ docs/superpowers
22
+ # --- httpsms HF deployment additions ---
23
+ firebase-credentials.json
24
+ *.jks
25
+ *.keystore
.mcp.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "mcpServers": {
3
+ "context7": {
4
+ "type": "stdio",
5
+ "command": "npx",
6
+ "args": ["@upstash/context7-mcp@latest"]
7
+ }
8
+ }
9
+ }
.pre-commit-config.yaml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/tekwizely/pre-commit-golang
3
+ rev: v1.0.0-rc.4
4
+ hooks:
5
+ - id: go-fumpt
6
+ - id: go-mod-tidy
7
+ - id: go-lint
8
+ - id: go-imports
9
+ - repo: https://github.com/pre-commit/pre-commit-hooks
10
+ rev: v6.0.0
11
+ hooks:
12
+ - id: check-yaml
13
+ - id: end-of-file-fixer
14
+ - id: trailing-whitespace
15
+
16
+ - repo: https://github.com/pre-commit/mirrors-prettier
17
+ rev: v4.0.0-alpha.8
18
+ hooks:
19
+ - id: prettier
20
+ exclude: ^web/
CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ - Demonstrating empathy and kindness toward other people
21
+ - Being respectful of differing opinions, viewpoints, and experiences
22
+ - Giving and gracefully accepting constructive feedback
23
+ - Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ - Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ - The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ - Trolling, insulting or derogatory comments, and personal or political attacks
33
+ - Public or private harassment
34
+ - Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ - Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at arnold@httpsms.com.
63
+ All complaints will be reviewed and investigated promptly and fairly.
64
+
65
+ All community leaders are obligated to respect the privacy and security of the
66
+ reporter of any incident.
67
+
68
+ ## Enforcement Guidelines
69
+
70
+ Community leaders will follow these Community Impact Guidelines in determining
71
+ the consequences for any action they deem in violation of this Code of Conduct:
72
+
73
+ ### 1. Correction
74
+
75
+ **Community Impact**: Use of inappropriate language or other behavior deemed
76
+ unprofessional or unwelcome in the community.
77
+
78
+ **Consequence**: A private, written warning from community leaders, providing
79
+ clarity around the nature of the violation and an explanation of why the
80
+ behavior was inappropriate. A public apology may be requested.
81
+
82
+ ### 2. Warning
83
+
84
+ **Community Impact**: A violation through a single incident or series of
85
+ actions.
86
+
87
+ **Consequence**: A warning with consequences for continued behavior. No
88
+ interaction with the people involved, including unsolicited interaction with
89
+ those enforcing the Code of Conduct, for a specified period of time. This
90
+ includes avoiding interactions in community spaces as well as external channels
91
+ like social media. Violating these terms may lead to a temporary or permanent
92
+ ban.
93
+
94
+ ### 3. Temporary Ban
95
+
96
+ **Community Impact**: A serious violation of community standards, including
97
+ sustained inappropriate behavior.
98
+
99
+ **Consequence**: A temporary ban from any sort of interaction or public
100
+ communication with the community for a specified period of time. No public or
101
+ private interaction with the people involved, including unsolicited interaction
102
+ with those enforcing the Code of Conduct, is allowed during this period.
103
+ Violating these terms may lead to a permanent ban.
104
+
105
+ ### 4. Permanent Ban
106
+
107
+ **Community Impact**: Demonstrating a pattern of violation of community
108
+ standards, including sustained inappropriate behavior, harassment of an
109
+ individual, or aggression toward or disparagement of classes of individuals.
110
+
111
+ **Consequence**: A permanent ban from any sort of public interaction within the
112
+ community.
113
+
114
+ ## Attribution
115
+
116
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
117
+ version 2.1, available at
118
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
119
+
120
+ Community Impact Guidelines were inspired by
121
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
122
+
123
+ For answers to common questions about this code of conduct, see the FAQ at
124
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
125
+ [https://www.contributor-covenant.org/translations][translations].
126
+
127
+ [homepage]: https://www.contributor-covenant.org
128
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
129
+ [Mozilla CoC]: https://github.com/mozilla/diversity
130
+ [FAQ]: https://www.contributor-covenant.org/faq
131
+ [translations]: https://www.contributor-covenant.org/translations
Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1
2
+ # ============================================================
3
+ # Stage 1 — Nuxt 3 static SPA build (web/)
4
+ # ============================================================
5
+ FROM node:22-alpine AS web-builder
6
+ WORKDIR /build
7
+ COPY web/ ./
8
+ RUN npm install -g pnpm@11.11.0 \
9
+ && pnpm install --frozen-lockfile
10
+ # web/.env (committed, public build-time config: API_BASE_URL, Firebase web config, Turnstile site key)
11
+ RUN pnpm generate
12
+ # -> /build/.output/public (static SPA)
13
+
14
+ # ============================================================
15
+ # Stage 2 — Go Fiber API build (api/)
16
+ # ============================================================
17
+ FROM golang:1.26-alpine AS api-builder
18
+ WORKDIR /build
19
+ COPY api/ ./
20
+ RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags "-s -w" -o /httpsms-api .
21
+
22
+ # ============================================================
23
+ # Stage 3 — runtime: nginx :7860 + API :8000 + psql seeding
24
+ # ============================================================
25
+ FROM alpine:3.20
26
+ RUN apk add --no-cache nginx postgresql postgresql-client redis ca-certificates curl tzdata \
27
+ && adduser -D -u 1000 user \
28
+ && mkdir -p /usr/share/nginx/html /var/log/nginx /var/lib/nginx \
29
+ && chown -R user:user /usr/share/nginx/html /var/log/nginx /var/lib/nginx /etc/nginx /tmp
30
+
31
+ COPY --from=web-builder --chown=user:user /build/.output/public/ /usr/share/nginx/html/
32
+ COPY --from=api-builder --chown=user:user /httpsms-api /usr/local/bin/httpsms-api
33
+ COPY --chown=user:user nginx.hf.conf /etc/nginx/nginx.conf
34
+ COPY --chown=user:user entrypoint.sh /entrypoint.sh
35
+
36
+ RUN chmod +x /entrypoint.sh
37
+
38
+ USER user
39
+ ENV HOME=/home/user
40
+ WORKDIR /home/user
41
+ EXPOSE 7860
42
+ ENTRYPOINT ["/entrypoint.sh"]
LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ <one line to give the program's name and a brief idea of what it does.>
633
+ Copyright (C) <year> <name of author>
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published
637
+ by the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
README.md ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: httpSMS Bulk Android Gateway
3
+ emoji: 📱
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ ---
10
+
11
+ [![Built with ML Intern](https://huggingface.co/datasets/huggingface/badges/resolve/main/built-with-ml-intern-sm.svg)](https://hf.co/chat?mode=ml-intern)
12
+
13
+ # httpSMS Gateway — self-hosted on Hugging Face Spaces
14
+
15
+ Production-hardened, single-origin deployment of the open-source [httpSMS](https://github.com/NdoleStudio/httpsms) Android SMS gateway: Go Fiber REST API + Nuxt 3 web dashboard behind a non-root nginx reverse proxy on a Hugging Face Docker Space.
16
+
17
+ - **Live dashboard:** https://red-kit-httpsms-gateway.hf.space
18
+ - **REST API base URL:** https://red-kit-httpsms-gateway.hf.space/v1
19
+ - **Android APK (direct download):** https://red-kit-httpsms-gateway.hf.space/HttpSms.apk
20
+
21
+ ## Bootstrap mode
22
+
23
+ If the `DATABASE_URL` / `REDIS_URL` Space secrets are **not** set, `entrypoint.sh` starts ephemeral in-container PostgreSQL and Redis so the gateway is live out of the box. Data resets on restart. Set the two secrets to switch to a managed database (Neon/Supabase/Upstash) — no rebuild needed.
24
+
25
+ ## Architecture
26
+
27
+ - nginx (uid 1000, non-root) listens on `:7860`, proxies `/v1/*` and heartbeat/health routes to the Go Fiber API on `127.0.0.1:8000`, and serves the static Nuxt SPA plus the APK.
28
+ - State lives in external managed PostgreSQL and Redis (injected as Space secrets, never committed).
29
+ - `entrypoint.sh` starts the API for GORM auto-migration, idempotently seeds the internal CloudEvents queue system user (`ON CONFLICT DO UPDATE`), then supervises the API and runs nginx.
30
+ - WebSocket/SSE upgrade headers, `X-Real-IP`, `X-Forwarded-For`, `X-Forwarded-Proto: https` are set by nginx on API routes.
31
+
32
+ ## Quick start — REST API
33
+
34
+ Get your API key from the web dashboard after login, then:
35
+
36
+ ```bash
37
+ export HTTPSMS_API_KEY="<your api key from the dashboard>"
38
+
39
+ # Send a single SMS
40
+ curl -X POST https://red-kit-httpsms-gateway.hf.space/v1/messages/send \
41
+ -H "X-API-Key: ${HTTPSMS_API_KEY}" \
42
+ -H "Content-Type: application/json" \
43
+ -d '{"from": "+18005550199", "to": "+18005550100", "content": "Hello from httpSMS"}'
44
+
45
+ # Bulk-send to many recipients
46
+ curl -X POST https://red-kit-httpsms-gateway.hf.space/v1/messages/bulk-send \
47
+ -H "X-API-Key: ${HTTPSMS_API_KEY}" \
48
+ -H "Content-Type: application/json" \
49
+ -d '{"from": "+18005550199", "to": ["+18005550100", "+18005550101"], "content": "Hello from httpSMS"}'
50
+ ```
51
+
52
+ Messages are delivered through the connected Android phone running the httpSMS app (install the APK above; its default server URL points at this Space).
53
+
54
+ Upstream source: https://github.com/NdoleStudio/httpsms · Docs: https://docs.httpsms.com
SECURITY.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ As of today, I only support the latest version of httpSMS in the `main` branch of github. Please make sure you stay up-to-date.
6
+
7
+ | Version | Supported |
8
+ | ------- | ------------------ |
9
+ | main | :white_check_mark: |
10
+
11
+ ## Reporting a Vulnerability
12
+
13
+ Please report severe security issues privately via arnold@httpsms.com or by sending me a private message on [Discord](https://discord.gg/kGk8HVqeEZ).
android/.gitignore ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.iml
2
+ .gradle
3
+ /local.properties
4
+ /.idea/caches
5
+ /.idea/libraries
6
+ /.idea/modules.xml
7
+ /.idea/workspace.xml
8
+ /.idea/navEditor.xml
9
+ /.idea/assetWizardSettings.xml
10
+ .DS_Store
11
+ /build
12
+ /captures
13
+ .externalNativeBuild
14
+ .cxx
15
+ .kotlin/sessions/
16
+ local.properties
android/app/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ /build
android/app/build.gradle.kts ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ plugins {
2
+ id("com.android.application")
3
+ id("com.google.gms.google-services")
4
+ id("io.sentry.android.gradle") version "6.14.0"
5
+ id("org.jetbrains.kotlin.plugin.compose")
6
+ }
7
+
8
+ val gitHash = providers.exec {
9
+ commandLine("git", "rev-parse", "--short", "HEAD")
10
+ }.standardOutput.asText.map { it.trim() }
11
+
12
+ android {
13
+ compileSdk = 37
14
+
15
+ defaultConfig {
16
+ applicationId = "com.httpsms"
17
+ minSdk = 28
18
+ targetSdk = 37
19
+ versionCode = 1
20
+ versionName = gitHash.getOrElse("unknown")
21
+ testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
22
+ }
23
+
24
+ buildTypes {
25
+ getByName("debug") {
26
+ manifestPlaceholders["sentryEnvironment"] = "development"
27
+ }
28
+ getByName("release") {
29
+ manifestPlaceholders["sentryEnvironment"] = "production"
30
+ isMinifyEnabled = false
31
+ proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
32
+ }
33
+ }
34
+ compileOptions {
35
+ sourceCompatibility = JavaVersion.VERSION_1_8
36
+ targetCompatibility = JavaVersion.VERSION_1_8
37
+ }
38
+ namespace = "com.httpsms"
39
+
40
+ buildFeatures {
41
+ buildConfig = true
42
+ compose = true
43
+ }
44
+ }
45
+
46
+ dependencies {
47
+ val composeBom = platform("androidx.compose:compose-bom:2026.06.01")
48
+ implementation(composeBom)
49
+ androidTestImplementation(composeBom)
50
+
51
+ implementation("androidx.compose.ui:ui")
52
+ implementation("androidx.compose.ui:ui-graphics")
53
+ implementation("androidx.compose.ui:ui-tooling-preview")
54
+ implementation("androidx.compose.material3:material3")
55
+ implementation("androidx.compose.material:material-icons-extended")
56
+ implementation("androidx.activity:activity-compose:1.13.0")
57
+ implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.11.0")
58
+
59
+ implementation(platform("com.google.firebase:firebase-bom:34.16.0"))
60
+ implementation("com.journeyapps:zxing-android-embedded:4.3.0")
61
+ implementation("com.google.firebase:firebase-analytics")
62
+ implementation("com.google.firebase:firebase-messaging")
63
+ implementation("com.squareup.okhttp3:okhttp:5.4.0")
64
+ implementation("com.jakewharton.timber:timber:5.0.1")
65
+ implementation("androidx.preference:preference-ktx:1.2.1")
66
+ implementation("androidx.work:work-runtime-ktx:2.11.2")
67
+ implementation("androidx.core:core-ktx:1.19.0")
68
+ implementation("androidx.cardview:cardview:1.0.0")
69
+ implementation("com.beust:klaxon:5.6")
70
+ implementation("androidx.appcompat:appcompat:1.7.1")
71
+ implementation("org.apache.commons:commons-text:1.15.0")
72
+ implementation("com.google.android.material:material:1.14.0")
73
+ implementation("androidx.constraintlayout:constraintlayout:2.2.1")
74
+ implementation("com.googlecode.libphonenumber:libphonenumber:9.0.34")
75
+ implementation("com.klinkerapps:android-smsmms:5.2.6")
76
+ testImplementation("junit:junit:4.13.2")
77
+ androidTestImplementation("androidx.test.ext:junit:1.3.0")
78
+ androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
79
+ }
android/app/google-services.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "project_info": {
3
+ "project_number": "533003867471",
4
+ "project_id": "httpsms-66180",
5
+ "storage_bucket": "httpsms-66180.firebasestorage.app"
6
+ },
7
+ "client": [
8
+ {
9
+ "client_info": {
10
+ "mobilesdk_app_id": "1:533003867471:android:36f4e532bc408fe798a13a",
11
+ "android_client_info": {
12
+ "package_name": "com.httpsms"
13
+ }
14
+ },
15
+ "oauth_client": [],
16
+ "api_key": [
17
+ {
18
+ "current_key": "AIzaSyCaqEuBeLoHw7CzVW9cgecAk84JcgpiBKM"
19
+ }
20
+ ],
21
+ "services": {
22
+ "appinvite_service": {
23
+ "other_platform_oauth_client": []
24
+ }
25
+ }
26
+ }
27
+ ],
28
+ "configuration_version": "1"
29
+ }
android/app/proguard-rules.pro ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Add project specific ProGuard rules here.
2
+ # You can control the set of applied configuration files using the
3
+ # proguardFiles setting in build.gradle.
4
+ #
5
+ # For more details, see
6
+ # http://developer.android.com/guide/developing/tools/proguard.html
7
+
8
+ # If your project uses WebView with JS, uncomment the following
9
+ # and specify the fully qualified class name to the JavaScript interface
10
+ # class:
11
+ #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12
+ # public *;
13
+ #}
14
+
15
+ # Uncomment this to preserve the line number information for
16
+ # debugging stack traces.
17
+ #-keepattributes SourceFile,LineNumberTable
18
+
19
+ # If you keep the line number information, uncomment this to
20
+ # hide the original source file name.
21
+ #-renamesourcefileattribute SourceFile
android/app/src/androidTest/java/com/httpsms/ExampleInstrumentedTest.kt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms
2
+
3
+ import androidx.test.platform.app.InstrumentationRegistry
4
+ import androidx.test.ext.junit.runners.AndroidJUnit4
5
+
6
+ import org.junit.Test
7
+ import org.junit.runner.RunWith
8
+
9
+ import org.junit.Assert.*
10
+
11
+ /**
12
+ * Instrumented test, which will execute on an Android device.
13
+ *
14
+ * See [testing documentation](http://d.android.com/tools/testing).
15
+ */
16
+ @RunWith(AndroidJUnit4::class)
17
+ class ExampleInstrumentedTest {
18
+ @Test
19
+ fun useAppContext() {
20
+ // Context of the app under test.
21
+ val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22
+ assertEquals("com.httpsms", appContext.packageName)
23
+ }
24
+ }
android/app/src/main/AndroidManifest.xml ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3
+ xmlns:tools="http://schemas.android.com/tools">
4
+
5
+
6
+ <uses-feature
7
+ android:name="android.hardware.telephony"
8
+ android:required="false" />
9
+
10
+ <uses-permission android:name="android.permission.READ_PHONE_STATE" />
11
+ <uses-permission android:name="android.permission.READ_CALL_LOG" />
12
+ <uses-permission android:name="android.permission.READ_SMS" />
13
+ <uses-permission android:name="android.permission.SEND_SMS" />
14
+ <uses-permission android:name="android.permission.RECEIVE_SMS" />
15
+ <uses-permission android:name="android.permission.RECEIVE_MMS"/>
16
+ <uses-permission android:name="android.permission.INTERNET" />
17
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
18
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
19
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
20
+ <uses-permission android:name="android.permission.WAKE_LOCK" />
21
+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
22
+ <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
23
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_REMOTE_MESSAGING"/>
24
+
25
+ <application
26
+ android:allowBackup="true"
27
+ android:dataExtractionRules="@xml/data_extraction_rules"
28
+ android:fullBackupContent="@xml/backup_rules"
29
+ android:icon="@mipmap/ic_launcher"
30
+ android:label="@string/app_name"
31
+ android:roundIcon="@mipmap/ic_launcher_round"
32
+ android:supportsRtl="true"
33
+ android:theme="@style/Theme.HttpSMS"
34
+ tools:targetApi="36">
35
+ <activity
36
+ android:name=".MainActivity"
37
+ android:screenOrientation="portrait"
38
+ android:exported="true"
39
+ tools:ignore="LockedOrientationActivity">
40
+ <intent-filter>
41
+ <action android:name="android.intent.action.MAIN" />
42
+
43
+ <category android:name="android.intent.category.LAUNCHER" />
44
+ </intent-filter>
45
+ </activity>
46
+ <activity android:name=".LoginActivity" android:screenOrientation="portrait"
47
+ tools:ignore="LockedOrientationActivity" />
48
+ <activity android:name=".SettingsActivity" android:screenOrientation="portrait"
49
+ tools:ignore="LockedOrientationActivity" />
50
+ <activity
51
+ android:name="com.journeyapps.barcodescanner.CaptureActivity"
52
+ android:screenOrientation="fullSensor"
53
+ tools:replace="screenOrientation"
54
+ tools:ignore="DiscouragedApi" />
55
+
56
+ <service
57
+ android:name=".services.StickyNotificationService"
58
+ android:enabled="true"
59
+ android:foregroundServiceType="remoteMessaging"
60
+ android:exported="false">
61
+ </service>
62
+
63
+ <service
64
+ android:name=".MyFirebaseMessagingService"
65
+ android:foregroundServiceType="remoteMessaging"
66
+ android:exported="false">
67
+ <intent-filter>
68
+ <action android:name="com.google.firebase.MESSAGING_EVENT" />
69
+ </intent-filter>
70
+ </service>
71
+
72
+ <receiver android:name=".ReceivedReceiver" android:permission="android.permission.BROADCAST_SMS"
73
+ android:exported="true">
74
+ <intent-filter android:priority="999">
75
+ <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
76
+ </intent-filter>
77
+ <intent-filter android:priority="999">
78
+ <action android:name="android.provider.Telephony.WAP_PUSH_RECEIVED" />
79
+ <data android:mimeType="application/vnd.wap.mms-message" />
80
+ </intent-filter>
81
+ </receiver>
82
+
83
+ <receiver android:enabled="true" android:exported="true" android:name=".receivers.PhoneStateReceiver" android:permission="android.permission.READ_PHONE_STATE">
84
+ <intent-filter>
85
+ <action android:name="android.intent.action.PHONE_STATE" />
86
+ </intent-filter>
87
+ </receiver>
88
+
89
+ <receiver android:enabled="true"
90
+ android:name=".receivers.BootReceiver"
91
+ android:exported="true"
92
+ android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
93
+ <intent-filter>
94
+ <action android:name="android.intent.action.BOOT_COMPLETED"/>
95
+ </intent-filter>
96
+ </receiver>
97
+
98
+ <!-- Need this to share the attachment images with native mms service -->
99
+ <provider
100
+ android:name="androidx.core.content.FileProvider"
101
+ android:authorities="${applicationId}.fileprovider"
102
+ android:exported="false"
103
+ android:grantUriPermissions="true">
104
+ <meta-data
105
+ android:name="android.support.FILE_PROVIDER_PATHS"
106
+ android:resource="@xml/file_paths" />
107
+ </provider>
108
+
109
+ <meta-data
110
+ android:name="com.google.firebase.messaging.default_notification_channel_id"
111
+ android:value="@string/notification_channel_default" />
112
+ <meta-data android:name="io.sentry.dsn" android:value="https://3413741bb211a873f5f93a00b8974a03@o291224.ingest.sentry.io/6539757" />
113
+ <!-- Set tracesSampleRate to 1.0 to capture 100% of transactions for performance monitoring.
114
+ We recommend adjusting this value in production. -->
115
+ <meta-data android:name="io.sentry.traces.sample-rate" android:value="0.5" />
116
+ <!-- Enable user interaction tracing to capture transactions for various UI events (such as clicks or scrolls). -->
117
+ <meta-data android:name="io.sentry.traces.user-interaction.enable" android:value="true" />
118
+
119
+ <!-- https://developer.android.com/studio/build/manifest-build-variables -->
120
+ <meta-data android:name="io.sentry.environment" android:value="${sentryEnvironment}" />
121
+ </application>
122
+ </manifest>
android/app/src/main/ic_launcher-playstore.png ADDED
android/app/src/main/java/com/httpsms/Constants.kt ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms
2
+
3
+ class Constants {
4
+ companion object {
5
+ const val KEY_MESSAGE_ID = "KEY_MESSAGE_ID"
6
+ const val KEY_MESSAGE_FROM = "KEY_MESSAGE_FROM"
7
+ const val KEY_MESSAGE_TO = "KEY_MESSAGE_TO"
8
+ const val KEY_MESSAGE_SIM = "KEY_MESSAGE_SIM"
9
+ const val KEY_MESSAGE_CONTENT = "KEY_MESSAGE_CONTENT"
10
+ const val KEY_MESSAGE_TIMESTAMP = "KEY_MESSAGE_TIMESTAMP"
11
+ const val KEY_MESSAGE_REASON = "KEY_MESSAGE_REASON"
12
+ const val KEY_MESSAGE_ENCRYPTED = "KEY_MESSAGE_ENCRYPTED"
13
+ const val KEY_MESSAGE_ATTACHMENTS = "KEY_MESSAGE_ATTACHMENTS"
14
+
15
+
16
+ const val KEY_HEARTBEAT_ID = "KEY_HEARTBEAT_ID"
17
+
18
+ const val SIM1 = "SIM1"
19
+ const val SIM2 = "SIM2"
20
+
21
+ const val TIMESTAMP_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'000000'ZZZZZ"
22
+
23
+ const val MAX_MMS_ATTACHMENT_SIZE: Long = (3L * 1024 * 1024) / 2
24
+ }
25
+ }
android/app/src/main/java/com/httpsms/DeliveredReceiver.kt ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms
2
+
3
+ import android.app.Activity
4
+ import android.content.BroadcastReceiver
5
+ import android.content.Context
6
+ import android.content.Intent
7
+ import androidx.work.Constraints
8
+ import androidx.work.Data
9
+ import androidx.work.NetworkType
10
+ import androidx.work.OneTimeWorkRequest
11
+ import androidx.work.WorkManager
12
+ import androidx.work.Worker
13
+ import androidx.work.WorkerParameters
14
+ import androidx.work.workDataOf
15
+ import timber.log.Timber
16
+
17
+
18
+ internal class DeliveredReceiver : BroadcastReceiver() {
19
+ override fun onReceive(context: Context, intent: Intent) {
20
+ when (resultCode) {
21
+ Activity.RESULT_OK -> handleMessageDelivered(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID))
22
+ else -> handleMessageFailed(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID))
23
+ }
24
+ }
25
+
26
+ private fun handleMessageDelivered(context: Context, messageId: String?) {
27
+ if (!Receiver.isValid(context, messageId)) {
28
+ return
29
+ }
30
+
31
+ val constraints = Constraints.Builder()
32
+ .setRequiredNetworkType(NetworkType.CONNECTED)
33
+ .build()
34
+
35
+ val inputData: Data = workDataOf(
36
+ Constants.KEY_MESSAGE_ID to messageId,
37
+ Constants.KEY_MESSAGE_TIMESTAMP to Settings.currentTimestamp()
38
+ )
39
+
40
+ val work = OneTimeWorkRequest
41
+ .Builder(DeliveredMessageWorker::class.java)
42
+ .setConstraints(constraints)
43
+ .setInputData(inputData)
44
+ .build()
45
+
46
+ WorkManager
47
+ .getInstance(context)
48
+ .enqueue(work)
49
+
50
+ Timber.d("work enqueued with ID [${work.id}] for [DELIVERED] message with ID [${messageId}]")
51
+ }
52
+
53
+ private fun handleMessageFailed(context: Context, messageId: String?) {
54
+ if (!Receiver.isValid(context, messageId)) {
55
+ return
56
+ }
57
+
58
+ val constraints = Constraints.Builder()
59
+ .setRequiredNetworkType(NetworkType.CONNECTED)
60
+ .build()
61
+
62
+ val inputData: Data = workDataOf(
63
+ Constants.KEY_MESSAGE_ID to messageId,
64
+ Constants.KEY_MESSAGE_REASON to "CANNOT BE DELIVERED",
65
+ Constants.KEY_MESSAGE_TIMESTAMP to Settings.currentTimestamp()
66
+ )
67
+
68
+ val work = OneTimeWorkRequest
69
+ .Builder(FailedMessageWorker::class.java)
70
+ .setConstraints(constraints)
71
+ .setInputData(inputData)
72
+ .build()
73
+
74
+ WorkManager
75
+ .getInstance(context)
76
+ .enqueue(work)
77
+
78
+ Timber.d("work enqueued with ID [${work.id}] for [FAILED] message with ID [${messageId}]")
79
+ }
80
+
81
+
82
+ internal class DeliveredMessageWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) {
83
+ override fun doWork(): Result {
84
+ val messageId = this.inputData.getString(Constants.KEY_MESSAGE_ID)
85
+ val timestamp = this.inputData.getString(Constants.KEY_MESSAGE_TIMESTAMP)
86
+
87
+ Timber.i("[${timestamp}] sending [DELIVERED] message event with ID [${messageId}]")
88
+
89
+ if (HttpSmsApiService.create(applicationContext).sendDeliveredEvent(messageId!!, timestamp!!)){
90
+ return Result.success()
91
+ }
92
+ return Result.retry()
93
+ }
94
+ }
95
+
96
+ internal class FailedMessageWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) {
97
+ override fun doWork(): Result {
98
+ val messageId = this.inputData.getString(Constants.KEY_MESSAGE_ID)
99
+ val reason = this.inputData.getString(Constants.KEY_MESSAGE_REASON)
100
+ val timestamp = this.inputData.getString(Constants.KEY_MESSAGE_TIMESTAMP)
101
+
102
+ Timber.i("[${timestamp}] sending [FAILED] message event with ID [${messageId}] and reason [$reason]")
103
+
104
+ if (HttpSmsApiService.create(applicationContext).sendFailedEvent(messageId!!, timestamp!!, reason!!)){
105
+ return Result.success()
106
+ }
107
+ return Result.retry()
108
+ }
109
+ }
110
+ }
android/app/src/main/java/com/httpsms/Encrypter.kt ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms
2
+
3
+ import timber.log.Timber
4
+ import java.security.MessageDigest
5
+ import java.util.Base64
6
+ import java.util.Random
7
+ import javax.crypto.Cipher
8
+ import javax.crypto.spec.IvParameterSpec
9
+ import javax.crypto.spec.SecretKeySpec
10
+
11
+ object Encrypter {
12
+ private const val ALGORITHM = "AES/CFB/NoPadding"
13
+ private const val IV_SIZE = 16
14
+
15
+ fun decrypt(key: String, cipherText: String): String {
16
+ val cipher = Cipher.getInstance(ALGORITHM)
17
+ val cipherBytes = Base64.getDecoder().decode(cipherText)
18
+ Timber.d("iv = ${Base64.getEncoder().encodeToString(cipherBytes.take(IV_SIZE).toByteArray())}")
19
+ Timber.d("cipher = ${Base64.getEncoder().encodeToString(cipherBytes.drop(IV_SIZE).toByteArray())}")
20
+ cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(hash(key), "AES"), IvParameterSpec(cipherBytes.take(IV_SIZE).toByteArray()))
21
+ val plainText = cipher.doFinal(cipherBytes.drop(IV_SIZE).toByteArray())
22
+ return String(plainText)
23
+ }
24
+
25
+ fun encrypt(key: String, inputText: String): String {
26
+ val cipher = Cipher.getInstance(ALGORITHM)
27
+ val iv = generateIv()
28
+ cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(hash(key),"AES"), IvParameterSpec(iv))
29
+ val cipherBytes = iv + cipher.doFinal(inputText.toByteArray())
30
+ return Base64.getEncoder().encodeToString(cipherBytes)
31
+ }
32
+
33
+ private fun generateIv(): ByteArray {
34
+ val b = ByteArray(IV_SIZE)
35
+ Random().nextBytes(b)
36
+ return b
37
+ }
38
+
39
+ private fun hash(key: String): ByteArray {
40
+ val bytes = key.toByteArray()
41
+ val md = MessageDigest.getInstance("SHA-256")
42
+ return md.digest(bytes)
43
+ }
44
+ }
android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms
2
+
3
+ import android.app.PendingIntent
4
+ import android.content.Context
5
+ import android.content.Intent
6
+ import androidx.work.*
7
+ import com.google.firebase.messaging.FirebaseMessagingService
8
+ import com.google.firebase.messaging.RemoteMessage
9
+ import com.httpsms.SentReceiver.FailedMessageWorker
10
+ import timber.log.Timber
11
+
12
+ import com.google.android.mms.pdu_alt.CharacterSets
13
+ import com.google.android.mms.pdu_alt.EncodedStringValue
14
+ import com.google.android.mms.pdu_alt.PduBody
15
+ import com.google.android.mms.pdu_alt.PduComposer
16
+ import com.google.android.mms.pdu_alt.PduPart
17
+ import com.google.android.mms.pdu_alt.SendReq
18
+ import okhttp3.MediaType
19
+ import java.io.File
20
+
21
+ class MyFirebaseMessagingService : FirebaseMessagingService() {
22
+ // [START receive_message]
23
+ override fun onMessageReceived(remoteMessage: RemoteMessage) {
24
+ initTimber()
25
+ Timber.d(MyFirebaseMessagingService::onMessageReceived.name)
26
+
27
+ if (remoteMessage.data.containsKey(Constants.KEY_HEARTBEAT_ID)) {
28
+ Timber.w("received heartbeat message with ID [${remoteMessage.data[Constants.KEY_HEARTBEAT_ID]}] and priority [${remoteMessage.priority}] and original priority [${remoteMessage.originalPriority}]")
29
+ sendHeartbeat()
30
+ return
31
+ }
32
+
33
+ val messageID = remoteMessage.data[Constants.KEY_MESSAGE_ID]
34
+ if (messageID == null) {
35
+ Timber.e("cannot get message id from notification data with key [${Constants.KEY_MESSAGE_ID}]")
36
+ return
37
+ }
38
+
39
+ scheduleJob(messageID)
40
+ }
41
+ // [END receive_message]
42
+
43
+ // [START on_new_token]
44
+ /**
45
+ * Called if the FCM registration token is updated. This may occur if the security of
46
+ * the previous token had been compromised. Note that this is called when the
47
+ * FCM registration token is initially generated so this is where you would retrieve the token.
48
+ */
49
+ override fun onNewToken(token: String) {
50
+ initTimber()
51
+ Timber.d("Refreshed token: $token")
52
+
53
+ // If you want to send messages to this application instance or
54
+ // manage this apps subscriptions on the server side, send the
55
+ // FCM registration token to your app server.
56
+ sendRegistrationToServer(token)
57
+ }
58
+ // [END on_new_token]
59
+
60
+ private fun sendHeartbeat() {
61
+ Timber.d("sending heartbeat from FCM notification")
62
+ if (!Settings.isLoggedIn(applicationContext)) {
63
+ Timber.w("user is not logged in, not sending heartbeat")
64
+ return
65
+ }
66
+ Thread {
67
+ try {
68
+ val phoneNumbers = mutableListOf<String>()
69
+ phoneNumbers.add(Settings.getSIM1PhoneNumber(applicationContext))
70
+ if (Settings.getActiveStatus(applicationContext, Constants.SIM2)) {
71
+ phoneNumbers.add(Settings.getSIM2PhoneNumber(applicationContext))
72
+ }
73
+
74
+ HttpSmsApiService.create(applicationContext).storeHeartbeat(phoneNumbers.toTypedArray(), Settings.isCharging(applicationContext))
75
+ Settings.setHeartbeatTimestampAsync(applicationContext, System.currentTimeMillis())
76
+ } catch (exception: Exception) {
77
+ Timber.e(exception)
78
+ }
79
+ Timber.d("finished sending pulse")
80
+ }.start()
81
+ }
82
+
83
+ private fun scheduleJob(messageID: String) {
84
+ // [START dispatch_job]
85
+ val constraints = Constraints.Builder()
86
+ .setRequiredNetworkType(NetworkType.CONNECTED)
87
+ .build()
88
+
89
+ val inputData: Data = workDataOf(Constants.KEY_MESSAGE_ID to messageID)
90
+ val work = OneTimeWorkRequest
91
+ .Builder(SendSmsWorker::class.java)
92
+ .setConstraints(constraints)
93
+ .setInputData(inputData)
94
+ .addTag(messageID)
95
+ .build()
96
+
97
+ WorkManager
98
+ .getInstance(this)
99
+ .enqueue(work)
100
+
101
+ Timber.d("work enqueued with ID [${work.id}] for messageID [${messageID}]")
102
+ // [END dispatch_job]
103
+ }
104
+ private fun sendRegistrationToServer(token: String) {
105
+ Timber.d("sendRegistrationTokenToServer($token)")
106
+ Settings.setFcmTokenAsync(this, token)
107
+
108
+ if (Settings.isLoggedIn(this)) {
109
+ Timber.d("updating SIM1 phone with new fcm token")
110
+ val response = HttpSmsApiService.create(this).updateFcmToken(Settings.getSIM1PhoneNumber(this), Constants.SIM1, token)
111
+ if (response.first != null) {
112
+ Settings.setUserID(this, response.first!!.userID)
113
+ }
114
+ }
115
+
116
+ if(Settings.isDualSIM(this)) {
117
+ Timber.d("updating SIM2 phone with new fcm token")
118
+ HttpSmsApiService.create(this).updateFcmToken(Settings.getSIM2PhoneNumber(this), Constants.SIM2, token)
119
+ }
120
+ }
121
+
122
+ private fun initTimber() {
123
+ if (Timber.treeCount > 1) {
124
+ Timber.d("timber is already initialized with count [${Timber.treeCount}]")
125
+ return
126
+ }
127
+
128
+ if(Settings.isDebugLogEnabled(this)) {
129
+ Timber.plant(Timber.DebugTree())
130
+ Timber.plant(LogzTree(this.applicationContext))
131
+ }
132
+ }
133
+
134
+ internal class SendSmsWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) {
135
+ override fun doWork(): Result {
136
+ if (!Settings.isLoggedIn(applicationContext)) {
137
+ Timber.w("user is not logged in, stopping processing")
138
+ return Result.failure()
139
+ }
140
+
141
+ val messageID = this.inputData.getString(Constants.KEY_MESSAGE_ID)
142
+ if (messageID == null) {
143
+ Timber.e("cannot get outstanding message for work [${this.id}]")
144
+ return Result.failure()
145
+ }
146
+
147
+ val message = getMessage(applicationContext, messageID) ?: return Result.failure()
148
+
149
+ if (message.contact.isBlank()) {
150
+ Timber.w("message contact is blank, stopping processing")
151
+ handleFailed(applicationContext, messageID, "The contact phone number is empty.")
152
+ return Result.failure()
153
+ }
154
+
155
+ if (!Settings.getActiveStatus(applicationContext, message.sim)) {
156
+ Timber.w("[${message.sim}] SIM is not active, stopping processing")
157
+ handleFailed(applicationContext, messageID, "Outgoing messages have been disabled on the mobile app")
158
+ return Result.failure()
159
+ }
160
+
161
+ if (message.encrypted && Settings.getEncryptionKey(applicationContext).isNullOrEmpty()) {
162
+ Timber.w("[${message.sim}] message is encrypted but the encryption key is empty")
163
+ handleFailed(applicationContext, messageID, "Outgoing message is encrypted but mobile app has no encryption key")
164
+ return Result.failure()
165
+ }
166
+ if (message.encrypted) {
167
+ try {
168
+ Encrypter.decrypt(Settings.getEncryptionKey(applicationContext)!!, message.content)
169
+ } catch (exception: Exception) {
170
+ Timber.e(exception)
171
+ handleFailed(applicationContext, messageID, "Cannot decrypt the outgoing message. Check your encryption key on the Android app.")
172
+ return Result.failure()
173
+ }
174
+ }
175
+
176
+ Receiver.register(applicationContext)
177
+
178
+ if (message.attachments != null && message.attachments.isNotEmpty()) {
179
+ return handleMmsMessage(message)
180
+ }
181
+
182
+ val parts = getMessageParts(applicationContext, message)
183
+ if (parts.size == 1) {
184
+ return handleSingleMessage(message, parts.first())
185
+ }
186
+ return handleMultipartMessage(message, parts)
187
+ }
188
+
189
+ fun extractFileName(url: String, prefix: String, mimeType: String? = null): String {
190
+ val fileName = url.substringAfterLast("/")
191
+ .substringBefore("?")
192
+ .takeIf { it.isNotBlank() && it.contains(".") }
193
+ ?: run {
194
+ val extension = mimeType?.let { mime ->
195
+ val ext = mime.substringAfterLast("/")
196
+ if (ext.isNotBlank()) ".$ext" else ".bin"
197
+ } ?: ""
198
+ "attachment$extension"
199
+ }
200
+
201
+ return "${prefix}_$fileName"
202
+ }
203
+
204
+ private fun handleMmsMessage(message: Message): Result {
205
+ Timber.d("Processing MMS for message ID [${message.id}]")
206
+ val apiService = HttpSmsApiService.create(applicationContext)
207
+
208
+ val downloadedFiles = mutableListOf<Pair<File, MediaType>>()
209
+
210
+ try {
211
+ for ((index, attachment) in message.attachments!!.withIndex()) {
212
+ val file = apiService.downloadAttachment(applicationContext, attachment, message.id, index)
213
+ if (file.first == null || file.second == null) {
214
+ handleFailed(applicationContext, message.id, "Failed to download attachment or file size exceeded 1.5MB.")
215
+ return Result.failure()
216
+ }
217
+ downloadedFiles.add(Pair(file.first!!, file.second!!))
218
+ }
219
+
220
+ val sendReq = SendReq()
221
+
222
+ val encodedContact = EncodedStringValue(message.contact)
223
+ sendReq.to = arrayOf(encodedContact)
224
+
225
+ val pduBody = PduBody()
226
+
227
+ if (message.content.isNotEmpty()) {
228
+ val textPart = PduPart()
229
+ textPart.setCharset(CharacterSets.UTF_8)
230
+ textPart.contentType = "text/plain".toByteArray()
231
+ textPart.name = "text".toByteArray()
232
+ textPart.contentId = "text".toByteArray()
233
+ textPart.contentLocation = "text".toByteArray()
234
+
235
+ var messageBody = message.content
236
+ val encryptionKey = Settings.getEncryptionKey(applicationContext)
237
+ if (message.encrypted && !encryptionKey.isNullOrEmpty()) {
238
+ messageBody = Encrypter.decrypt(encryptionKey, messageBody)
239
+ }
240
+ textPart.data = messageBody.toByteArray(Charsets.UTF_8)
241
+
242
+ pduBody.addPart(textPart)
243
+ }
244
+
245
+ for ((index, file) in downloadedFiles.withIndex()) {
246
+ val fileBytes = file.first.readBytes()
247
+
248
+ val mediaPart = PduPart()
249
+ mediaPart.contentType = file.second.toString().toByteArray()
250
+
251
+
252
+ val fileName = extractFileName(message.attachments[index], index.toString(), file.second.toString())
253
+ mediaPart.name = fileName.toByteArray()
254
+ mediaPart.contentId = fileName.toByteArray()
255
+ mediaPart.contentLocation = fileName.toByteArray()
256
+ mediaPart.data = fileBytes
257
+
258
+ Timber.d("Adding MMS attachment with name [$fileName] and size [${fileBytes.size}] and type [${file.second}]")
259
+
260
+ pduBody.addPart(mediaPart)
261
+ }
262
+
263
+ sendReq.body = pduBody
264
+
265
+ val pduComposer = PduComposer(applicationContext, sendReq)
266
+ val pduBytes = pduComposer.make()
267
+
268
+ if (pduBytes == null) {
269
+ Timber.e("PduComposer failed to generate PDU byte array")
270
+ handleFailed(applicationContext, message.id, "Failed to compose MMS PDU.")
271
+ return Result.failure()
272
+ }
273
+
274
+ val mmsDir = java.io.File(applicationContext.cacheDir, "mms_attachments")
275
+ if (!mmsDir.exists()) {
276
+ mmsDir.mkdirs()
277
+ }
278
+
279
+ val pduFile = java.io.File(mmsDir, "pdu_${message.id}.dat")
280
+ java.io.FileOutputStream(pduFile).use { it.write(pduBytes) }
281
+
282
+ val pduUri = androidx.core.content.FileProvider.getUriForFile(
283
+ applicationContext,
284
+ "${BuildConfig.APPLICATION_ID}.fileprovider",
285
+ pduFile
286
+ )
287
+
288
+ val sentIntent = createPendingIntent(message.id, SmsManagerService.sentAction())
289
+ SmsManagerService().sendMultimediaMessage(applicationContext, pduUri, message.sim, sentIntent)
290
+
291
+ Timber.d("Successfully dispatched MMS for message ID [${message.id}]")
292
+ return Result.success()
293
+
294
+ } catch (e: Exception) {
295
+ Timber.e(e, "Failed to send MMS for message ID [${message.id}]")
296
+ handleFailed(applicationContext, message.id, e.message ?: "Internal error while building or sending MMS.")
297
+ return Result.failure()
298
+ } finally {
299
+ // Clean up any downloaded temporary files
300
+ downloadedFiles.forEach { file ->
301
+ if (file.first.exists()) {
302
+ file.first.delete()
303
+ }
304
+ }
305
+
306
+ // Also clean up the MMS PDU file to avoid cache buildup in cases where
307
+ // sendMultimediaMessage fails before the sent broadcast is delivered.
308
+ try {
309
+ // The PDU file is stored under the "mms_attachments" cache subdirectory;
310
+ // delete it from the same location to ensure cleanup is effective.
311
+ val pduDir = File(applicationContext.cacheDir, "mms_attachments")
312
+ val pduFile = File(pduDir, "pdu_${message.id}.dat")
313
+ if (pduFile.exists()) {
314
+ val deleted = pduFile.delete()
315
+ if (!deleted) {
316
+ Timber.w("Failed to delete MMS PDU file for message ID [${message.id}] at [${pduFile.absolutePath}]")
317
+ }
318
+ }
319
+ } catch (cleanupException: Exception) {
320
+ // Best-effort cleanup; log but do not change the original result.
321
+ Timber.w(cleanupException, "Error while cleaning up MMS PDU file for message ID [${message.id}]")
322
+ }
323
+ }
324
+ }
325
+
326
+ private fun handleMultipartMessage(message:Message, parts: ArrayList<String>): Result {
327
+ Timber.d("sending multipart SMS for message with ID [${message.id}]")
328
+ return try {
329
+ val sentIntents = ArrayList<PendingIntent>()
330
+ val deliveredIntents = ArrayList<PendingIntent>()
331
+
332
+ for (i in 0 until parts.size) {
333
+ var id = "${message.id}.$i"
334
+
335
+ // Listen for 'delivered' and 'sent' intents only on the last part in the
336
+ // multipart SMS message
337
+ if (i == parts.size -1) {
338
+ id = message.id
339
+ }
340
+
341
+ sentIntents.add(createPendingIntent(id, SmsManagerService.sentAction()))
342
+ deliveredIntents.add(createPendingIntent(id, SmsManagerService.deliveredAction()))
343
+ }
344
+ SmsManagerService().sendMultipartMessage(this.applicationContext,message.contact, parts, message.sim, sentIntents, deliveredIntents)
345
+ Timber.d("sent SMS for message with ID [${message.id}] in [${parts.size}] parts")
346
+ Result.success()
347
+ } catch (e: Exception) {
348
+ Timber.e(e)
349
+ Timber.d("could not send SMS for message with ID [${message.id}] in [${parts.size}] parts")
350
+ handleFailed(this.applicationContext, message.id, e.message ?: e.javaClass.simpleName)
351
+ Result.failure()
352
+ }
353
+ }
354
+
355
+ private fun handleSingleMessage(message:Message, content: String): Result {
356
+ sendMessage(
357
+ message,
358
+ content,
359
+ createPendingIntent(message.id, SmsManagerService.sentAction()),
360
+ createPendingIntent(message.id, SmsManagerService.deliveredAction())
361
+ )
362
+ return Result.success()
363
+ }
364
+
365
+ private fun handleFailed(context: Context, messageID: String, reason: String) {
366
+ Timber.d("sending [FAILED] event for message with ID [${messageID}]")
367
+
368
+ val constraints = Constraints.Builder()
369
+ .setRequiredNetworkType(NetworkType.CONNECTED)
370
+ .build()
371
+
372
+ val inputData: Data = workDataOf(
373
+ Constants.KEY_MESSAGE_ID to messageID,
374
+ Constants.KEY_MESSAGE_REASON to reason,
375
+ Constants.KEY_MESSAGE_TIMESTAMP to Settings.currentTimestamp()
376
+ )
377
+
378
+ val work = OneTimeWorkRequest
379
+ .Builder(FailedMessageWorker::class.java)
380
+ .setConstraints(constraints)
381
+ .setInputData(inputData)
382
+ .build()
383
+
384
+ WorkManager
385
+ .getInstance(context)
386
+ .enqueue(work)
387
+
388
+ Timber.d("work enqueued with ID [${work.id}] for [FAILED] message with ID [${messageID}]")
389
+ }
390
+
391
+ private fun getMessage(context: Context, messageID: String): Message? {
392
+ Timber.d("fetching message with ID [${messageID}]")
393
+ val message = HttpSmsApiService.create(context).getOutstandingMessage(messageID)
394
+
395
+ if (message != null) {
396
+ Timber.d("fetched message with ID [${message.id}]")
397
+ return message
398
+ }
399
+
400
+ Timber.e("cannot get message from API with ID [${messageID}]")
401
+ return null
402
+ }
403
+
404
+ private fun sendMessage(message: Message, content: String, sentIntent: PendingIntent, deliveredIntent: PendingIntent) {
405
+ Timber.d("sending SMS for message with ID [${message.id}]")
406
+ try {
407
+ SmsManagerService().sendTextMessage(this.applicationContext,message.contact, content, message.sim, sentIntent, deliveredIntent)
408
+ } catch (e: Exception) {
409
+ Timber.e(e)
410
+ Timber.d("could not send SMS for message with ID [${message.id}]")
411
+ handleFailed(this.applicationContext, message.id, e.message ?: e.javaClass.simpleName)
412
+ return
413
+ }
414
+ Timber.d("sent SMS for message with ID [${message.id}]")
415
+ }
416
+
417
+ private fun getMessageParts(context: Context, message: Message): ArrayList<String> {
418
+ Timber.d("getting parts for message with ID [${message.id}]")
419
+
420
+ var messageBody = message.content
421
+ val encryptionKey = Settings.getEncryptionKey(context)
422
+ if (message.encrypted && !encryptionKey.isNullOrEmpty()) {
423
+ messageBody = Encrypter.decrypt(encryptionKey, messageBody)
424
+ }
425
+
426
+ return try {
427
+ val parts = SmsManagerService().messageParts(context, messageBody)
428
+ Timber.d("message with ID [${message.id}] has [${parts.size}] parts")
429
+ parts
430
+ } catch (e: Exception) {
431
+ Timber.e(e)
432
+ Timber.d("could not get parts message with ID [${message.id}] returning [1] part with entire content")
433
+ val list = ArrayList<String>()
434
+ list.add(messageBody)
435
+ list
436
+ }
437
+ }
438
+
439
+ private fun createPendingIntent(id: String, action: String): PendingIntent {
440
+ val intent = Intent(action)
441
+ intent.putExtra(Constants.KEY_MESSAGE_ID, id)
442
+
443
+ return PendingIntent.getBroadcast(
444
+ this.applicationContext,
445
+ id.hashCode(),
446
+ intent,
447
+ PendingIntent.FLAG_IMMUTABLE
448
+ )
449
+ }
450
+ }
451
+ }
android/app/src/main/java/com/httpsms/HttpSmsApiService.kt ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms
2
+
3
+ import android.content.Context
4
+ import com.httpsms.Constants.Companion.MAX_MMS_ATTACHMENT_SIZE
5
+ import okhttp3.MediaType
6
+ import okhttp3.MediaType.Companion.toMediaType
7
+ import okhttp3.OkHttpClient
8
+ import okhttp3.Request
9
+ import okhttp3.RequestBody.Companion.toRequestBody
10
+ import timber.log.Timber
11
+ import java.io.File
12
+ import java.io.FileOutputStream
13
+ import java.io.IOException
14
+ import java.io.InputStream
15
+ import java.io.OutputStream
16
+ import java.net.URI
17
+ import java.net.URL
18
+ import java.util.logging.Level
19
+ import java.util.logging.Logger.getLogger
20
+
21
+
22
+ class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {
23
+ private val apiKeyHeader = "x-api-key"
24
+ private val clientVersionHeader = "X-Client-Version"
25
+ private val jsonMediaType = "application/json; charset=utf-8".toMediaType()
26
+ private val client = OkHttpClient.Builder().retryOnConnectionFailure(true).build()
27
+
28
+ init {
29
+ getLogger(OkHttpClient::class.java.name).level = Level.FINE
30
+ }
31
+
32
+ companion object {
33
+ fun create(context: Context): HttpSmsApiService {
34
+ return HttpSmsApiService(
35
+ Settings.getApiKeyOrDefault(context),
36
+ Settings.getServerUrlOrDefault(context)
37
+ )
38
+ }
39
+ }
40
+
41
+ fun getOutstandingMessage(messageID: String): Message? {
42
+ val request: Request = Request.Builder()
43
+ .url(resolveURL("/v1/messages/outstanding?message_id=${messageID}"))
44
+ .header(apiKeyHeader, apiKey)
45
+ .header(clientVersionHeader, BuildConfig.VERSION_NAME)
46
+ .build()
47
+
48
+ val response = client.newCall(request).execute()
49
+ if (response.isSuccessful) {
50
+ val payload = ResponseMessage.fromJson(response.body!!.string())?.data
51
+ if (payload == null) {
52
+ response.close()
53
+ Timber.e("cannot decode payload [${response.body}]")
54
+ return null
55
+ }
56
+ response.close()
57
+ return payload
58
+ }
59
+
60
+ Timber.e("invalid response with code [${response.code}]")
61
+ response.close()
62
+ return null
63
+ }
64
+
65
+ fun sendDeliveredEvent(messageId: String, timestamp: String): Boolean {
66
+ return sendEvent(messageId, "DELIVERED", timestamp)
67
+ }
68
+
69
+ fun sendSentEvent(messageId: String, timestamp: String): Boolean {
70
+ return sendEvent(messageId, "SENT", timestamp)
71
+ }
72
+
73
+ fun sendFailedEvent(messageId: String, timestamp: String, reason: String): Boolean {
74
+ return sendEvent(messageId, "FAILED", timestamp, reason)
75
+ }
76
+
77
+ fun receive(requestPayload: ReceivedMessageRequest): Boolean {
78
+ val body = com.beust.klaxon.Klaxon().toJsonString(requestPayload)
79
+
80
+ val request: Request = Request.Builder()
81
+ .url(resolveURL("/v1/messages/receive"))
82
+ .post(body.toRequestBody(jsonMediaType))
83
+ .header(apiKeyHeader, apiKey)
84
+ .header(clientVersionHeader, BuildConfig.VERSION_NAME)
85
+ .build()
86
+
87
+ val response = try {
88
+ client.newCall(request).execute()
89
+ } catch (e: Exception) {
90
+ Timber.e(e, "Exception while sending received message request")
91
+ return false
92
+ }
93
+
94
+ if (!response.isSuccessful) {
95
+ Timber.e("error response [${response.body?.string()}] with code [${response.code}] while receiving message")
96
+ response.close()
97
+ return response.code in 400..499
98
+ }
99
+
100
+ response.close()
101
+ Timber.i("received message stored successfully")
102
+ return true
103
+ }
104
+
105
+ fun sendMissedCallEvent(sim: String, from: String, to: String, timestamp: String): Boolean {
106
+ val body = """
107
+ {
108
+ "sim": "$sim",
109
+ "from": "$from",
110
+ "timestamp": "$timestamp",
111
+ "to": "$to"
112
+ }
113
+ """.trimIndent()
114
+
115
+ val request: Request = Request.Builder()
116
+ .url(resolveURL("/v1/messages/calls/missed"))
117
+ .post(body.toRequestBody(jsonMediaType))
118
+ .header(apiKeyHeader, apiKey)
119
+ .header(clientVersionHeader, BuildConfig.VERSION_NAME)
120
+ .build()
121
+
122
+ val response = client.newCall(request).execute()
123
+ if (!response.isSuccessful) {
124
+ Timber.e("error response [${response.body?.string()}] with code [${response.code}] while sending missed call event [${body}]")
125
+ response.close()
126
+ return response.code in 400..499
127
+ }
128
+
129
+ response.close()
130
+ Timber.i("missed call from [${from}] to [${to}] sent successfully with timestamp [${timestamp}]" )
131
+ return true
132
+ }
133
+
134
+ fun storeHeartbeat(phoneNumbers: Array<String>, charging: Boolean): Boolean {
135
+ val body = """
136
+ {
137
+ "charging": $charging,
138
+ "phone_numbers": ${phoneNumbers.joinToString(prefix = "[", postfix = "]") { "\"$it\"" }}
139
+ }
140
+ """.trimIndent()
141
+
142
+ val request: Request = Request.Builder()
143
+ .url(resolveURL("/v1/heartbeats"))
144
+ .post(body.toRequestBody(jsonMediaType))
145
+ .header(apiKeyHeader, apiKey)
146
+ .header(clientVersionHeader, BuildConfig.VERSION_NAME)
147
+ .build()
148
+
149
+ val response = client.newCall(request).execute()
150
+ if (!response.isSuccessful) {
151
+ Timber.e("error response [${response.body?.string()}] with code [${response.code}] while sending heartbeat [$body] for phone numbers [${phoneNumbers.joinToString()}]")
152
+ response.close()
153
+ return false
154
+ }
155
+
156
+ response.close()
157
+ Timber.i( "heartbeat stored successfully for phone numbers [${phoneNumbers.joinToString()}]" )
158
+ return true
159
+ }
160
+
161
+ fun InputStream.copyToWithLimit(
162
+ out: OutputStream,
163
+ limit: Long,
164
+ bufferSize: Int = DEFAULT_BUFFER_SIZE
165
+ ): Long {
166
+ var bytesCopied: Long = 0
167
+ val buffer = ByteArray(bufferSize)
168
+ var bytes = read(buffer)
169
+
170
+ while (bytes >= 0) {
171
+ bytesCopied += bytes
172
+
173
+ if (bytesCopied > limit) {
174
+ throw IOException("Download aborted: File exceeded maximum allowed size of $limit bytes.")
175
+ }
176
+
177
+ out.write(buffer, 0, bytes)
178
+ bytes = read(buffer)
179
+ }
180
+ return bytesCopied
181
+ }
182
+
183
+ fun downloadAttachment(context: Context, urlString: String, messageId: String, attachmentIndex: Int): Pair<File?, MediaType?> {
184
+ val request = Request.Builder().url(urlString).build()
185
+
186
+ try {
187
+ client.newCall(request).execute().use { response ->
188
+ if (!response.isSuccessful) {
189
+ Timber.e("Failed to download attachment: ${response.code}")
190
+ return Pair(null, null)
191
+ }
192
+
193
+ val body = response.body
194
+ val contentLength = body.contentLength()
195
+ if (contentLength > MAX_MMS_ATTACHMENT_SIZE) {
196
+ Timber.e("Attachment is too large ($contentLength bytes).")
197
+ return Pair(null, null)
198
+ }
199
+
200
+ val mmsDir = File(context.cacheDir, "mms_attachments")
201
+ if (!mmsDir.exists()) {
202
+ mmsDir.mkdirs()
203
+ }
204
+
205
+ val tempFile = File(mmsDir, "mms_${messageId}_$attachmentIndex")
206
+ val inputStream = body.byteStream()
207
+ FileOutputStream(tempFile).use { outputStream ->
208
+ inputStream.use { input ->
209
+ input.copyToWithLimit(outputStream, MAX_MMS_ATTACHMENT_SIZE)
210
+ }
211
+ }
212
+
213
+ return Pair(tempFile, body.contentType())
214
+ }
215
+ } catch (e: Exception) {
216
+ Timber.e(e, "Exception while download attachment")
217
+ return Pair(null, null)
218
+ }
219
+ }
220
+
221
+ private fun sendEvent(messageId: String, event: String, timestamp: String, reason: String? = null): Boolean {
222
+ var reasonString = "null"
223
+ if (reason != null) {
224
+ reasonString = "\"$reason\""
225
+ }
226
+
227
+ val body = """
228
+ {
229
+ "event_name": "$event",
230
+ "reason": $reasonString,
231
+ "timestamp": "$timestamp"
232
+ }
233
+ """.trimIndent()
234
+
235
+ val request: Request = Request.Builder()
236
+ .url(resolveURL("/v1/messages/${messageId}/events"))
237
+ .post(body.toRequestBody(jsonMediaType))
238
+ .header(apiKeyHeader, apiKey)
239
+ .header(clientVersionHeader, BuildConfig.VERSION_NAME)
240
+ .build()
241
+
242
+ val response = client.newCall(request).execute()
243
+ if (response.code == 404) {
244
+ response.close()
245
+ Timber.i( "[$event] event sent successfully but message with ID [$messageId] has been deleted" )
246
+ return true
247
+ }
248
+
249
+ if (!response.isSuccessful) {
250
+ Timber.e("error response [${response.body.string()}] with code [${response.code}] while sending [${event}] event [${body}] for message with ID [${messageId}]")
251
+ response.close()
252
+ return false
253
+ }
254
+
255
+ response.close()
256
+ Timber.i( "[$event] event sent successfully for message with ID [$messageId]" )
257
+ return true
258
+ }
259
+
260
+ fun updateFcmToken(phoneNumber: String, sim: String, fcmToken: String): Triple<Phone?, String?, String?> {
261
+ val body = """
262
+ {
263
+ "fcm_token": "$fcmToken",
264
+ "phone_number": "$phoneNumber",
265
+ "sim": "$sim"
266
+ }
267
+ """.trimIndent()
268
+
269
+ val request: Request = Request.Builder()
270
+ .url(resolveURL("/v1/phones/fcm-token"))
271
+ .put(body.toRequestBody(jsonMediaType))
272
+ .header(apiKeyHeader, apiKey)
273
+ .header(clientVersionHeader, BuildConfig.VERSION_NAME)
274
+ .build()
275
+
276
+ try {
277
+ val response = client.newCall(request).execute()
278
+ if (!response.isSuccessful) {
279
+ Timber.e("error response [${response.body?.string()}] with code [${response.code}] while updating FCM token [$fcmToken] with apiKey [$apiKey]")
280
+ response.close()
281
+ if (response.code == 401) {
282
+ Timber.e("invalid API key [$apiKey]")
283
+ return Triple(null, "Cannot validate the API key. Check if it is correct and try again.", null)
284
+ }
285
+ return Triple(null,null, "Cannot login to the server, Make sure the phone number is in international format e.g +18005550100")
286
+ }
287
+
288
+ Timber.i("FCM token submitted correctly with API key [$apiKey] and server url [$baseURL]" )
289
+ val payload = ResponsePhone.fromJson(response.body!!.string())?.data
290
+ response.close()
291
+ return Triple(payload, null, null)
292
+ } catch (ex: Exception) {
293
+ return Triple(null, null, ex.message)
294
+ }
295
+ }
296
+
297
+ private fun resolveURL(path: String): URL {
298
+ return baseURL.resolve(baseURL.path + path).toURL()
299
+ }
300
+ }
android/app/src/main/java/com/httpsms/LoginActivity.kt ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms
2
+
3
+ import android.Manifest
4
+ import android.annotation.SuppressLint
5
+ import android.content.Context
6
+ import android.content.Intent
7
+ import android.content.pm.PackageManager
8
+ import android.os.Build
9
+ import android.os.Bundle
10
+ import android.telephony.TelephonyManager
11
+ import android.widget.Toast
12
+ import androidx.activity.compose.setContent
13
+ import androidx.activity.result.contract.ActivityResultContracts
14
+ import androidx.activity.viewModels
15
+ import androidx.appcompat.app.AppCompatActivity
16
+ import androidx.compose.runtime.LaunchedEffect
17
+ import androidx.compose.runtime.collectAsState
18
+ import androidx.compose.runtime.getValue
19
+ import androidx.core.app.ActivityCompat
20
+ import com.google.android.gms.common.ConnectionResult
21
+ import com.google.android.gms.common.GoogleApiAvailability
22
+ import com.httpsms.ui.login.LoginScreen
23
+ import com.httpsms.ui.login.LoginViewModel
24
+ import com.httpsms.ui.theme.HttpSmsTheme
25
+ import com.journeyapps.barcodescanner.ScanContract
26
+ import com.journeyapps.barcodescanner.ScanOptions
27
+ import timber.log.Timber
28
+
29
+ class LoginActivity : AppCompatActivity() {
30
+ private val viewModel: LoginViewModel by viewModels()
31
+
32
+ override fun onCreate(savedInstanceState: Bundle?) {
33
+ super.onCreate(savedInstanceState)
34
+ redirectToMain()
35
+
36
+ viewModel.initialize(this, getString(R.string.default_server_url))
37
+
38
+ setContent {
39
+ HttpSmsTheme {
40
+ val uiState by viewModel.uiState.collectAsState()
41
+
42
+ LaunchedEffect(uiState.loginSuccess) {
43
+ if (uiState.loginSuccess) {
44
+ redirectToMain()
45
+ }
46
+ }
47
+
48
+ LoginScreen(
49
+ viewModel = viewModel,
50
+ onQrScanClick = { startQrCodeScan() },
51
+ onLoginClick = {
52
+ val error = isGooglePlayServicesAvailable()
53
+ if (error != null) {
54
+ Toast.makeText(this@LoginActivity, error, Toast.LENGTH_SHORT).show()
55
+ } else {
56
+ viewModel.login(
57
+ context = this@LoginActivity,
58
+ countryCode = getCountryCode(),
59
+ onGooglePlayServicesError = {
60
+ Toast.makeText(this@LoginActivity, it, Toast.LENGTH_SHORT).show()
61
+ },
62
+ onFcmTokenMissing = {
63
+ Toast.makeText(
64
+ this@LoginActivity,
65
+ "Cannot find FCM token. Make sure you have Google Play Services installed",
66
+ Toast.LENGTH_LONG
67
+ ).show()
68
+ }
69
+ )
70
+ }
71
+ }
72
+ )
73
+ }
74
+ }
75
+ }
76
+
77
+ private val barcodeLauncher = registerForActivityResult(ScanContract()) { result ->
78
+ if (result.contents != null) {
79
+ viewModel.onApiKeyChange(result.contents)
80
+ Toast.makeText(this, "Scanned: ${result.contents}", Toast.LENGTH_LONG).show()
81
+ } else {
82
+ Toast.makeText(this, "Scan cancelled", Toast.LENGTH_SHORT).show()
83
+ }
84
+ }
85
+
86
+ private fun startQrCodeScan() {
87
+ val options = ScanOptions()
88
+ options.setPrompt("Scan a QR code")
89
+ options.setBeepEnabled(true)
90
+ options.setOrientationLocked(false)
91
+ options.setCameraId(0)
92
+ barcodeLauncher.launch(options)
93
+ }
94
+
95
+ override fun onStart() {
96
+ super.onStart()
97
+ Timber.i("on start")
98
+ requestPermissions()
99
+ }
100
+
101
+ @SuppressLint("HardwareIds")
102
+ @Suppress("DEPRECATION")
103
+ private fun getPhoneNumber(context: Context): String? {
104
+ val telephonyManager = this.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
105
+ if (ActivityCompat.checkSelfPermission(
106
+ this,
107
+ Manifest.permission.READ_SMS
108
+ ) != PackageManager.PERMISSION_GRANTED
109
+ ) {
110
+ Timber.e("cannot get owner because permissions are not granted")
111
+ return Settings.getSIM1PhoneNumber(this)
112
+ }
113
+
114
+ if (telephonyManager.line1Number != null && telephonyManager.line1Number != "") {
115
+ Settings.setSIM1PhoneNumber(context, telephonyManager.line1Number)
116
+ }
117
+
118
+ return telephonyManager.line1Number
119
+ }
120
+
121
+ private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
122
+ permissions.entries.forEach {
123
+ Timber.d("${it.key} = ${it.value}")
124
+ }
125
+ // Try to auto-detect phone numbers after permissions are granted
126
+ viewModel.autoDetectPhoneNumbers(this)
127
+ }
128
+
129
+ private fun requestPermissions() {
130
+ Timber.d("requesting permissions")
131
+
132
+ var permissions = arrayOf(
133
+ Manifest.permission.SEND_SMS,
134
+ Manifest.permission.RECEIVE_SMS,
135
+ Manifest.permission.READ_PHONE_STATE,
136
+ Manifest.permission.READ_SMS,
137
+ )
138
+
139
+ if(Build.VERSION.SDK_INT >= 33) {
140
+ permissions += Manifest.permission.POST_NOTIFICATIONS
141
+ }
142
+
143
+ requestPermissionLauncher.launch(permissions)
144
+
145
+ Timber.d("creating permissions launcher")
146
+ }
147
+
148
+ private fun isGooglePlayServicesAvailable(): String? {
149
+ val googleApiAvailability = GoogleApiAvailability.getInstance()
150
+ val status = googleApiAvailability.isGooglePlayServicesAvailable(this)
151
+ if (status != ConnectionResult.SUCCESS) {
152
+ if (googleApiAvailability.isUserResolvableError(status)) {
153
+ googleApiAvailability.getErrorDialog(this, status, 2404)?.show()
154
+ }
155
+ return googleApiAvailability.getErrorString(status)
156
+ }
157
+ return null
158
+ }
159
+
160
+ private fun redirectToMain() {
161
+ if (!Settings.isLoggedIn(this)) {
162
+ return
163
+ }
164
+ finish()
165
+
166
+ val switchActivityIntent = Intent(this, MainActivity::class.java)
167
+ startActivity(switchActivityIntent)
168
+ }
169
+
170
+ private fun getCountryCode() : String {
171
+ val tm = this.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
172
+ val code = tm.networkCountryIso.uppercase()
173
+ if (code.isEmpty()) {
174
+ return this.resources.configuration.locales.get(0).country.uppercase()
175
+ }
176
+ return code
177
+ }
178
+ }
android/app/src/main/java/com/httpsms/LogzTree.kt ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms
2
+
3
+ import android.content.Context
4
+ import android.os.Build
5
+ import com.beust.klaxon.Json
6
+ import com.beust.klaxon.Klaxon
7
+ import okhttp3.MediaType.Companion.toMediaType
8
+ import okhttp3.OkHttpClient
9
+ import okhttp3.Request
10
+ import okhttp3.RequestBody.Companion.toRequestBody
11
+ import timber.log.Timber
12
+ import java.time.ZoneOffset
13
+ import java.time.ZonedDateTime
14
+ import java.time.format.DateTimeFormatter
15
+ import io.sentry.Sentry
16
+
17
+ class LogzTree(val context: Context): Timber.DebugTree() {
18
+ private val client = OkHttpClient()
19
+
20
+ override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
21
+ val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
22
+ val logEntry = LogEntry(
23
+ BuildConfig.APPLICATION_ID,
24
+ BuildConfig.VERSION_NAME,
25
+ priority,
26
+ severity(priority),
27
+ tag,
28
+ message,
29
+ Build.MODEL,
30
+ Build.BRAND,
31
+ Build.DEVICE,
32
+ Build.VERSION.SDK_INT,
33
+ ZonedDateTime.now(ZoneOffset.UTC).format(formatter),
34
+ Settings.getUserID(context),
35
+ t
36
+ )
37
+
38
+ val body = Klaxon().toJsonString(listOf(logEntry)).toRequestBody("application/json".toMediaType())
39
+ val request: Request = Request.Builder()
40
+ .url("https://api.axiom.co/v1/datasets/production/ingest")
41
+ .post(body)
42
+ .header("Content-Type", "application/json")
43
+ .header("Authorization", "Bearer xaat-2a2e0b73-3702-4971-a80f-be3956934950")
44
+ .build()
45
+
46
+ Thread {
47
+ try {
48
+ val response = client.newCall(request).execute()
49
+ response.body?.close()
50
+ } catch(ex: Exception) {
51
+ Sentry.captureException(ex)
52
+ }
53
+ }.start()
54
+ }
55
+
56
+ private fun severity(priority: Int): String {
57
+ return when(priority) {
58
+ 3 -> "DEBUG"
59
+ 4 -> "INFO"
60
+ 5 -> "WARNING"
61
+ 6 -> "ERROR"
62
+ 7 -> "ASSERT"
63
+ else -> "VERBOSE"
64
+ }
65
+ }
66
+
67
+ class LogEntry(
68
+ val name: String,
69
+ val release: String,
70
+ val priority: Int,
71
+ val severity: String,
72
+ val tag: String?,
73
+ val message: String,
74
+ val model: String,
75
+ val brand: String,
76
+ val device: String,
77
+ val version: Int,
78
+ @Json(name = "@timestamp")
79
+ val dt: String,
80
+ val userID: String,
81
+ val throwable: Throwable?)
82
+ }
android/app/src/main/java/com/httpsms/MainActivity.kt ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms
2
+
3
+ import android.Manifest
4
+ import android.annotation.SuppressLint
5
+ import android.app.NotificationChannel
6
+ import android.app.NotificationManager
7
+ import android.content.Context
8
+ import android.content.Intent
9
+ import android.content.pm.PackageManager
10
+ import android.net.Uri
11
+ import android.os.Build
12
+ import android.os.Bundle
13
+ import android.provider.Settings as ProviderSettings
14
+ import android.widget.Toast
15
+ import androidx.activity.compose.setContent
16
+ import androidx.activity.result.contract.ActivityResultContracts
17
+ import androidx.activity.viewModels
18
+ import androidx.appcompat.app.AppCompatActivity
19
+ import androidx.work.Constraints
20
+ import androidx.work.ExistingPeriodicWorkPolicy
21
+ import androidx.work.NetworkType
22
+ import androidx.work.PeriodicWorkRequestBuilder
23
+ import androidx.work.WorkManager
24
+ import com.httpsms.services.StickyNotificationService
25
+ import com.httpsms.ui.main.MainScreen
26
+ import com.httpsms.ui.main.MainViewModel
27
+ import com.httpsms.ui.theme.HttpSmsTheme
28
+ import com.httpsms.worker.HeartbeatWorker
29
+ import timber.log.Timber
30
+ import java.util.concurrent.TimeUnit
31
+
32
+
33
+ class MainActivity : AppCompatActivity() {
34
+ private val viewModel: MainViewModel by viewModels()
35
+
36
+ override fun onCreate(savedInstanceState: Bundle?) {
37
+ super.onCreate(savedInstanceState)
38
+
39
+ initTimber()
40
+
41
+ redirectToLogin()
42
+
43
+ viewModel.initialize(this, getString(R.string.app_version, BuildConfig.VERSION_NAME))
44
+
45
+ setContent {
46
+ HttpSmsTheme {
47
+ MainScreen(
48
+ viewModel = viewModel,
49
+ onSettingsClick = { onSettingsClick() },
50
+ onSmsPermissionClick = {
51
+ val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://httpsms.com/blog/grant-send-and-read-sms-permissions-on-android"))
52
+ startActivity(intent)
53
+ },
54
+ onBatteryOptimizationClick = {
55
+ val intent = Intent()
56
+ intent.action = ProviderSettings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
57
+ intent.data = Uri.parse("package:$packageName")
58
+ startActivity(intent)
59
+ },
60
+ onHeartbeatClick = {
61
+ viewModel.sendHeartbeat(this) { error ->
62
+ if (error != null) {
63
+ Timber.w("heartbeat sending failed with [$error]")
64
+ Toast.makeText(this, error, Toast.LENGTH_LONG).show()
65
+ } else {
66
+ Toast.makeText(this, "Heartbeat sent successfully", Toast.LENGTH_SHORT).show()
67
+ }
68
+ }
69
+ }
70
+ )
71
+ }
72
+ }
73
+
74
+ createChannel()
75
+ refreshToken(this)
76
+
77
+ startStickyNotification(this)
78
+ scheduleHeartbeatWorker(this)
79
+ }
80
+
81
+ override fun onStart() {
82
+ super.onStart()
83
+ requestPermissions(this)
84
+ }
85
+
86
+ override fun onResume() {
87
+ super.onResume()
88
+ Timber.d( "on activity resume")
89
+ redirectToLogin()
90
+ refreshToken(this)
91
+ viewModel.updateState(this, getString(R.string.app_version, BuildConfig.VERSION_NAME))
92
+ }
93
+
94
+ private fun requestPermissions(context:Context) {
95
+ Timber.d("requesting permissions")
96
+ val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
97
+ permissions.entries.forEach {
98
+ Timber.d("${it.key} = ${it.value}")
99
+ if (it.key == Manifest.permission.READ_CALL_LOG && !it.value) {
100
+ Timber.w("disabling incoming call events since for SIM1 and SIM2")
101
+ Settings.setIncomingCallEventsEnabled(context, Constants.SIM1, false)
102
+ Settings.setIncomingCallEventsEnabled(context, Constants.SIM2, false)
103
+ }
104
+ }
105
+ viewModel.updateState(context, getString(R.string.app_version, BuildConfig.VERSION_NAME))
106
+ }
107
+
108
+ var permissions = arrayOf(
109
+ Manifest.permission.SEND_SMS,
110
+ Manifest.permission.RECEIVE_SMS,
111
+ Manifest.permission.READ_SMS
112
+ )
113
+
114
+ if(Build.VERSION.SDK_INT >= 33) {
115
+ permissions += Manifest.permission.POST_NOTIFICATIONS
116
+ }
117
+
118
+ if(Settings.isIncomingCallEventsEnabled(context,Constants.SIM1) || Settings.isIncomingCallEventsEnabled(context,Constants.SIM2) ) {
119
+ permissions += Manifest.permission.READ_CALL_LOG
120
+ permissions += Manifest.permission.READ_PHONE_STATE
121
+ }
122
+
123
+ requestPermissionLauncher.launch(permissions)
124
+
125
+ Timber.d("creating permissions launcher")
126
+ }
127
+
128
+ private fun scheduleHeartbeatWorker(context: Context) {
129
+ val tag = "TAG_HEARTBEAT_WORKER"
130
+
131
+ val constraints = Constraints.Builder()
132
+ .setRequiredNetworkType(NetworkType.CONNECTED)
133
+ .build()
134
+
135
+ val heartbeatWorker =
136
+ PeriodicWorkRequestBuilder<HeartbeatWorker>(15, TimeUnit.MINUTES)
137
+ .setConstraints(constraints)
138
+ .addTag(tag)
139
+ .build()
140
+
141
+ WorkManager
142
+ .getInstance(context)
143
+ .enqueueUniquePeriodicWork(tag, ExistingPeriodicWorkPolicy.KEEP, heartbeatWorker)
144
+
145
+ Timber.d("finished scheduling heartbeat worker with ID [${heartbeatWorker.id}]")
146
+ }
147
+
148
+ private fun startStickyNotification(context: Context) {
149
+ Timber.d("starting foreground service")
150
+ if(!Settings.getActiveStatus(context, Constants.SIM1) && !Settings.getActiveStatus(context, Constants.SIM2)) {
151
+ Timber.d("active status is false, not starting foreground service")
152
+ return
153
+ }
154
+ val notificationIntent = Intent(context, StickyNotificationService::class.java)
155
+ val service = context.startForegroundService(notificationIntent)
156
+ Timber.d("foreground service started [${service?.className}]")
157
+ }
158
+
159
+ private fun refreshToken(context: Context) {
160
+ if(!Settings.isLoggedIn(context)) {
161
+ Timber.w("cannot refresh token because owner is not logged in")
162
+ return
163
+ }
164
+
165
+ if(!Settings.hasOwner(context)) {
166
+ Timber.w("cannot refresh token because owner does not exist")
167
+ return
168
+ }
169
+
170
+ if (Settings.getFcmToken(context) == null) {
171
+ Timber.w("cannot refresh token because token does not exist")
172
+ return
173
+ }
174
+
175
+ val updateTimestamp = Settings.getFcmTokenLastUpdateTimestamp(context)
176
+ Timber.d("FCM_TOKEN_UPDATE_TIMESTAMP: $updateTimestamp")
177
+
178
+ val interval = 24 * 60 * 60 * 1000 // 1 day
179
+ val currentTimeStamp = System.currentTimeMillis()
180
+
181
+ if (currentTimeStamp - updateTimestamp < interval) {
182
+ Timber.i("update interval [${currentTimeStamp - updateTimestamp}] < 24 hours [$interval]")
183
+ return
184
+ }
185
+
186
+ sendFCMToken(currentTimeStamp, context, Settings.getSIM1PhoneNumber(context), Constants.SIM1)
187
+ if (Settings.isDualSIM(context)) {
188
+ sendFCMToken(currentTimeStamp, context, Settings.getSIM2PhoneNumber(context), Constants.SIM2)
189
+ }
190
+ }
191
+
192
+ private fun sendFCMToken(timestamp: Long, context:Context, phoneNumber: String, sim: String) {
193
+ Thread {
194
+ val response = HttpSmsApiService.create(context).updateFcmToken(phoneNumber, sim,Settings.getFcmToken(context) ?: "")
195
+ if (response.first != null) {
196
+ Settings.setUserID(context, response.first!!.userID)
197
+ Settings.setFcmTokenLastUpdateTimestampAsync(context, timestamp)
198
+ Timber.i("[${sim}] FCM token uploaded successfully")
199
+ return@Thread
200
+ } else {
201
+ Timber.e("[${sim}] could not update FCM token")
202
+ }
203
+ }.start()
204
+ }
205
+
206
+ private fun initTimber() {
207
+ if (Timber.treeCount > 1) {
208
+ Timber.d("timber is already initialized with count [${Timber.treeCount}]")
209
+ return
210
+ }
211
+
212
+ if(Settings.isDebugLogEnabled(this)) {
213
+ Timber.plant(Timber.DebugTree())
214
+ Timber.plant(LogzTree(this.applicationContext))
215
+ }
216
+ }
217
+
218
+ private fun onSettingsClick() {
219
+ Timber.d("settings button clicked")
220
+ val switchActivityIntent = Intent(this, SettingsActivity::class.java)
221
+ startActivity(switchActivityIntent)
222
+ }
223
+
224
+ private fun redirectToLogin():Boolean {
225
+ if (Settings.isLoggedIn(this)) {
226
+ return false
227
+ }
228
+ val switchActivityIntent = Intent(this, LoginActivity::class.java)
229
+ startActivity(switchActivityIntent)
230
+ return true
231
+ }
232
+
233
+ private fun createChannel() {
234
+ // Create the NotificationChannel
235
+ val name = getString(R.string.notification_channel_default)
236
+ val descriptionText = getString(R.string.notification_channel_default)
237
+ val importance = NotificationManager.IMPORTANCE_DEFAULT
238
+ val mChannel = NotificationChannel(name, name, importance)
239
+ mChannel.description = descriptionText
240
+ // Register the channel with the system; you can't change the importance
241
+ // or other notification behaviors after this
242
+ val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
243
+ notificationManager.createNotificationChannel(mChannel)
244
+ }
245
+ }
android/app/src/main/java/com/httpsms/Models.kt ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms
2
+
3
+ import com.beust.klaxon.Json
4
+ import com.beust.klaxon.Klaxon
5
+
6
+ data class ResponseMessage (
7
+ val data: Message,
8
+ val message: String,
9
+ val status: String
10
+ ) {
11
+ companion object {
12
+ fun fromJson(json: String) = Klaxon().parse<ResponseMessage>(json)
13
+ }
14
+ }
15
+ data class ResponsePhone (
16
+ val data: Phone,
17
+ val message: String,
18
+ val status: String,
19
+ ) {
20
+ companion object {
21
+ fun fromJson(json: String) = Klaxon().parse<ResponsePhone>(json)
22
+ }
23
+ }
24
+
25
+ data class Phone (
26
+ val id: String,
27
+
28
+ @Json(name = "user_id")
29
+ val userID: String,
30
+ )
31
+
32
+ data class Message (
33
+ val contact: String,
34
+ val content: String,
35
+ val sim: String,
36
+
37
+ @Json(name = "created_at")
38
+ val createdAt: String,
39
+
40
+ @Json(name = "failure_reason")
41
+ val failureReason: String?,
42
+
43
+ val id: String,
44
+
45
+ @Json(name = "last_attempted_at")
46
+ val lastAttemptedAt: String?,
47
+
48
+ @Json(name = "order_timestamp")
49
+ val orderTimestamp: String,
50
+
51
+ val owner: String,
52
+
53
+ @Json(name = "received_at")
54
+ val receivedAt: String?,
55
+
56
+ val encrypted: Boolean,
57
+
58
+ @Json(name = "request_received_at")
59
+ val requestReceivedAt: String,
60
+
61
+ @Json(name = "send_time")
62
+ val sendTime: Long?,
63
+
64
+ @Json(name = "sent_at")
65
+ val sentAt: String?,
66
+
67
+ val status: String,
68
+ val type: String,
69
+
70
+ @Json(name = "updated_at")
71
+ val updatedAt: String,
72
+
73
+ val attachments: List<String>? = null
74
+ )
75
+
76
+ data class ReceivedAttachment(
77
+ val name: String,
78
+ @Json(name = "content_type")
79
+ val contentType: String,
80
+ val content: String
81
+ )
82
+
83
+ data class ReceivedMessageRequest(
84
+ val sim: String,
85
+ val from: String,
86
+ val to: String,
87
+ val content: String,
88
+ val encrypted: Boolean,
89
+ val timestamp: String,
90
+ val attachments: List<ReceivedAttachment>? = null
91
+ )
android/app/src/main/java/com/httpsms/ReceivedReceiver.kt ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms
2
+
3
+ import android.content.BroadcastReceiver
4
+ import android.content.Context
5
+ import android.content.Intent
6
+ import android.provider.Telephony
7
+ import android.util.Base64
8
+ import androidx.work.Constraints
9
+ import androidx.work.Data
10
+ import androidx.work.NetworkType
11
+ import androidx.work.OneTimeWorkRequest
12
+ import androidx.work.WorkManager
13
+ import androidx.work.Worker
14
+ import androidx.work.WorkerParameters
15
+ import androidx.work.workDataOf
16
+ import com.google.android.mms.pdu_alt.CharacterSets
17
+ import com.google.android.mms.pdu_alt.MultimediaMessagePdu
18
+ import com.google.android.mms.pdu_alt.PduParser
19
+ import com.google.android.mms.pdu_alt.RetrieveConf
20
+ import timber.log.Timber
21
+ import java.io.File
22
+ import java.io.FileOutputStream
23
+ import java.time.ZoneOffset
24
+ import java.time.ZonedDateTime
25
+ import java.time.format.DateTimeFormatter
26
+
27
+ class ReceivedReceiver: BroadcastReceiver()
28
+ {
29
+ override fun onReceive(context: Context, intent: Intent) {
30
+ if (intent.action == Telephony.Sms.Intents.SMS_RECEIVED_ACTION) {
31
+ handleSmsReceived(context, intent)
32
+ } else if (intent.action == Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION) {
33
+ handleMmsReceived(context, intent)
34
+ } else {
35
+ Timber.e("received invalid intent with action [${intent.action}]")
36
+ }
37
+ }
38
+
39
+ private fun handleSmsReceived(context: Context, intent: Intent) {
40
+ var smsSender = ""
41
+ var smsBody = ""
42
+
43
+ for (smsMessage in Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
44
+ smsSender = smsMessage.displayOriginatingAddress
45
+ smsBody += smsMessage.messageBody
46
+ }
47
+
48
+ val (sim, owner) = getSimAndOwner(context, intent)
49
+
50
+ if (!Settings.isIncomingMessageEnabled(context, sim)) {
51
+ Timber.w("[${sim}] is not active for incoming messages")
52
+ return
53
+ }
54
+
55
+ handleMessageReceived(
56
+ context,
57
+ sim,
58
+ smsSender,
59
+ owner,
60
+ smsBody
61
+ )
62
+ }
63
+
64
+ private fun handleMmsReceived(context: Context, intent: Intent) {
65
+ val pushData = intent.getByteArrayExtra("data") ?: return
66
+ val pdu = PduParser(pushData, true).parse() ?: return
67
+
68
+ if (pdu !is MultimediaMessagePdu) {
69
+ Timber.d("Received PDU is not a MultimediaMessagePdu, ignoring.")
70
+ return
71
+ }
72
+
73
+ val from = pdu.from?.string ?: ""
74
+ var content = ""
75
+ val attachmentFiles = mutableListOf<String>()
76
+
77
+ // Check if it's a RetrieveConf (which contains the actual message body)
78
+ if (pdu is RetrieveConf) {
79
+ val body = pdu.body
80
+ if (body != null) {
81
+ for (i in 0 until body.partsNum) {
82
+ val part = body.getPart(i)
83
+ val partData = part.data ?: continue
84
+ val contentType = String(part.contentType ?: "application/octet-stream".toByteArray())
85
+
86
+ if (contentType.startsWith("text/plain")) {
87
+ content += String(partData, charset(CharacterSets.getMimeName(part.charset)))
88
+ } else {
89
+ // Save attachment to a temporary file
90
+ val fileName = String(part.name ?: part.contentLocation ?: part.contentId ?: "attachment_$i".toByteArray())
91
+ val tempFile = File(context.cacheDir, "received_mms_${System.currentTimeMillis()}_$i")
92
+ FileOutputStream(tempFile).use { it.write(partData) }
93
+ attachmentFiles.add("${tempFile.absolutePath}|${contentType}|${fileName}")
94
+ }
95
+ }
96
+ }
97
+ } else {
98
+ Timber.d("Received PDU is of type [${pdu.javaClass.simpleName}], body extraction not implemented.")
99
+ }
100
+
101
+ val (sim, owner) = getSimAndOwner(context, intent)
102
+
103
+ if (!Settings.isIncomingMessageEnabled(context, sim)) {
104
+ Timber.w("[${sim}] is not active for incoming messages")
105
+ return
106
+ }
107
+
108
+ handleMessageReceived(
109
+ context,
110
+ sim,
111
+ from,
112
+ owner,
113
+ content,
114
+ attachmentFiles.toTypedArray()
115
+ )
116
+ }
117
+
118
+ private fun getSimAndOwner(context: Context, intent: Intent): Pair<String, String> {
119
+ var sim = Constants.SIM1
120
+ var owner = Settings.getSIM1PhoneNumber(context)
121
+ if (intent.getIntExtra("android.telephony.extra.SLOT_INDEX", 0) > 0 && Settings.isDualSIM(context)) {
122
+ owner = Settings.getSIM2PhoneNumber(context)
123
+ sim = Constants.SIM2
124
+ }
125
+ return Pair(sim, owner)
126
+ }
127
+
128
+ private fun handleMessageReceived(context: Context, sim: String, from: String, to : String, content: String, attachments: Array<String>? = null) {
129
+ val timestamp = ZonedDateTime.now(ZoneOffset.UTC)
130
+
131
+ if (!Settings.isLoggedIn(context)) {
132
+ Timber.w("[${sim}] user is not logged in")
133
+ return
134
+ }
135
+
136
+ if (!Settings.getActiveStatus(context, sim)) {
137
+ Timber.w("[${sim}] user is not active")
138
+ return
139
+ }
140
+
141
+ var body = content;
142
+ if (Settings.encryptReceivedMessages(context)) {
143
+ body = Encrypter.encrypt(Settings.getEncryptionKey(context)!!, content)
144
+ }
145
+
146
+ val constraints = Constraints.Builder()
147
+ .setRequiredNetworkType(NetworkType.CONNECTED)
148
+ .build()
149
+
150
+ val inputData: Data = workDataOf(
151
+ Constants.KEY_MESSAGE_FROM to from,
152
+ Constants.KEY_MESSAGE_TO to to,
153
+ Constants.KEY_MESSAGE_SIM to sim,
154
+ Constants.KEY_MESSAGE_CONTENT to body,
155
+ Constants.KEY_MESSAGE_ENCRYPTED to Settings.encryptReceivedMessages(context),
156
+ Constants.KEY_MESSAGE_TIMESTAMP to DateTimeFormatter.ofPattern(Constants.TIMESTAMP_PATTERN).format(timestamp).replace("+", "Z"),
157
+ Constants.KEY_MESSAGE_ATTACHMENTS to attachments
158
+ )
159
+
160
+ val work = OneTimeWorkRequest
161
+ .Builder(ReceivedSmsWorker::class.java)
162
+ .setConstraints(constraints)
163
+ .setInputData(inputData)
164
+ .build()
165
+
166
+ WorkManager
167
+ .getInstance(context)
168
+ .enqueue(work)
169
+
170
+ Timber.d("work enqueued with ID [${work.id}] for received message from [${from}] to [${to}]")
171
+ }
172
+
173
+ internal class ReceivedSmsWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) {
174
+ override fun doWork(): Result {
175
+ Timber.i("[${this.inputData.getString(Constants.KEY_MESSAGE_SIM)}] forwarding received message from [${this.inputData.getString(Constants.KEY_MESSAGE_FROM)}] to [${this.inputData.getString(Constants.KEY_MESSAGE_TO)}]")
176
+
177
+ val sim = this.inputData.getString(Constants.KEY_MESSAGE_SIM)!!
178
+ val from = this.inputData.getString(Constants.KEY_MESSAGE_FROM)!!
179
+ val to = this.inputData.getString(Constants.KEY_MESSAGE_TO)!!
180
+ val content = this.inputData.getString(Constants.KEY_MESSAGE_CONTENT)!!
181
+ val encrypted = this.inputData.getBoolean(Constants.KEY_MESSAGE_ENCRYPTED, false)
182
+ val timestamp = this.inputData.getString(Constants.KEY_MESSAGE_TIMESTAMP)!!
183
+
184
+ val attachmentsData = inputData.getStringArray(Constants.KEY_MESSAGE_ATTACHMENTS)
185
+ val attachments = attachmentsData?.mapNotNull {
186
+ val parts = it.split("|")
187
+ val file = File(parts[0])
188
+ if (file.exists()) {
189
+ val bytes = file.readBytes()
190
+ val base64Content = Base64.encodeToString(bytes, Base64.NO_WRAP)
191
+ ReceivedAttachment(
192
+ name = parts[2],
193
+ contentType = parts[1],
194
+ content = base64Content
195
+ )
196
+ } else {
197
+ null
198
+ }
199
+ }
200
+
201
+ val request = ReceivedMessageRequest(
202
+ sim = sim,
203
+ from = from,
204
+ to = to,
205
+ content = content,
206
+ encrypted = encrypted,
207
+ timestamp = timestamp,
208
+ attachments = attachments
209
+ )
210
+
211
+ val success = HttpSmsApiService.create(applicationContext).receive(request)
212
+
213
+ // Cleanup temp files
214
+ attachmentsData?.forEach {
215
+ val path = it.split("|")[0]
216
+ val file = File(path)
217
+ if (file.exists()) {
218
+ file.delete()
219
+ }
220
+ }
221
+
222
+ if (success) {
223
+ return Result.success()
224
+ }
225
+
226
+ return Result.retry()
227
+ }
228
+ }
229
+ }
android/app/src/main/java/com/httpsms/Receiver.kt ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms
2
+
3
+ import android.content.Context
4
+ import android.content.Context.RECEIVER_EXPORTED
5
+ import android.content.IntentFilter
6
+ import android.os.Build
7
+ import androidx.annotation.RequiresApi
8
+ import timber.log.Timber
9
+
10
+ object Receiver {
11
+ private var sentReceiver: SentReceiver? = null;
12
+ private var deliveredReceiver: DeliveredReceiver? = null;
13
+
14
+ fun register(context: Context) {
15
+ if(sentReceiver == null) {
16
+ Timber.d("registering [sent] receiver for intent [${SmsManagerService.sentAction()}]")
17
+ sentReceiver = SentReceiver()
18
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
19
+ context.registerReceiver(
20
+ sentReceiver,
21
+ IntentFilter(SmsManagerService.sentAction()),
22
+ RECEIVER_EXPORTED
23
+ )
24
+ } else {
25
+ context.registerReceiver(
26
+ sentReceiver,
27
+ IntentFilter(SmsManagerService.sentAction())
28
+ )
29
+ }
30
+ }
31
+
32
+ if(deliveredReceiver == null) {
33
+ Timber.d("registering [delivered] receiver for intent [${SmsManagerService.deliveredAction()}]")
34
+ deliveredReceiver = DeliveredReceiver()
35
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
36
+ context.registerReceiver(
37
+ deliveredReceiver,
38
+ IntentFilter(SmsManagerService.deliveredAction()),
39
+ RECEIVER_EXPORTED
40
+ )
41
+ } else {
42
+ context.registerReceiver(
43
+ deliveredReceiver,
44
+ IntentFilter(SmsManagerService.deliveredAction())
45
+ )
46
+ }
47
+ }
48
+ }
49
+
50
+ fun isValid(context: Context, messageId: String?): Boolean {
51
+ if (messageId == null) {
52
+ Timber.e("cannot handle event because the message ID is null")
53
+ return false
54
+ }
55
+
56
+ if (!Settings.isLoggedIn(context)) {
57
+ Timber.w("cannot handle message with id [$messageId] because the user is not logged in")
58
+ return false
59
+ }
60
+
61
+ if (!Settings.getActiveStatus(context, Constants.SIM1) && !Settings.getActiveStatus(context, Constants.SIM2)) {
62
+ Timber.w("cannot handle message with id [$messageId] because the user is not active")
63
+ return false
64
+ }
65
+
66
+ if(messageId.contains(".")) {
67
+ Timber.d("message id [${messageId}] is for multipart segment [${messageId.split(".")[1]}]")
68
+ return false
69
+ }
70
+
71
+ return true
72
+ }
73
+ }
android/app/src/main/java/com/httpsms/SentReceiver.kt ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms
2
+
3
+ import android.app.Activity
4
+ import android.content.BroadcastReceiver
5
+ import android.content.Context
6
+ import android.content.Intent
7
+ import android.telephony.SmsManager
8
+ import androidx.work.Constraints
9
+ import androidx.work.Data
10
+ import androidx.work.NetworkType
11
+ import androidx.work.OneTimeWorkRequest
12
+ import androidx.work.WorkManager
13
+ import androidx.work.Worker
14
+ import androidx.work.WorkerParameters
15
+ import androidx.work.workDataOf
16
+ import timber.log.Timber
17
+ import java.io.File
18
+
19
+ internal class SentReceiver : BroadcastReceiver() {
20
+ override fun onReceive(context: Context, intent: Intent) {
21
+ val messageId = intent.getStringExtra(Constants.KEY_MESSAGE_ID)
22
+ cleanupPduFile(context, messageId)
23
+ when (resultCode) {
24
+ Activity.RESULT_OK -> handleMessageSent(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID))
25
+ SmsManager.RESULT_ERROR_GENERIC_FAILURE -> handleMessageFailed(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID), "GENERIC_FAILURE")
26
+ SmsManager.RESULT_ERROR_NO_SERVICE -> handleMessageFailed(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID), "NO_SERVICE")
27
+ SmsManager.RESULT_ERROR_NULL_PDU -> handleMessageFailed(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID), "NULL_PDU")
28
+ SmsManager.RESULT_ERROR_RADIO_OFF -> handleMessageFailed(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID), "RADIO_OFF")
29
+ SmsManager.RESULT_ERROR_LIMIT_EXCEEDED -> handleMessageFailed(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID), "LIMIT_EXCEEDED")
30
+ else -> handleMessageFailed(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID), "UNKNOWN:${resultCode}")
31
+ }
32
+ }
33
+
34
+ private fun cleanupPduFile(context: Context, messageId: String?) {
35
+ if (messageId == null) return
36
+
37
+ try {
38
+ val baseMessageId = messageId.substringBefore(".")
39
+ val mmsDir = File(context.cacheDir, "mms_attachments")
40
+ val pduFile = File(mmsDir, "pdu_$baseMessageId.dat")
41
+
42
+ if (pduFile.exists()) {
43
+ if (pduFile.delete()) {
44
+ Timber.d("Cleaned up PDU file for message ID [$baseMessageId]")
45
+ } else {
46
+ Timber.w("Failed to delete PDU file for message ID [$baseMessageId]")
47
+ }
48
+ }
49
+ } catch (e: Exception) {
50
+ Timber.e(e, "Error cleaning up PDU file for message ID [$messageId]")
51
+ }
52
+ }
53
+
54
+ private fun handleMessageSent(context: Context, messageId: String?) {
55
+ if (!Receiver.isValid(context, messageId)) {
56
+ return
57
+ }
58
+
59
+ val constraints = Constraints.Builder()
60
+ .setRequiredNetworkType(NetworkType.CONNECTED)
61
+ .build()
62
+
63
+ val inputData: Data = workDataOf(
64
+ Constants.KEY_MESSAGE_ID to messageId,
65
+ Constants.KEY_MESSAGE_TIMESTAMP to Settings.currentTimestamp()
66
+ )
67
+
68
+ val work = OneTimeWorkRequest
69
+ .Builder(SentMessageWorker::class.java)
70
+ .setConstraints(constraints)
71
+ .setInputData(inputData)
72
+ .build()
73
+
74
+ WorkManager
75
+ .getInstance(context)
76
+ .enqueue(work)
77
+
78
+ Timber.d("work enqueued with ID [${work.id}] for [SENT] message with ID [${messageId}]")
79
+ }
80
+
81
+ private fun handleMessageFailed(context: Context, messageId: String?, reason: String) {
82
+ if (!Receiver.isValid(context, messageId)) {
83
+ return
84
+ }
85
+
86
+ val constraints = Constraints.Builder()
87
+ .setRequiredNetworkType(NetworkType.CONNECTED)
88
+ .build()
89
+
90
+ val inputData: Data = workDataOf(
91
+ Constants.KEY_MESSAGE_ID to messageId,
92
+ Constants.KEY_MESSAGE_REASON to reason,
93
+ Constants.KEY_MESSAGE_TIMESTAMP to Settings.currentTimestamp()
94
+ )
95
+
96
+ val work = OneTimeWorkRequest
97
+ .Builder(FailedMessageWorker::class.java)
98
+ .setConstraints(constraints)
99
+ .setInputData(inputData)
100
+ .build()
101
+
102
+ WorkManager
103
+ .getInstance(context)
104
+ .enqueue(work)
105
+
106
+ Timber.d("work enqueued with ID [${work.id}] for [FAILED] message with ID [${messageId}]")
107
+ }
108
+
109
+ internal class SentMessageWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) {
110
+ override fun doWork(): Result {
111
+ val messageId = this.inputData.getString(Constants.KEY_MESSAGE_ID)
112
+ val timestamp = this.inputData.getString(Constants.KEY_MESSAGE_TIMESTAMP)
113
+
114
+ Timber.i("[${timestamp}] sending [SENT] message event with ID [${messageId}]")
115
+
116
+ if (HttpSmsApiService.create(applicationContext).sendSentEvent(messageId!!, timestamp!!)){
117
+ return Result.success()
118
+ }
119
+ return Result.retry()
120
+ }
121
+ }
122
+
123
+ internal class FailedMessageWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) {
124
+ override fun doWork(): Result {
125
+ val messageId = this.inputData.getString(Constants.KEY_MESSAGE_ID)
126
+ val reason = this.inputData.getString(Constants.KEY_MESSAGE_REASON)
127
+ val timestamp = this.inputData.getString(Constants.KEY_MESSAGE_TIMESTAMP)
128
+
129
+ Timber.i("[${timestamp}] sending [FAILED] message event with ID [${messageId}] and reason [$reason]")
130
+
131
+ if (HttpSmsApiService.create(applicationContext).sendFailedEvent(messageId!!, timestamp!!, reason!!)){
132
+ return Result.success()
133
+ }
134
+ return Result.retry()
135
+ }
136
+ }
137
+ }
android/app/src/main/java/com/httpsms/Settings.kt ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms
2
+
3
+ import android.content.Context
4
+ import android.os.BatteryManager
5
+ import androidx.preference.PreferenceManager
6
+ import timber.log.Timber
7
+ import java.net.URI
8
+ import java.time.ZoneOffset
9
+ import java.time.ZonedDateTime
10
+ import java.time.format.DateTimeFormatter
11
+
12
+ object Settings {
13
+ private const val SETTINGS_SIM1_PHONE_NUMBER = "SETTINGS_SIM1_PHONE_NUMBER"
14
+ private const val SETTINGS_SIM2_PHONE_NUMBER = "SETTINGS_SIM2_PHONE_NUMBER"
15
+ private const val SETTINGS_SIM1_ACTIVE = "SETTINGS_SIM1_ACTIVE_STATUS"
16
+ private const val SETTINGS_SIM2_ACTIVE = "SETTINGS_SIM2_ACTIVE_STATUS"
17
+ private const val SETTINGS_SIM1_INCOMING_ACTIVE = "SETTINGS_SIM1_INCOMING_ACTIVE"
18
+ private const val SETTINGS_SIM2_INCOMING_ACTIVE = "SETTINGS_SIM2_INCOMING_ACTIVE"
19
+ private const val SETTINGS_SIM1_INCOMING_CALL_ACTIVE = "SETTINGS_SIM1_INCOMING_CALL_ACTIVE"
20
+ private const val SETTINGS_SIM2_INCOMING_CALL_ACTIVE = "SETTINGS_SIM2_INCOMING_CALL_ACTIVE"
21
+ private const val SETTINGS_DEBUG_LOG_ENABLED = "SETTINGS_DEBUG_LOG_ENABLED"
22
+ private const val SETTINGS_API_KEY = "SETTINGS_API_KEY"
23
+ private const val SETTINGS_SERVER_URL = "SETTINGS_SERVER_URL"
24
+ private const val SETTINGS_FCM_TOKEN = "SETTINGS_FCM_TOKEN"
25
+ private const val SETTINGS_USER_ID = "SETTINGS_USER_ID"
26
+ private const val SETTINGS_FCM_TOKEN_UPDATE_TIMESTAMP = "SETTINGS_FCM_TOKEN_UPDATE_TIMESTAMP"
27
+ private const val SETTINGS_HEARTBEAT_TIMESTAMP = "SETTINGS_HEARTBEAT_TIMESTAMP"
28
+ private const val SETTINGS_ENCRYPTION_KEY = "SETTINGS_ENCRYPTION_KEY"
29
+ private const val SETTINGS_ENCRYPT_RECEIVED_MESSAGES = "SETTINGS_ENCRYPT_RECEIVED_MESSAGES"
30
+
31
+ fun getPhoneNumber(context:Context, sim: String): String {
32
+ if (sim == Constants.SIM2) {
33
+ return getSIM2PhoneNumber(context)
34
+ }
35
+ return getSIM1PhoneNumber(context)
36
+ }
37
+
38
+ fun getSIM1PhoneNumber(context: Context): String {
39
+ Timber.d(Settings::getSIM1PhoneNumber.name)
40
+
41
+ val owner = PreferenceManager
42
+ .getDefaultSharedPreferences(context)
43
+ .getString(this.SETTINGS_SIM1_PHONE_NUMBER, null)
44
+
45
+ if (owner == null) {
46
+ Timber.i("cannot get owner from preference [${this.SETTINGS_SIM1_PHONE_NUMBER}]")
47
+ return ""
48
+ }
49
+
50
+ Timber.d("SETTINGS_SIM1_PHONE_NUMBER: [$owner]")
51
+ return owner
52
+ }
53
+
54
+ fun getSIM2PhoneNumber(context: Context): String {
55
+ Timber.d(Settings::getSIM2PhoneNumber.name)
56
+
57
+ val owner = PreferenceManager
58
+ .getDefaultSharedPreferences(context)
59
+ .getString(this.SETTINGS_SIM2_PHONE_NUMBER, null)
60
+
61
+ if (owner == null) {
62
+ Timber.i("cannot get owner from preference [${this.SETTINGS_SIM2_PHONE_NUMBER}]")
63
+ return ""
64
+ }
65
+
66
+ Timber.d("SETTINGS_SIM2_PHONE_NUMBER: [$owner]")
67
+ return owner
68
+ }
69
+
70
+ fun hasOwner(context: Context): Boolean {
71
+ return getSIM1PhoneNumber(context) != ""
72
+ }
73
+
74
+ fun getFcmTokenLastUpdateTimestamp(context: Context): Long {
75
+ Timber.d(Settings::getFcmTokenLastUpdateTimestamp.name)
76
+
77
+ val timestamp = PreferenceManager
78
+ .getDefaultSharedPreferences(context)
79
+ .getLong(this.SETTINGS_FCM_TOKEN_UPDATE_TIMESTAMP,0)
80
+
81
+ Timber.d("SETTINGS_FCM_TOKEN_UPDATE_TIMESTAMP: [$timestamp]")
82
+ return timestamp
83
+ }
84
+
85
+
86
+ fun setFcmTokenLastUpdateTimestampAsync(context: Context, timestamp: Long) {
87
+ Timber.d(Settings::setFcmTokenLastUpdateTimestampAsync.name)
88
+
89
+ PreferenceManager.getDefaultSharedPreferences(context)
90
+ .edit()
91
+ .putLong(this.SETTINGS_FCM_TOKEN_UPDATE_TIMESTAMP, timestamp)
92
+ .apply()
93
+ }
94
+
95
+ fun setSIM1PhoneNumber(context: Context, owner: String?) {
96
+ Timber.d(Settings::setSIM1PhoneNumber.name)
97
+
98
+ PreferenceManager.getDefaultSharedPreferences(context)
99
+ .edit()
100
+ .putString(this.SETTINGS_SIM1_PHONE_NUMBER, owner)
101
+ .apply()
102
+ }
103
+
104
+ fun setSIM2PhoneNumber(context: Context, owner: String?) {
105
+ Timber.d(Settings::setSIM2PhoneNumber.name)
106
+
107
+ PreferenceManager.getDefaultSharedPreferences(context)
108
+ .edit()
109
+ .putString(this.SETTINGS_SIM2_PHONE_NUMBER, owner)
110
+ .apply()
111
+ }
112
+
113
+ fun isIncomingMessageEnabled(context: Context, sim: String): Boolean {
114
+ var setting = this.SETTINGS_SIM1_INCOMING_ACTIVE
115
+ if (sim == Constants.SIM2) {
116
+ setting = this.SETTINGS_SIM2_INCOMING_ACTIVE
117
+ }
118
+ val activeStatus = PreferenceManager
119
+ .getDefaultSharedPreferences(context)
120
+ .getBoolean(setting,true)
121
+
122
+ Timber.d("SETTINGS_${sim}_INCOMING_ACTIVE: [$activeStatus]")
123
+ return activeStatus
124
+ }
125
+
126
+ fun isIncomingCallEventsEnabled(context: Context, sim: String): Boolean {
127
+ var setting = this.SETTINGS_SIM1_INCOMING_CALL_ACTIVE
128
+ if (sim == Constants.SIM2) {
129
+ setting = this.SETTINGS_SIM2_INCOMING_CALL_ACTIVE
130
+ }
131
+ val activeStatus = PreferenceManager
132
+ .getDefaultSharedPreferences(context)
133
+ .getBoolean(setting,false)
134
+
135
+ Timber.d("SETTINGS_${sim}_INCOMING_CALL_ACTIVE: [$activeStatus]")
136
+ return activeStatus
137
+ }
138
+
139
+ fun setIncomingCallEventsEnabled(context: Context, sim: String, enabled: Boolean) {
140
+ var setting = this.SETTINGS_SIM1_INCOMING_CALL_ACTIVE
141
+ if (sim == Constants.SIM2) {
142
+ setting = this.SETTINGS_SIM2_INCOMING_CALL_ACTIVE
143
+ }
144
+
145
+ PreferenceManager.getDefaultSharedPreferences(context)
146
+ .edit()
147
+ .putBoolean(setting, enabled)
148
+ .apply()
149
+ }
150
+
151
+
152
+ fun isDebugLogEnabled(context: Context) : Boolean {
153
+ Timber.d(Settings::isDebugLogEnabled.name)
154
+
155
+ return PreferenceManager
156
+ .getDefaultSharedPreferences(context)
157
+ .getBoolean(this.SETTINGS_DEBUG_LOG_ENABLED, false)
158
+ }
159
+
160
+ fun setDebugLogEnabled(context: Context, status: Boolean) {
161
+ Timber.d(Settings::setDebugLogEnabled.name)
162
+
163
+ PreferenceManager.getDefaultSharedPreferences(context)
164
+ .edit()
165
+ .putBoolean(this.SETTINGS_DEBUG_LOG_ENABLED, status)
166
+ .apply()
167
+ }
168
+
169
+ fun setIncomingActiveSIM1(context: Context, status: Boolean) {
170
+ Timber.d(Settings::setIncomingActiveSIM1.name)
171
+
172
+ PreferenceManager.getDefaultSharedPreferences(context)
173
+ .edit()
174
+ .putBoolean(this.SETTINGS_SIM1_INCOMING_ACTIVE, status)
175
+ .apply()
176
+ }
177
+
178
+ fun setEncryptReceivedMessages(context: Context, status: Boolean) {
179
+ Timber.d(Settings::setEncryptReceivedMessages.name)
180
+
181
+ PreferenceManager.getDefaultSharedPreferences(context)
182
+ .edit()
183
+ .putBoolean(this.SETTINGS_ENCRYPT_RECEIVED_MESSAGES, status)
184
+ .apply()
185
+ }
186
+
187
+ fun encryptReceivedMessages(context: Context): Boolean {
188
+ Timber.d(Settings::encryptReceivedMessages.name)
189
+
190
+ val encryptReceivedMessages = PreferenceManager
191
+ .getDefaultSharedPreferences(context)
192
+ .getBoolean(this.SETTINGS_ENCRYPT_RECEIVED_MESSAGES,false)
193
+
194
+ Timber.d("SETTINGS_ENCRYPT_RECEIVED_MESSAGES: [$encryptReceivedMessages]")
195
+ return encryptReceivedMessages && !getEncryptionKey(context).isNullOrEmpty()
196
+ }
197
+
198
+ fun setEncryptionKey(context: Context, key: String?) {
199
+ Timber.d(Settings::setEncryptionKey.name)
200
+
201
+ PreferenceManager.getDefaultSharedPreferences(context)
202
+ .edit()
203
+ .putString(this.SETTINGS_ENCRYPTION_KEY, key)
204
+ .apply()
205
+ }
206
+
207
+ fun getEncryptionKey(context: Context): String? {
208
+ Timber.d(Settings::getEncryptionKey.name)
209
+
210
+ return PreferenceManager
211
+ .getDefaultSharedPreferences(context)
212
+ .getString(this.SETTINGS_ENCRYPTION_KEY, "")
213
+ }
214
+
215
+ fun setIncomingActiveSIM2(context: Context, status: Boolean) {
216
+ Timber.d(Settings::setIncomingActiveSIM2.name)
217
+
218
+ PreferenceManager.getDefaultSharedPreferences(context)
219
+ .edit()
220
+ .putBoolean(this.SETTINGS_SIM2_INCOMING_ACTIVE, status)
221
+ .apply()
222
+ }
223
+
224
+
225
+ fun getActiveStatus(context: Context, sim: String): Boolean {
226
+ var setting = this.SETTINGS_SIM1_ACTIVE
227
+ if (sim == Constants.SIM2) {
228
+ setting = this.SETTINGS_SIM2_ACTIVE
229
+ }
230
+ var activeStatus = PreferenceManager
231
+ .getDefaultSharedPreferences(context)
232
+ .getBoolean(setting,true)
233
+
234
+ if (sim == Constants.SIM2) {
235
+ activeStatus = activeStatus && isDualSIM(context)
236
+ }
237
+
238
+ Timber.d("SETTINGS_${sim}_ACTIVE: [$activeStatus]")
239
+ return activeStatus
240
+ }
241
+
242
+ fun setActiveStatusAsync(context: Context, status: Boolean, sim: String) {
243
+ Timber.d(Settings::setActiveStatusAsync.name)
244
+
245
+ var setting = this.SETTINGS_SIM1_ACTIVE
246
+ if (sim == Constants.SIM2) {
247
+ setting = this.SETTINGS_SIM2_ACTIVE
248
+ }
249
+
250
+ PreferenceManager.getDefaultSharedPreferences(context)
251
+ .edit()
252
+ .putBoolean(setting, status)
253
+ .apply()
254
+ }
255
+
256
+ fun isLoggedIn(context: Context): Boolean {
257
+ return getApiKey(context) != null && hasOwner(context)
258
+ }
259
+
260
+ fun isDualSIM(context: Context): Boolean {
261
+ return getSIM1PhoneNumber(context) != "" && getSIM2PhoneNumber(context) != ""
262
+ }
263
+
264
+ private fun getApiKey(context: Context): String?{
265
+ Timber.d(Settings::getApiKey.name)
266
+
267
+ val apiKey = PreferenceManager
268
+ .getDefaultSharedPreferences(context)
269
+ .getString(this.SETTINGS_API_KEY,null)
270
+
271
+ Timber.d("SETTINGS_API_KEY: [$apiKey]")
272
+ return apiKey
273
+ }
274
+
275
+ fun getApiKeyOrDefault(context:Context): String {
276
+ return getApiKey(context) ?: ""
277
+ }
278
+
279
+ fun isCharging(context: Context): Boolean {
280
+ val myBatteryManager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
281
+ return myBatteryManager.isCharging
282
+ }
283
+
284
+ fun setUserID(context:Context, userID: String?) {
285
+ Timber.d(Settings::setUserID.name)
286
+ PreferenceManager.getDefaultSharedPreferences(context)
287
+ .edit()
288
+ .putString(this.SETTINGS_USER_ID, userID)
289
+ .apply()
290
+ }
291
+
292
+ // getUserID don't log here as this will create recursion on the LogTail sink
293
+ fun getUserID(context:Context): String {
294
+ val userID = PreferenceManager
295
+ .getDefaultSharedPreferences(context)
296
+ .getString(this.SETTINGS_USER_ID,null)
297
+ return userID ?: ""
298
+ }
299
+
300
+ fun getServerUrlOrDefault(context:Context): URI {
301
+ val urlString = getServerUrl(context) ?: "https://red-kit-httpsms-gateway.hf.space"
302
+ return URI(urlString)
303
+ }
304
+
305
+ private fun getServerUrl(context: Context): String? {
306
+ Timber.d(Settings::getServerUrl.name)
307
+
308
+ val serverUrl = PreferenceManager
309
+ .getDefaultSharedPreferences(context)
310
+ .getString(this.SETTINGS_SERVER_URL,null)
311
+
312
+ Timber.d("SETTINGS_SERVER_URL: [$serverUrl]")
313
+ return serverUrl
314
+ }
315
+
316
+ fun setServerUrlAsync(context: Context, serverURL: String?) {
317
+ Timber.d(Settings::SETTINGS_SERVER_URL.name)
318
+
319
+ PreferenceManager.getDefaultSharedPreferences(context)
320
+ .edit()
321
+ .putString(this.SETTINGS_SERVER_URL, serverURL)
322
+ .apply()
323
+ }
324
+
325
+ fun setApiKeyAsync(context: Context, apiKey: String?) {
326
+ Timber.d(Settings::setApiKeyAsync.name)
327
+
328
+ PreferenceManager.getDefaultSharedPreferences(context)
329
+ .edit()
330
+ .putString(this.SETTINGS_API_KEY, apiKey)
331
+ .apply()
332
+ }
333
+
334
+ fun getFcmToken(context: Context): String?{
335
+ Timber.d(Settings::getFcmToken.name)
336
+
337
+ val activeStatus = PreferenceManager
338
+ .getDefaultSharedPreferences(context)
339
+ .getString(this.SETTINGS_FCM_TOKEN,null)
340
+
341
+ Timber.d("SETTINGS_FCM_TOKEN: [$activeStatus]")
342
+ return activeStatus
343
+ }
344
+
345
+ fun setFcmTokenAsync(context: Context, apiKey: String) {
346
+ Timber.d(Settings::setApiKeyAsync.name)
347
+
348
+ PreferenceManager.getDefaultSharedPreferences(context)
349
+ .edit()
350
+ .putString(this.SETTINGS_FCM_TOKEN, apiKey)
351
+ .apply()
352
+ }
353
+
354
+ fun getHeartbeatTimestamp(context: Context): Long {
355
+ Timber.d(Settings::getHeartbeatTimestamp.name)
356
+
357
+ val timestamp = PreferenceManager
358
+ .getDefaultSharedPreferences(context)
359
+ .getLong(this.SETTINGS_HEARTBEAT_TIMESTAMP,0)
360
+
361
+ Timber.d("SETTINGS_HEARTBEAT_TIMESTAMP: [$timestamp]")
362
+ return timestamp
363
+ }
364
+
365
+ fun currentTimestamp(): String {
366
+ return DateTimeFormatter.ofPattern(Constants.TIMESTAMP_PATTERN).format(
367
+ ZonedDateTime.now(ZoneOffset.UTC)
368
+ ).replace("+", "Z")
369
+ }
370
+
371
+
372
+ fun setHeartbeatTimestampAsync(context: Context, timestamp: Long) {
373
+ Timber.d(Settings::setHeartbeatTimestampAsync.name)
374
+
375
+ PreferenceManager.getDefaultSharedPreferences(context)
376
+ .edit()
377
+ .putLong(this.SETTINGS_HEARTBEAT_TIMESTAMP, timestamp)
378
+ .apply()
379
+ }
380
+ }
android/app/src/main/java/com/httpsms/SettingsActivity.kt ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms
2
+
3
+ import android.content.Intent
4
+ import android.os.Bundle
5
+ import androidx.activity.compose.setContent
6
+ import androidx.activity.viewModels
7
+ import androidx.appcompat.app.AppCompatActivity
8
+ import com.google.android.material.dialog.MaterialAlertDialogBuilder
9
+ import com.httpsms.ui.settings.SettingsScreen
10
+ import com.httpsms.ui.settings.SettingsViewModel
11
+ import com.httpsms.ui.theme.HttpSmsTheme
12
+ import timber.log.Timber
13
+
14
+ class SettingsActivity : AppCompatActivity() {
15
+ private val viewModel: SettingsViewModel by viewModels()
16
+
17
+ override fun onCreate(savedInstanceState: Bundle?) {
18
+ super.onCreate(savedInstanceState)
19
+
20
+ viewModel.initialize(this)
21
+
22
+ setContent {
23
+ HttpSmsTheme {
24
+ SettingsScreen(
25
+ viewModel = viewModel,
26
+ onBackClick = { onBackClicked() },
27
+ onLogoutClick = { onLogoutClick() }
28
+ )
29
+ }
30
+ }
31
+ }
32
+
33
+ private fun onBackClicked() {
34
+ Timber.d("back button clicked")
35
+ redirectToMain()
36
+ }
37
+
38
+ private fun redirectToMain() {
39
+ finish()
40
+ val switchActivityIntent = Intent(this, MainActivity::class.java)
41
+ startActivity(switchActivityIntent)
42
+ }
43
+
44
+ private fun onLogoutClick() {
45
+ Timber.d("logout button clicked")
46
+ MaterialAlertDialogBuilder(this)
47
+ .setTitle("Confirm")
48
+ .setMessage("Are you sure you want to logout of the httpSMS App?")
49
+ .setNeutralButton("Cancel"){ _, _ -> Timber.d("logout dialog canceled") }
50
+ .setPositiveButton("Logout"){_, _ ->
51
+ Timber.d("logging out user")
52
+ viewModel.logout(this) {
53
+ redirectToLogin()
54
+ }
55
+ }
56
+ .show()
57
+ }
58
+
59
+ private fun redirectToLogin():Boolean {
60
+ if (Settings.isLoggedIn(this)) {
61
+ return false
62
+ }
63
+ val switchActivityIntent = Intent(this, LoginActivity::class.java)
64
+ startActivity(switchActivityIntent)
65
+ return true
66
+ }
67
+ }
android/app/src/main/java/com/httpsms/SmsManagerService.kt ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms
2
+
3
+ import android.Manifest
4
+ import android.annotation.SuppressLint
5
+ import android.app.PendingIntent
6
+ import android.content.Context
7
+ import android.content.pm.PackageManager
8
+ import android.os.Build
9
+ import android.telephony.SmsManager
10
+ import android.telephony.SubscriptionManager
11
+ import androidx.core.app.ActivityCompat
12
+ import timber.log.Timber
13
+
14
+
15
+ class SmsManagerService {
16
+ companion object {
17
+ private const val ACTION_SMS_SENT = "SMS_SENT"
18
+ private const val ACTION_SMS_DELIVERED = "SMS_DELIVERED"
19
+
20
+ fun sentAction(): String {
21
+ return "${BuildConfig.APPLICATION_ID}.$ACTION_SMS_SENT"
22
+ }
23
+
24
+ fun deliveredAction(): String {
25
+ return "${BuildConfig.APPLICATION_ID}.$ACTION_SMS_DELIVERED"
26
+ }
27
+
28
+ fun isDualSIM(context: Context) : Boolean {
29
+ if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
30
+ ) {
31
+ Timber.w("cannot check if dual sim, no permission")
32
+ return false
33
+ }
34
+ val localSubscriptionManager: SubscriptionManager = if (Build.VERSION.SDK_INT < 31) {
35
+ SubscriptionManager.from(context)
36
+ } else {
37
+ context.getSystemService(SubscriptionManager::class.java)
38
+ }
39
+ return (localSubscriptionManager.activeSubscriptionInfoList?.size ?: 0) > 1
40
+ }
41
+ }
42
+
43
+ fun messageParts(context: Context, content: String): ArrayList<String> {
44
+ return getSmsManager(context).divideMessage(content)
45
+ }
46
+
47
+ fun sendMultipartMessage(context: Context, contact: String, parts: ArrayList<String>, sim: String, sendIntents: ArrayList<PendingIntent>, deliveryIntents: ArrayList<PendingIntent>) {
48
+ runSmsAction(context, sim) { smsManager ->
49
+ smsManager.sendMultipartTextMessage(contact, null, parts, sendIntents, deliveryIntents)
50
+ }
51
+ }
52
+
53
+ fun sendTextMessage(context: Context, contact: String, content: String, sim: String, sentIntent: PendingIntent, deliveryIntent: PendingIntent) {
54
+ runSmsAction(context, sim) { smsManager ->
55
+ smsManager.sendTextMessage(contact, null, content, sentIntent, deliveryIntent)
56
+ }
57
+ }
58
+
59
+ // Wrapper for the smsManager's sendMultimediaMessage
60
+ fun sendMultimediaMessage(context: Context, pduUri: android.net.Uri, sim: String, sentIntent: PendingIntent) {
61
+ runSmsAction(context, sim) { smsManager ->
62
+ smsManager.sendMultimediaMessage(context, pduUri, null, null, sentIntent)
63
+ }
64
+ }
65
+
66
+ private fun runSmsAction(context: Context, sim: String, action: (SmsManager) -> Unit) {
67
+ try {
68
+ action(getSmsManager(context, sim))
69
+ } catch (e: NullPointerException) {
70
+ if (e.isEmergencyNumberBug()) {
71
+ Timber.w(e, "Caught EmergencyNumber NPE, falling back to default SmsManager")
72
+ action(getDefaultSmsManager(context))
73
+ } else {
74
+ throw e
75
+ }
76
+ }
77
+ }
78
+
79
+ private fun Throwable.isEmergencyNumberBug(): Boolean {
80
+ return this is NullPointerException && this.message?.contains("EmergencyNumber.getNumber()") == true
81
+ }
82
+
83
+ @Suppress("DEPRECATION")
84
+ private fun getDefaultSmsManager(context: Context): SmsManager {
85
+ return if (Build.VERSION.SDK_INT >= 31) {
86
+ context.getSystemService(SmsManager::class.java)
87
+ } else {
88
+ SmsManager.getDefault()
89
+ }
90
+ }
91
+
92
+ @Suppress("DEPRECATION")
93
+ @SuppressLint("MissingPermission")
94
+ private fun getSmsManager(context: Context, sim: String = Constants.SIM1): SmsManager {
95
+ val localSubscriptionManager: SubscriptionManager = if (Build.VERSION.SDK_INT < 31) {
96
+ SubscriptionManager.from(context)
97
+ } else {
98
+ context.getSystemService(SubscriptionManager::class.java)
99
+ }
100
+
101
+ val infoList = localSubscriptionManager.activeSubscriptionInfoList
102
+ Timber.d("active subscription info size: [${infoList?.size ?: 0}]")
103
+
104
+ val subscriptionId = if (sim == Constants.SIM1 && !infoList.isNullOrEmpty()) {
105
+ infoList[0].subscriptionId
106
+ } else if (sim == Constants.SIM2 && (infoList?.size ?: 0) > 1) {
107
+ infoList!![1].subscriptionId
108
+ } else{
109
+ SubscriptionManager.getDefaultSmsSubscriptionId()
110
+ }
111
+
112
+ if (subscriptionId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
113
+ return getDefaultSmsManager(context)
114
+ }
115
+
116
+ return if (Build.VERSION.SDK_INT < 31) {
117
+ SmsManager.getSmsManagerForSubscriptionId(subscriptionId)
118
+ } else {
119
+ context.getSystemService(SmsManager::class.java).createForSubscriptionId(subscriptionId)
120
+ }
121
+ }
122
+ }
android/app/src/main/java/com/httpsms/receivers/BootReceiver.kt ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms.receivers
2
+
3
+ import android.content.BroadcastReceiver
4
+ import android.content.Context
5
+ import android.content.Intent
6
+ import com.httpsms.Constants
7
+ import com.httpsms.Settings
8
+ import com.httpsms.services.StickyNotificationService
9
+ import timber.log.Timber
10
+
11
+
12
+ class BootReceiver : BroadcastReceiver() {
13
+ override fun onReceive(context: Context, intent: Intent) {
14
+ if (intent.action == Intent.ACTION_BOOT_COMPLETED) {
15
+ startStickyNotification(context)
16
+ } else {
17
+ Timber.e("invalid intent [${intent.action}]")
18
+ }
19
+ }
20
+ private fun startStickyNotification(context: Context) {
21
+ if(!Settings.getActiveStatus(context, Constants.SIM1) && !Settings.getActiveStatus(context, Constants.SIM2)) {
22
+ Timber.d("active status is false, not starting foreground service")
23
+ return
24
+ }
25
+
26
+ Timber.d("starting foreground service")
27
+ val notificationIntent = Intent(context, StickyNotificationService::class.java)
28
+ val service = context.startForegroundService(notificationIntent)
29
+ Timber.d("foreground service started [${service?.className}]")
30
+ }
31
+ }
android/app/src/main/java/com/httpsms/receivers/PhoneStateReceiver.kt ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms.receivers
2
+
3
+ import android.annotation.SuppressLint
4
+ import android.content.BroadcastReceiver
5
+ import android.content.Context
6
+ import android.content.Intent
7
+ import android.os.Build
8
+ import android.provider.CallLog
9
+ import android.telephony.SubscriptionManager
10
+ import android.telephony.TelephonyManager
11
+ import androidx.work.Constraints
12
+ import androidx.work.Data
13
+ import androidx.work.NetworkType
14
+ import androidx.work.OneTimeWorkRequest
15
+ import androidx.work.WorkManager
16
+ import androidx.work.Worker
17
+ import androidx.work.WorkerParameters
18
+ import androidx.work.workDataOf
19
+ import com.httpsms.Constants
20
+ import com.httpsms.HttpSmsApiService
21
+ import com.httpsms.Settings
22
+ import timber.log.Timber
23
+ import java.time.Instant
24
+ import java.time.ZoneOffset
25
+ import java.time.ZonedDateTime
26
+ import java.time.format.DateTimeFormatter
27
+
28
+
29
+ class PhoneStateReceiver : BroadcastReceiver() {
30
+ override fun onReceive(context: Context, intent: Intent) {
31
+ Timber.d("onReceive: ${intent.action}")
32
+ val stateStr = intent.extras!!.getString(TelephonyManager.EXTRA_STATE)
33
+
34
+ @Suppress("DEPRECATION")
35
+ val number = intent.extras!!.getString(TelephonyManager.EXTRA_INCOMING_NUMBER)
36
+ if (stateStr != "IDLE" || number == null) {
37
+ Timber.d("event is not a missed call or permission is not granted state = [${stateStr}]")
38
+ return
39
+ }
40
+
41
+ // Sleep so that the call gets added into the call log
42
+ Thread.sleep(200)
43
+
44
+ val lastCall = getCallLog(context, number)
45
+ if (lastCall == null) {
46
+ Timber.d("The call from [${number}] was not a missed call.")
47
+ return
48
+ }
49
+
50
+ handleMissedCallEvent(context, number, lastCall)
51
+ }
52
+
53
+ private fun handleMissedCallEvent(context: Context, contact: String, callLog: Pair<ZonedDateTime, String>) {
54
+ val (timestamp, sim) = callLog
55
+ val owner = Settings.getPhoneNumber(context, sim)
56
+
57
+ if (!Settings.isLoggedIn(context)) {
58
+ Timber.w("[${sim}] user is not logged in")
59
+ return
60
+ }
61
+
62
+ if (!Settings.isIncomingCallEventsEnabled(context, callLog.second)) {
63
+ Timber.w("[${sim}] incoming call events is not enabled")
64
+ return
65
+ }
66
+
67
+ val constraints = Constraints.Builder()
68
+ .setRequiredNetworkType(NetworkType.CONNECTED)
69
+ .build()
70
+
71
+ val inputData: Data = workDataOf(
72
+ Constants.KEY_MESSAGE_FROM to contact,
73
+ Constants.KEY_MESSAGE_SIM to sim,
74
+ Constants.KEY_MESSAGE_TO to owner,
75
+ Constants.KEY_MESSAGE_TIMESTAMP to DateTimeFormatter.ofPattern(Constants.TIMESTAMP_PATTERN).format(timestamp).replace("+", "Z")
76
+ )
77
+
78
+ val work = OneTimeWorkRequest
79
+ .Builder(MissedCallWorker::class.java)
80
+ .setConstraints(constraints)
81
+ .setInputData(inputData)
82
+ .build()
83
+
84
+ WorkManager
85
+ .getInstance(context)
86
+ .enqueue(work)
87
+
88
+ Timber.d("work enqueued with ID [${work.id}] for missed phone call from [${contact}] to [${owner}] in [${sim}]")
89
+ }
90
+
91
+ @SuppressLint("MissingPermission")
92
+ private fun getSlotIndexFromSubscriptionId(context: Context, subscriptionId: Int): String {
93
+ val localSubscriptionManager: SubscriptionManager = if (Build.VERSION.SDK_INT < 31) {
94
+ @Suppress("DEPRECATION")
95
+ SubscriptionManager.from(context)
96
+ } else {
97
+ context.getSystemService(SubscriptionManager::class.java)
98
+ }
99
+
100
+ var sim = Constants.SIM1
101
+ localSubscriptionManager.activeSubscriptionInfoList!!.forEach {
102
+ if (it.subscriptionId == subscriptionId) {
103
+ if (it.simSlotIndex > 0){
104
+ sim = Constants.SIM2
105
+ }
106
+ }
107
+ }
108
+ return sim
109
+ }
110
+
111
+ private fun getCallLog(context: Context, phoneNumber: String): Pair<ZonedDateTime, String>? {
112
+ // Specify the columns you want to retrieve from the call log
113
+ val projection = arrayOf(CallLog.Calls.NUMBER, CallLog.Calls.DATE, CallLog.Calls.TYPE, CallLog.Calls.PHONE_ACCOUNT_ID)
114
+
115
+ // Query the call log content provider
116
+ val cursor = context.contentResolver.query(
117
+ CallLog.Calls.CONTENT_URI,
118
+ projection,
119
+ null,
120
+ null,
121
+ CallLog.Calls.DATE + " DESC" // Order by date in descending order
122
+ )
123
+
124
+ // Check if the cursor is not null and contains at least one entry
125
+ if (cursor != null && cursor.moveToFirst()) {
126
+ val number = cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.NUMBER))
127
+ if (number != phoneNumber) {
128
+ Timber.w("last phone call has phone number [${number}] but the expected phone number was [${phoneNumber}]")
129
+ return null
130
+ }
131
+
132
+ if (cursor.getInt(cursor.getColumnIndexOrThrow(CallLog.Calls.TYPE)) != CallLog.Calls.MISSED_TYPE) {
133
+ Timber.w("last phone call from phone number was [${phoneNumber}] was not a missed call")
134
+ return null
135
+ }
136
+
137
+ val date = cursor.getLong(cursor.getColumnIndexOrThrow(CallLog.Calls.DATE))
138
+ val sim = getSlotIndexFromSubscriptionId(context, cursor.getInt(cursor.getColumnIndexOrThrow(CallLog.Calls.PHONE_ACCOUNT_ID)))
139
+
140
+ // Convert date to a readable format (optional)
141
+ val dateString = java.text.DateFormat.getDateTimeInstance().format(date)
142
+ Timber.d("missed call date is [${dateString}], SIM = [${sim}]")
143
+
144
+ // Close the cursor to free up resources
145
+ cursor.close()
146
+
147
+ // Construct a string representing the last call
148
+ return Pair(ZonedDateTime.ofInstant(Instant.ofEpochMilli(date), ZoneOffset.UTC), sim)
149
+ }
150
+
151
+ // Close the cursor if it's not null even if it doesn't contain any data
152
+ cursor?.close()
153
+
154
+ // Return null if no calls are found
155
+ return null
156
+ }
157
+
158
+ internal class MissedCallWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) {
159
+ override fun doWork(): Result {
160
+ Timber.i("[${this.inputData.getString(Constants.KEY_MESSAGE_SIM)}] forwarding missed call from [${this.inputData.getString(Constants.KEY_MESSAGE_FROM)}] to [${this.inputData.getString(Constants.KEY_MESSAGE_TO)}]")
161
+
162
+ if (HttpSmsApiService.create(applicationContext).sendMissedCallEvent(
163
+ this.inputData.getString(Constants.KEY_MESSAGE_SIM)!!,
164
+ this.inputData.getString(Constants.KEY_MESSAGE_FROM)!!,
165
+ this.inputData.getString(Constants.KEY_MESSAGE_TO)!!,
166
+ this.inputData.getString(Constants.KEY_MESSAGE_TIMESTAMP)!!,
167
+ )) {
168
+ return Result.success()
169
+ }
170
+
171
+ return Result.retry()
172
+ }
173
+ }
174
+ }
android/app/src/main/java/com/httpsms/services/StickyNotificationService.kt ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms.services
2
+
3
+ import android.app.*
4
+ import android.content.Context
5
+ import android.content.Intent
6
+ import android.os.IBinder
7
+ import android.widget.Toast
8
+ import com.httpsms.MainActivity
9
+ import com.httpsms.R
10
+ import timber.log.Timber
11
+
12
+ class StickyNotificationService: Service() {
13
+ override fun onBind(intent: Intent?): IBinder? {
14
+ Timber.d("Some component want to bind with the service [${intent?.action}]")
15
+ return null
16
+ }
17
+
18
+ override fun onCreate() {
19
+ Timber.d("The service has been created")
20
+ super.onCreate()
21
+ val notification = createNotification()
22
+ startForeground(1, notification)
23
+ }
24
+
25
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
26
+ Timber.d("onStartCommand executed with startId: $startId")
27
+ // by returning this we make sure the service is restarted if the system kills the service
28
+ return START_STICKY
29
+ }
30
+
31
+ override fun onDestroy() {
32
+ super.onDestroy()
33
+ Timber.d("The service has been destroyed")
34
+ Toast.makeText(this, "Service destroyed", Toast.LENGTH_SHORT).show()
35
+ }
36
+
37
+
38
+ private fun createNotification(): Notification {
39
+ val notificationChannelId = "sticky_notification_channel"
40
+
41
+ // depending on the Android API that we're dealing with we will have
42
+ // to use a specific method to create the notification
43
+ val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
44
+ val channel = NotificationChannel(
45
+ notificationChannelId,
46
+ notificationChannelId,
47
+ NotificationManager.IMPORTANCE_HIGH
48
+ ).apply {
49
+ enableVibration(false)
50
+ setShowBadge(false)
51
+ }
52
+ notificationManager.createNotificationChannel(channel)
53
+
54
+ val pendingIntent: PendingIntent = Intent(this, MainActivity::class.java).let {
55
+ notificationIntent -> PendingIntent.getActivity(
56
+ this,
57
+ 0,
58
+ notificationIntent,
59
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
60
+ }
61
+
62
+ val builder: Notification.Builder = Notification.Builder(
63
+ this,
64
+ notificationChannelId
65
+ )
66
+
67
+ return builder
68
+ .setContentTitle("httpSMS Listener")
69
+ .setContentText("httpSMS is listening for sent and received SMS messages in the background.")
70
+ .setContentIntent(pendingIntent)
71
+ .setOngoing(true)
72
+ .setSmallIcon(R.drawable.ic_stat_name)
73
+ .build()
74
+ }
75
+ }
android/app/src/main/java/com/httpsms/ui/login/LoginActivityContent.kt ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms.ui.login
2
+
3
+ import androidx.compose.foundation.Image
4
+ import androidx.compose.foundation.layout.Column
5
+ import androidx.compose.foundation.layout.PaddingValues
6
+ import androidx.compose.foundation.layout.Spacer
7
+ import androidx.compose.foundation.layout.fillMaxSize
8
+ import androidx.compose.foundation.layout.fillMaxWidth
9
+ import androidx.compose.foundation.layout.height
10
+ import androidx.compose.foundation.layout.padding
11
+ import androidx.compose.foundation.layout.size
12
+ import androidx.compose.foundation.rememberScrollState
13
+ import androidx.compose.foundation.text.ClickableText
14
+ import androidx.compose.foundation.text.KeyboardOptions
15
+ import androidx.compose.foundation.verticalScroll
16
+ import androidx.compose.material.icons.Icons
17
+ import androidx.compose.material.icons.filled.QrCodeScanner
18
+ import androidx.compose.material3.Button
19
+ import androidx.compose.material3.ButtonDefaults
20
+ import androidx.compose.material3.CircularProgressIndicator
21
+ import androidx.compose.material3.Icon
22
+ import androidx.compose.material3.IconButton
23
+ import androidx.compose.material3.MaterialTheme
24
+ import androidx.compose.material3.OutlinedTextField
25
+ import androidx.compose.material3.Text
26
+ import androidx.compose.runtime.Composable
27
+ import androidx.compose.runtime.collectAsState
28
+ import androidx.compose.runtime.getValue
29
+ import androidx.compose.ui.Alignment
30
+ import androidx.compose.ui.Modifier
31
+ import androidx.compose.ui.graphics.Color
32
+ import androidx.compose.ui.platform.LocalUriHandler
33
+ import androidx.compose.ui.res.painterResource
34
+ import androidx.compose.ui.res.stringResource
35
+ import androidx.compose.ui.text.SpanStyle
36
+ import androidx.compose.ui.text.buildAnnotatedString
37
+ import androidx.compose.ui.text.font.FontWeight
38
+ import androidx.compose.ui.text.input.ImeAction
39
+ import androidx.compose.ui.text.input.KeyboardType
40
+ import androidx.compose.ui.text.style.TextAlign
41
+ import androidx.compose.ui.text.withStyle
42
+ import androidx.compose.ui.unit.dp
43
+ import androidx.compose.ui.unit.sp
44
+ import com.httpsms.R
45
+ import com.httpsms.ui.theme.Blue500
46
+ import com.httpsms.ui.theme.Pink500
47
+
48
+ @Composable
49
+ fun LoginScreen(
50
+ viewModel: LoginViewModel,
51
+ onQrScanClick: () -> Unit,
52
+ onLoginClick: () -> Unit
53
+ ) {
54
+ val uiState by viewModel.uiState.collectAsState()
55
+ val uriHandler = LocalUriHandler.current
56
+
57
+ Column(
58
+ modifier = Modifier
59
+ .fillMaxSize()
60
+ .verticalScroll(rememberScrollState())
61
+ .padding(16.dp),
62
+ horizontalAlignment = Alignment.CenterHorizontally
63
+ ) {
64
+ Spacer(modifier = Modifier.height(64.dp))
65
+
66
+ Image(
67
+ painter = painterResource(id = R.drawable.logo_cropped),
68
+ contentDescription = stringResource(id = R.string.img_http_sms_logo),
69
+ modifier = Modifier.size(100.dp)
70
+ )
71
+
72
+ Spacer(modifier = Modifier.height(32.dp))
73
+
74
+ val annotatedString = buildAnnotatedString {
75
+ val text = stringResource(id = R.string.get_your_api_key)
76
+ val linkText = "httpsms.com/settings"
77
+ val startIndex = text.indexOf(linkText)
78
+
79
+ if (startIndex >= 0) {
80
+ append(text.substring(0, startIndex))
81
+
82
+ pushStringAnnotation(tag = "URL", annotation = "https://httpsms.com/settings")
83
+ withStyle(style = SpanStyle(color = Blue500, fontWeight = FontWeight.Bold)) {
84
+ append(linkText)
85
+ }
86
+ pop()
87
+
88
+ append(text.substring(startIndex + linkText.length))
89
+ } else {
90
+ append(text)
91
+ }
92
+ }
93
+
94
+ ClickableText(
95
+ text = annotatedString,
96
+ onClick = { offset ->
97
+ annotatedString.getStringAnnotations(tag = "URL", start = offset, end = offset)
98
+ .firstOrNull()?.let { annotation ->
99
+ uriHandler.openUri(annotation.item)
100
+ }
101
+ },
102
+ style = MaterialTheme.typography.bodyLarge.copy(
103
+ textAlign = TextAlign.Center,
104
+ fontSize = 20.sp,
105
+ lineHeight = 28.sp,
106
+ color = MaterialTheme.colorScheme.onBackground
107
+ ),
108
+ modifier = Modifier.fillMaxWidth()
109
+ )
110
+
111
+ Spacer(modifier = Modifier.height(24.dp))
112
+
113
+ OutlinedTextField(
114
+ value = uiState.apiKey,
115
+ onValueChange = { viewModel.onApiKeyChange(it) },
116
+ label = { Text(stringResource(id = R.string.text_area_api_key)) },
117
+ modifier = Modifier.fillMaxWidth(),
118
+ isError = uiState.apiKeyError != null,
119
+ supportingText = uiState.apiKeyError?.let { { Text(it) } },
120
+ trailingIcon = {
121
+ IconButton(onClick = onQrScanClick) {
122
+ Icon(
123
+ imageVector = Icons.Default.QrCodeScanner,
124
+ contentDescription = "Scan QR Code"
125
+ )
126
+ }
127
+ },
128
+ keyboardOptions = KeyboardOptions(
129
+ keyboardType = KeyboardType.Text,
130
+ imeAction = ImeAction.Done
131
+ ),
132
+ enabled = !uiState.isLoading
133
+ )
134
+
135
+ Spacer(modifier = Modifier.height(8.dp))
136
+
137
+ OutlinedTextField(
138
+ value = uiState.phoneNumberSIM1,
139
+ onValueChange = { viewModel.onPhoneNumberSIM1Change(it) },
140
+ label = { Text(stringResource(id = R.string.login_phone_number_sim1)) },
141
+ placeholder = { Text(stringResource(id = R.string.login_phone_number_hint)) },
142
+ modifier = Modifier.fillMaxWidth(),
143
+ isError = uiState.phoneNumberSIM1Error != null,
144
+ supportingText = uiState.phoneNumberSIM1Error?.let { { Text(it) } },
145
+ keyboardOptions = KeyboardOptions(
146
+ keyboardType = KeyboardType.Phone,
147
+ imeAction = ImeAction.Done
148
+ ),
149
+ enabled = !uiState.isLoading
150
+ )
151
+
152
+ if (uiState.isDualSim) {
153
+ Spacer(modifier = Modifier.height(8.dp))
154
+ OutlinedTextField(
155
+ value = uiState.phoneNumberSIM2,
156
+ onValueChange = { viewModel.onPhoneNumberSIM2Change(it) },
157
+ label = { Text(stringResource(id = R.string.login_phone_number_sim2)) },
158
+ placeholder = { Text(stringResource(id = R.string.login_phone_number_hint)) },
159
+ modifier = Modifier.fillMaxWidth(),
160
+ isError = uiState.phoneNumberSIM2Error != null,
161
+ supportingText = uiState.phoneNumberSIM2Error?.let { { Text(it) } },
162
+ keyboardOptions = KeyboardOptions(
163
+ keyboardType = KeyboardType.Phone,
164
+ imeAction = ImeAction.Done
165
+ ),
166
+ enabled = !uiState.isLoading
167
+ )
168
+ }
169
+
170
+ Spacer(modifier = Modifier.height(8.dp))
171
+
172
+ OutlinedTextField(
173
+ value = uiState.serverUrl,
174
+ onValueChange = { viewModel.onServerUrlChange(it) },
175
+ label = { Text(stringResource(id = R.string.server_url)) },
176
+ placeholder = { Text(stringResource(id = R.string.login_server_url_hint)) },
177
+ modifier = Modifier.fillMaxWidth(),
178
+ isError = uiState.serverUrlError != null,
179
+ supportingText = uiState.serverUrlError?.let { { Text(it) } },
180
+ keyboardOptions = KeyboardOptions(
181
+ keyboardType = KeyboardType.Uri,
182
+ imeAction = ImeAction.Done
183
+ ),
184
+ enabled = !uiState.isLoading
185
+ )
186
+
187
+ Spacer(modifier = Modifier.height(16.dp))
188
+
189
+ Button(
190
+ onClick = onLoginClick,
191
+ enabled = !uiState.isLoading,
192
+ modifier = Modifier.align(Alignment.CenterHorizontally),
193
+ colors = ButtonDefaults.buttonColors(containerColor = Blue500),
194
+ contentPadding = PaddingValues(horizontal = 32.dp, vertical = 16.dp)
195
+ ) {
196
+ Icon(
197
+ painter = painterResource(id = R.drawable.ic_login),
198
+ contentDescription = null,
199
+ modifier = Modifier.padding(end = 8.dp),
200
+ tint = Color.White
201
+ )
202
+ Text(
203
+ text = stringResource(id = R.string.sign_in_button),
204
+ color = Color.White,
205
+ fontSize = 18.sp
206
+ )
207
+ }
208
+
209
+ if (uiState.isLoading) {
210
+ Spacer(modifier = Modifier.height(16.dp))
211
+ CircularProgressIndicator(
212
+ modifier = Modifier.size(24.dp),
213
+ color = Pink500
214
+ )
215
+ }
216
+ }
217
+ }
android/app/src/main/java/com/httpsms/ui/login/LoginViewModel.kt ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms.ui.login
2
+
3
+ import android.Manifest
4
+ import android.content.Context
5
+ import android.content.pm.PackageManager
6
+ import android.os.Build
7
+ import android.telephony.SubscriptionManager
8
+ import android.telephony.TelephonyManager
9
+ import android.webkit.URLUtil
10
+ import androidx.core.content.ContextCompat
11
+ import androidx.lifecycle.ViewModel
12
+ import androidx.lifecycle.viewModelScope
13
+ import com.httpsms.Constants
14
+ import com.httpsms.HttpSmsApiService
15
+ import com.httpsms.Settings
16
+ import com.httpsms.SmsManagerService
17
+ import com.httpsms.validators.PhoneNumberValidator
18
+ import kotlinx.coroutines.Dispatchers
19
+ import kotlinx.coroutines.flow.MutableStateFlow
20
+ import kotlinx.coroutines.flow.asStateFlow
21
+ import kotlinx.coroutines.launch
22
+ import kotlinx.coroutines.withContext
23
+ import timber.log.Timber
24
+ import java.net.URI
25
+ import java.net.URISyntaxException
26
+
27
+ data class LoginUiState(
28
+ val apiKey: String = "",
29
+ val phoneNumberSIM1: String = "",
30
+ val phoneNumberSIM2: String = "",
31
+ val serverUrl: String = "",
32
+ val isLoading: Boolean = false,
33
+ val apiKeyError: String? = null,
34
+ val phoneNumberSIM1Error: String? = null,
35
+ val phoneNumberSIM2Error: String? = null,
36
+ val serverUrlError: String? = null,
37
+ val isDualSim: Boolean = false,
38
+ val loginSuccess: Boolean = false
39
+ )
40
+
41
+ class LoginViewModel : ViewModel() {
42
+ private val _uiState = MutableStateFlow(LoginUiState())
43
+ val uiState = _uiState.asStateFlow()
44
+
45
+ fun initialize(context: Context, defaultServerUrl: String) {
46
+ val isDualSim = SmsManagerService.isDualSIM(context)
47
+ val phoneNumberSIM1 = Settings.getSIM1PhoneNumber(context)
48
+ val phoneNumberSIM2 = Settings.getSIM2PhoneNumber(context)
49
+
50
+ _uiState.value = _uiState.value.copy(
51
+ isDualSim = isDualSim,
52
+ phoneNumberSIM1 = phoneNumberSIM1,
53
+ phoneNumberSIM2 = phoneNumberSIM2,
54
+ serverUrl = defaultServerUrl
55
+ )
56
+
57
+ // Try to auto-detect if fields are empty
58
+ if (phoneNumberSIM1.isEmpty() || (isDualSim && phoneNumberSIM2.isEmpty())) {
59
+ autoDetectPhoneNumbers(context)
60
+ }
61
+ }
62
+
63
+ fun autoDetectPhoneNumbers(context: Context) {
64
+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
65
+ Timber.d("READ_PHONE_STATE permission not granted for auto-detecting phone numbers")
66
+ return
67
+ }
68
+
69
+ val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
70
+
71
+ var detectedSIM1 = _uiState.value.phoneNumberSIM1
72
+ var detectedSIM2 = _uiState.value.phoneNumberSIM2
73
+
74
+ try {
75
+ val subscriptionManager = if (Build.VERSION.SDK_INT >= 31) {
76
+ context.getSystemService(SubscriptionManager::class.java)
77
+ } else {
78
+ SubscriptionManager.from(context)
79
+ }
80
+
81
+ val activeSubscriptions = try { subscriptionManager.activeSubscriptionInfoList } catch (e: Exception) { null }
82
+
83
+ if (detectedSIM1.isEmpty()) {
84
+ val line1Number = try { telephonyManager.line1Number } catch (e: Exception) { null }
85
+ if (!line1Number.isNullOrEmpty()) {
86
+ detectedSIM1 = line1Number
87
+ } else if (activeSubscriptions != null && activeSubscriptions.isNotEmpty()) {
88
+ detectedSIM1 = activeSubscriptions[0].number ?: ""
89
+ }
90
+ }
91
+
92
+ if (detectedSIM2.isEmpty() && activeSubscriptions != null && activeSubscriptions.size >= 2) {
93
+ detectedSIM2 = activeSubscriptions[1].number ?: ""
94
+ }
95
+
96
+ Timber.d("Auto-detected numbers - SIM1: $detectedSIM1, SIM2: $detectedSIM2")
97
+
98
+ } catch (e: SecurityException) {
99
+ Timber.e(e, "Security exception while auto-detecting phone numbers")
100
+ }
101
+
102
+ _uiState.value = _uiState.value.copy(
103
+ phoneNumberSIM1 = detectedSIM1,
104
+ phoneNumberSIM2 = detectedSIM2,
105
+ isDualSim = SmsManagerService.isDualSIM(context)
106
+ )
107
+ }
108
+
109
+ fun onApiKeyChange(value: String) {
110
+ _uiState.value = _uiState.value.copy(apiKey = value, apiKeyError = null)
111
+ }
112
+
113
+ fun onPhoneNumberSIM1Change(value: String) {
114
+ _uiState.value = _uiState.value.copy(phoneNumberSIM1 = value, phoneNumberSIM1Error = null)
115
+ }
116
+
117
+ fun onPhoneNumberSIM2Change(value: String) {
118
+ _uiState.value = _uiState.value.copy(phoneNumberSIM2 = value, phoneNumberSIM2Error = null)
119
+ }
120
+
121
+ fun onServerUrlChange(value: String) {
122
+ _uiState.value = _uiState.value.copy(serverUrl = value, serverUrlError = null)
123
+ }
124
+
125
+ fun login(context: Context, countryCode: String, onGooglePlayServicesError: (String) -> Unit, onFcmTokenMissing: () -> Unit) {
126
+ val currentState = _uiState.value
127
+
128
+ // Validation logic from LoginActivity.onLoginClick
129
+ if (Settings.getFcmToken(context) == null) {
130
+ onFcmTokenMissing()
131
+ return
132
+ }
133
+
134
+ _uiState.value = currentState.copy(isLoading = true)
135
+
136
+ viewModelScope.launch {
137
+ val apiKey = currentState.apiKey.trim()
138
+ val serverUrl = currentState.serverUrl.trim()
139
+ val phone1 = currentState.phoneNumberSIM1.trim()
140
+ val phone2 = currentState.phoneNumberSIM2.trim()
141
+
142
+ if (!PhoneNumberValidator.isValidPhoneNumber(phone1, countryCode)) {
143
+ _uiState.value = _uiState.value.copy(
144
+ isLoading = false,
145
+ phoneNumberSIM1Error = "Enter an international phone number in the E.164 format"
146
+ )
147
+ return@launch
148
+ }
149
+
150
+ if (currentState.isDualSim && !PhoneNumberValidator.isValidPhoneNumber(phone2, countryCode)) {
151
+ _uiState.value = _uiState.value.copy(
152
+ isLoading = false,
153
+ phoneNumberSIM2Error = "Enter an international phone number in the E.164 format"
154
+ )
155
+ return@launch
156
+ }
157
+
158
+ if (!URLUtil.isValidUrl(serverUrl)) {
159
+ _uiState.value = _uiState.value.copy(
160
+ isLoading = false,
161
+ serverUrlError = "Server URL [$serverUrl] is invalid"
162
+ )
163
+ return@launch
164
+ }
165
+
166
+ if (!URLUtil.isHttpsUrl(serverUrl)) {
167
+ _uiState.value = _uiState.value.copy(
168
+ isLoading = false,
169
+ serverUrlError = "Server URL [$serverUrl] must be HTTPS"
170
+ )
171
+ return@launch
172
+ }
173
+
174
+ val authResult = try {
175
+ withContext(Dispatchers.IO) {
176
+ val service = HttpSmsApiService(apiKey, URI(serverUrl))
177
+ val e164Phone1 = PhoneNumberValidator.formatE164(phone1, countryCode)
178
+ val response1 = service.updateFcmToken(e164Phone1, Constants.SIM1, Settings.getFcmToken(context) ?: "")
179
+
180
+ if (response1.second != null || response1.third != null) {
181
+ return@withContext Pair(response1.second, response1.third)
182
+ }
183
+
184
+ if (currentState.isDualSim) {
185
+ val e164Phone2 = PhoneNumberValidator.formatE164(phone2, countryCode)
186
+ val response2 = service.updateFcmToken(e164Phone2, Constants.SIM2, Settings.getFcmToken(context) ?: "")
187
+ return@withContext Pair(response2.second, response2.third)
188
+ }
189
+
190
+ Pair(null, null)
191
+ }
192
+ } catch (e: URISyntaxException) {
193
+ Timber.e(e, "Invalid URI: $serverUrl")
194
+ Pair(null, "Server URL [$serverUrl] is invalid")
195
+ } catch (e: Exception) {
196
+ Timber.e(e, "Login error")
197
+ Pair(null, "An unexpected error occurred: ${e.message}")
198
+ }
199
+
200
+ if (authResult.first != null) {
201
+ _uiState.value = _uiState.value.copy(isLoading = false, apiKeyError = authResult.first)
202
+ return@launch
203
+ }
204
+
205
+ if (authResult.second != null) {
206
+ _uiState.value = _uiState.value.copy(isLoading = false, serverUrlError = authResult.second)
207
+ return@launch
208
+ }
209
+
210
+ // Save settings
211
+ Settings.setApiKeyAsync(context, apiKey)
212
+ Settings.setServerUrlAsync(context, serverUrl)
213
+ Settings.setSIM1PhoneNumber(context, PhoneNumberValidator.formatE164(phone1, countryCode))
214
+ if (currentState.isDualSim) {
215
+ Settings.setSIM2PhoneNumber(context, PhoneNumberValidator.formatE164(phone2, countryCode))
216
+ }
217
+
218
+ _uiState.value = _uiState.value.copy(isLoading = false, loginSuccess = true)
219
+ }
220
+ }
221
+ }
android/app/src/main/java/com/httpsms/ui/main/MainActivityContent.kt ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms.ui.main
2
+
3
+ import android.telephony.PhoneNumberUtils
4
+ import androidx.compose.foundation.Image
5
+ import androidx.compose.foundation.layout.Column
6
+ import androidx.compose.foundation.layout.IntrinsicSize
7
+ import androidx.compose.foundation.layout.PaddingValues
8
+ import androidx.compose.foundation.layout.Row
9
+ import androidx.compose.foundation.layout.Spacer
10
+ import androidx.compose.foundation.layout.fillMaxSize
11
+ import androidx.compose.foundation.layout.fillMaxWidth
12
+ import androidx.compose.foundation.layout.height
13
+ import androidx.compose.foundation.layout.padding
14
+ import androidx.compose.foundation.layout.size
15
+ import androidx.compose.foundation.layout.width
16
+ import androidx.compose.foundation.rememberScrollState
17
+ import androidx.compose.foundation.verticalScroll
18
+ import androidx.compose.material.icons.Icons
19
+ import androidx.compose.material.icons.filled.BatteryAlert
20
+ import androidx.compose.material.icons.filled.CheckCircle
21
+ import androidx.compose.material.icons.filled.Favorite
22
+ import androidx.compose.material.icons.filled.Settings
23
+ import androidx.compose.material3.Button
24
+ import androidx.compose.material3.ButtonDefaults
25
+ import androidx.compose.material3.Card
26
+ import androidx.compose.material3.CardDefaults
27
+ import androidx.compose.material3.Icon
28
+ import androidx.compose.material3.LinearProgressIndicator
29
+ import androidx.compose.material3.LocalContentColor
30
+ import androidx.compose.material3.MaterialTheme
31
+ import androidx.compose.material3.Text
32
+ import androidx.compose.runtime.Composable
33
+ import androidx.compose.runtime.collectAsState
34
+ import androidx.compose.runtime.getValue
35
+ import androidx.compose.ui.Alignment
36
+ import androidx.compose.ui.Modifier
37
+ import androidx.compose.ui.graphics.Color
38
+ import androidx.compose.ui.platform.LocalContext
39
+ import androidx.compose.ui.res.painterResource
40
+ import androidx.compose.ui.res.stringResource
41
+ import androidx.compose.ui.text.font.FontWeight
42
+ import androidx.compose.ui.unit.dp
43
+ import androidx.compose.ui.unit.sp
44
+ import com.httpsms.R
45
+ import com.httpsms.ui.theme.Blue500
46
+ import com.httpsms.ui.theme.Pink500
47
+ import java.util.Locale
48
+
49
+ @Composable
50
+ fun MainScreen(
51
+ viewModel: MainViewModel,
52
+ onSettingsClick: () -> Unit,
53
+ onSmsPermissionClick: () -> Unit,
54
+ onBatteryOptimizationClick: () -> Unit,
55
+ onHeartbeatClick: () -> Unit
56
+ ) {
57
+ val uiState by viewModel.uiState.collectAsState()
58
+
59
+ Column(
60
+ modifier = Modifier
61
+ .fillMaxSize()
62
+ .verticalScroll(rememberScrollState())
63
+ .padding(16.dp),
64
+ horizontalAlignment = Alignment.CenterHorizontally
65
+ ) {
66
+ Spacer(modifier = Modifier.height(64.dp))
67
+
68
+ Image(
69
+ painter = painterResource(id = R.drawable.logo_cropped),
70
+ contentDescription = stringResource(id = R.string.img_http_sms_logo),
71
+ modifier = Modifier
72
+ .width(147.dp)
73
+ .height(92.dp)
74
+ )
75
+
76
+ Spacer(modifier = Modifier.height(24.dp))
77
+
78
+ PhoneCard(
79
+ phoneNumber = uiState.phoneNumberSIM1,
80
+ isActive = uiState.isActiveSIM1,
81
+ refreshTime = uiState.lastHeartbeatTime
82
+ )
83
+
84
+ if (uiState.isDualSim) {
85
+ Spacer(modifier = Modifier.height(24.dp))
86
+ PhoneCard(
87
+ phoneNumber = uiState.phoneNumberSIM2,
88
+ isActive = uiState.isActiveSIM2,
89
+ refreshTime = uiState.lastHeartbeatTime
90
+ )
91
+ }
92
+
93
+ Spacer(modifier = Modifier.height(16.dp))
94
+
95
+ if (!uiState.isSmsPermissionGranted || !uiState.isBatteryOptimizationDisabled) {
96
+ Column(modifier = Modifier.fillMaxWidth()) {
97
+ if (!uiState.isSmsPermissionGranted) {
98
+ Button(
99
+ onClick = onSmsPermissionClick,
100
+ modifier = Modifier.align(Alignment.CenterHorizontally),
101
+ colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF4CAF50)),
102
+ contentPadding = PaddingValues(horizontal = 32.dp, vertical = 16.dp)
103
+ ) {
104
+ Text(
105
+ stringResource(id = R.string.enable_sms_permission),
106
+ color = Color.White,
107
+ fontSize = 18.sp
108
+ )
109
+ Spacer(modifier = Modifier.width(8.dp))
110
+ Icon(
111
+ painter = painterResource(id = R.drawable.open_in_new_24),
112
+ contentDescription = null,
113
+ tint = Color.White
114
+ )
115
+ }
116
+ Spacer(modifier = Modifier.height(8.dp))
117
+ }
118
+
119
+ if (!uiState.isBatteryOptimizationDisabled) {
120
+ Button(
121
+ onClick = onBatteryOptimizationClick,
122
+ modifier = Modifier.align(Alignment.CenterHorizontally),
123
+ colors = ButtonDefaults.buttonColors(containerColor = Pink500),
124
+ contentPadding = PaddingValues(horizontal = 32.dp, vertical = 16.dp)
125
+ ) {
126
+ Icon(
127
+ imageVector = Icons.Default.BatteryAlert,
128
+ contentDescription = null,
129
+ tint = Color.White
130
+ )
131
+ Spacer(modifier = Modifier.width(8.dp))
132
+ Text(
133
+ stringResource(id = R.string.disable_battery_optimization),
134
+ color = Color.White,
135
+ fontSize = 18.sp
136
+ )
137
+ }
138
+ }
139
+ }
140
+ }
141
+
142
+ Spacer(modifier = Modifier.height(16.dp))
143
+
144
+ Column(
145
+ modifier = Modifier.width(IntrinsicSize.Max),
146
+ horizontalAlignment = Alignment.CenterHorizontally
147
+ ) {
148
+ Button(
149
+ onClick = onHeartbeatClick,
150
+ modifier = Modifier.fillMaxWidth(),
151
+ enabled = !uiState.isHeartbeatLoading,
152
+ colors = ButtonDefaults.buttonColors(containerColor = Blue500),
153
+ contentPadding = PaddingValues(horizontal = 32.dp, vertical = 16.dp)
154
+ ) {
155
+ Icon(
156
+ imageVector = Icons.Default.Favorite,
157
+ contentDescription = null,
158
+ tint = if (uiState.isHeartbeatLoading) LocalContentColor.current else Pink500
159
+ )
160
+ Spacer(modifier = Modifier.width(8.dp))
161
+ Text(
162
+ stringResource(id = R.string.send_heartbeat),
163
+ color = Color.White,
164
+ fontSize = 18.sp
165
+ )
166
+ }
167
+
168
+ if (uiState.isHeartbeatLoading) {
169
+ LinearProgressIndicator(
170
+ modifier = Modifier
171
+ .fillMaxWidth()
172
+ .padding(top = 4.dp),
173
+ color = Pink500
174
+ )
175
+ }
176
+ }
177
+
178
+ Spacer(modifier = Modifier.height(16.dp))
179
+
180
+ Text(
181
+ text = uiState.appVersion,
182
+ fontSize = 14.sp,
183
+ color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.6f)
184
+ )
185
+
186
+ Spacer(modifier = Modifier.weight(1f))
187
+ Spacer(modifier = Modifier.height(16.dp))
188
+
189
+ Button(
190
+ onClick = onSettingsClick,
191
+ colors = ButtonDefaults.buttonColors(containerColor = Color.Black),
192
+ contentPadding = PaddingValues(horizontal = 32.dp, vertical = 16.dp)
193
+ ) {
194
+ Icon(Icons.Default.Settings, contentDescription = null, tint = Color.White)
195
+ Spacer(modifier = Modifier.width(8.dp))
196
+ Text(
197
+ stringResource(id = R.string.main_app_settings),
198
+ color = Color.White,
199
+ fontSize = 18.sp
200
+ )
201
+ }
202
+
203
+ Spacer(modifier = Modifier.height(16.dp))
204
+ }
205
+ }
206
+
207
+ @Composable
208
+ fun PhoneCard(
209
+ phoneNumber: String,
210
+ isActive: Boolean,
211
+ refreshTime: String
212
+ ) {
213
+ Card(
214
+ modifier = Modifier.fillMaxWidth(),
215
+ elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
216
+ ) {
217
+ Column(modifier = Modifier.padding(16.dp)) {
218
+ Row(verticalAlignment = Alignment.CenterVertically) {
219
+ Text(
220
+ text = PhoneNumberUtils.formatNumber(phoneNumber, Locale.getDefault().country) ?: phoneNumber,
221
+ fontSize = 28.sp,
222
+ fontWeight = FontWeight.Medium,
223
+ modifier = Modifier.weight(1f),
224
+ color = MaterialTheme.colorScheme.onSurface
225
+ )
226
+ if (isActive) {
227
+ Icon(
228
+ imageVector = Icons.Default.CheckCircle,
229
+ contentDescription = "Active",
230
+ tint = Color(0xFF70AB5C),
231
+ modifier = Modifier.size(24.dp)
232
+ )
233
+ }
234
+ }
235
+ Spacer(modifier = Modifier.height(8.dp))
236
+ Text(
237
+ text = refreshTime,
238
+ fontSize = 16.sp,
239
+ color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
240
+ )
241
+ }
242
+ }
243
+ }
android/app/src/main/java/com/httpsms/ui/main/MainViewModel.kt ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms.ui.main
2
+
3
+ import android.Manifest
4
+ import android.content.Context
5
+ import android.content.pm.PackageManager
6
+ import android.os.PowerManager
7
+ import androidx.lifecycle.ViewModel
8
+ import androidx.lifecycle.viewModelScope
9
+ import com.httpsms.Constants
10
+ import com.httpsms.HttpSmsApiService
11
+ import com.httpsms.Settings
12
+ import kotlinx.coroutines.Dispatchers
13
+ import kotlinx.coroutines.flow.MutableStateFlow
14
+ import kotlinx.coroutines.flow.asStateFlow
15
+ import kotlinx.coroutines.launch
16
+ import kotlinx.coroutines.withContext
17
+ import timber.log.Timber
18
+ import java.time.Instant
19
+ import java.time.ZoneId
20
+ import java.time.ZoneOffset
21
+ import java.time.ZonedDateTime
22
+ import java.time.format.DateTimeFormatter
23
+
24
+ data class MainUiState(
25
+ val phoneNumberSIM1: String = "",
26
+ val isActiveSIM1: Boolean = false,
27
+ val phoneNumberSIM2: String = "",
28
+ val isActiveSIM2: Boolean = false,
29
+ val isDualSim: Boolean = false,
30
+ val lastHeartbeatTime: String = "--",
31
+ val isSmsPermissionGranted: Boolean = true,
32
+ val isBatteryOptimizationDisabled: Boolean = true,
33
+ val isHeartbeatLoading: Boolean = false,
34
+ val appVersion: String = ""
35
+ )
36
+
37
+ class MainViewModel : ViewModel() {
38
+ private val _uiState = MutableStateFlow(MainUiState())
39
+ val uiState = _uiState.asStateFlow()
40
+
41
+ fun initialize(context: Context, appVersion: String) {
42
+ updateState(context, appVersion)
43
+ }
44
+
45
+ fun updateState(context: Context, appVersion: String) {
46
+ val isDualSim = Settings.isDualSIM(context)
47
+ val phone1 = Settings.getSIM1PhoneNumber(context) ?: ""
48
+ val active1 = Settings.getActiveStatus(context, Constants.SIM1)
49
+ val phone2 = Settings.getSIM2PhoneNumber(context) ?: ""
50
+ val active2 = Settings.getActiveStatus(context, Constants.SIM2)
51
+
52
+ val timestamp = Settings.getHeartbeatTimestamp(context)
53
+ val lastHeartbeat = if (timestamp == 0L) {
54
+ "--"
55
+ } else {
56
+ val timestampZdt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneOffset.UTC)
57
+ val localTime = timestampZdt.withZoneSameInstant(ZoneId.systemDefault())
58
+ localTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
59
+ }
60
+
61
+ val smsPermissions = arrayOf(
62
+ Manifest.permission.SEND_SMS,
63
+ Manifest.permission.RECEIVE_SMS,
64
+ Manifest.permission.READ_SMS
65
+ )
66
+ val allGranted = smsPermissions.all {
67
+ context.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED
68
+ }
69
+
70
+ val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
71
+ val batteryOptimized = pm.isIgnoringBatteryOptimizations(context.packageName)
72
+
73
+ _uiState.value = _uiState.value.copy(
74
+ phoneNumberSIM1 = phone1,
75
+ isActiveSIM1 = active1,
76
+ phoneNumberSIM2 = phone2,
77
+ isActiveSIM2 = active2,
78
+ isDualSim = isDualSim,
79
+ lastHeartbeatTime = lastHeartbeat,
80
+ isSmsPermissionGranted = allGranted,
81
+ isBatteryOptimizationDisabled = batteryOptimized,
82
+ appVersion = appVersion
83
+ )
84
+ }
85
+
86
+ fun sendHeartbeat(context: Context, onComplete: (String?) -> Unit) {
87
+ _uiState.value = _uiState.value.copy(isHeartbeatLoading = true)
88
+
89
+ viewModelScope.launch {
90
+ val result = withContext(Dispatchers.IO) {
91
+ val charging = Settings.isCharging(context)
92
+ try {
93
+ val phoneNumbers = mutableListOf<String>()
94
+ phoneNumbers.add(Settings.getSIM1PhoneNumber(context))
95
+ if (Settings.getActiveStatus(context, Constants.SIM2)) {
96
+ phoneNumbers.add(Settings.getSIM2PhoneNumber(context))
97
+ }
98
+ val isStored = HttpSmsApiService.create(context).storeHeartbeat(phoneNumbers.toTypedArray(), charging)
99
+ if (!isStored) {
100
+ "Could not send heartbeat make sure the phone is connected to the internet"
101
+ } else {
102
+ Settings.setHeartbeatTimestampAsync(context, System.currentTimeMillis())
103
+ null
104
+ }
105
+ } catch (exception: Exception) {
106
+ Timber.e(exception)
107
+ exception.javaClass.simpleName
108
+ }
109
+ }
110
+
111
+ _uiState.value = _uiState.value.copy(isHeartbeatLoading = false)
112
+ updateState(context, _uiState.value.appVersion)
113
+ onComplete(result)
114
+ }
115
+ }
116
+ }
android/app/src/main/java/com/httpsms/ui/settings/SettingsActivityContent.kt ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms.ui.settings
2
+
3
+ import android.app.Activity
4
+ import androidx.compose.foundation.isSystemInDarkTheme
5
+ import androidx.compose.foundation.layout.Column
6
+ import androidx.compose.foundation.layout.PaddingValues
7
+ import androidx.compose.foundation.layout.Row
8
+ import androidx.compose.foundation.layout.Spacer
9
+ import androidx.compose.foundation.layout.fillMaxSize
10
+ import androidx.compose.foundation.layout.fillMaxWidth
11
+ import androidx.compose.foundation.layout.height
12
+ import androidx.compose.foundation.layout.padding
13
+ import androidx.compose.foundation.layout.width
14
+ import androidx.compose.foundation.rememberScrollState
15
+ import androidx.compose.foundation.verticalScroll
16
+ import androidx.compose.material.icons.Icons
17
+ import androidx.compose.material.icons.automirrored.filled.ArrowBack
18
+ import androidx.compose.material.icons.automirrored.filled.Logout
19
+ import androidx.compose.material3.Button
20
+ import androidx.compose.material3.ButtonDefaults
21
+ import androidx.compose.material3.ExperimentalMaterial3Api
22
+ import androidx.compose.material3.Icon
23
+ import androidx.compose.material3.IconButton
24
+ import androidx.compose.material3.MaterialTheme
25
+ import androidx.compose.material3.OutlinedTextField
26
+ import androidx.compose.material3.Scaffold
27
+ import androidx.compose.material3.Switch
28
+ import androidx.compose.material3.Text
29
+ import androidx.compose.material3.TopAppBar
30
+ import androidx.compose.material3.TopAppBarDefaults
31
+ import androidx.compose.runtime.Composable
32
+ import androidx.compose.runtime.SideEffect
33
+ import androidx.compose.runtime.collectAsState
34
+ import androidx.compose.runtime.getValue
35
+ import androidx.compose.ui.Alignment
36
+ import androidx.compose.ui.Modifier
37
+ import androidx.compose.ui.graphics.Color
38
+ import androidx.compose.ui.graphics.toArgb
39
+ import androidx.compose.ui.platform.LocalContext
40
+ import androidx.compose.ui.platform.LocalView
41
+ import androidx.compose.ui.res.stringResource
42
+ import androidx.compose.ui.unit.dp
43
+ import androidx.compose.ui.unit.sp
44
+ import androidx.core.view.WindowCompat
45
+ import com.httpsms.R
46
+ import com.httpsms.ui.theme.LogoGreen
47
+
48
+ @OptIn(ExperimentalMaterial3Api::class)
49
+ @Composable
50
+ fun SettingsScreen(
51
+ viewModel: SettingsViewModel,
52
+ onBackClick: () -> Unit,
53
+ onLogoutClick: () -> Unit
54
+ ) {
55
+ val uiState by viewModel.uiState.collectAsState()
56
+ val context = LocalContext.current
57
+ val isDarkTheme = isSystemInDarkTheme()
58
+ val primaryColor = if (isDarkTheme) Color.Black else LogoGreen
59
+
60
+ val view = LocalView.current
61
+ if (!view.isInEditMode) {
62
+ SideEffect {
63
+ val window = (view.context as Activity).window
64
+ window.statusBarColor = primaryColor.toArgb()
65
+ WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = false
66
+ }
67
+ }
68
+
69
+ Scaffold(
70
+ topBar = {
71
+ TopAppBar(
72
+ title = { Text("App Settings") },
73
+ navigationIcon = {
74
+ IconButton(onClick = onBackClick) {
75
+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
76
+ }
77
+ },
78
+ colors = TopAppBarDefaults.topAppBarColors(
79
+ containerColor = primaryColor,
80
+ titleContentColor = Color.White,
81
+ navigationIconContentColor = Color.White
82
+ )
83
+ )
84
+ }
85
+ ) { paddingValues ->
86
+ Column(
87
+ modifier = Modifier
88
+ .fillMaxSize()
89
+ .padding(paddingValues)
90
+ .verticalScroll(rememberScrollState())
91
+ .padding(16.dp)
92
+ ) {
93
+ // SIM 1 Settings
94
+ OutlinedTextField(
95
+ value = uiState.phoneNumberSIM1,
96
+ onValueChange = { },
97
+ label = { Text(stringResource(id = R.string.settings_sim1)) },
98
+ modifier = Modifier.fillMaxWidth(),
99
+ enabled = false
100
+ )
101
+
102
+ SwitchSetting(
103
+ text = stringResource(id = R.string.settings_outgoing_messages_sim1),
104
+ checked = uiState.isActiveSIM1,
105
+ onCheckedChange = { viewModel.setActiveSIM1(context, it) }
106
+ )
107
+
108
+ SwitchSetting(
109
+ text = stringResource(id = R.string.settings_incoming_messages_sim1),
110
+ checked = uiState.isIncomingSIM1Enabled,
111
+ onCheckedChange = { viewModel.setIncomingSIM1Enabled(context, it) }
112
+ )
113
+
114
+ SwitchSetting(
115
+ text = stringResource(id = R.string.enable_incoming_call_events_sim1),
116
+ checked = uiState.isIncomingCallEventsSIM1Enabled,
117
+ onCheckedChange = { viewModel.setIncomingCallEventsSIM1Enabled(context, it) }
118
+ )
119
+
120
+ if (uiState.isDualSim) {
121
+ Spacer(modifier = Modifier.height(16.dp))
122
+ // SIM 2 Settings
123
+ OutlinedTextField(
124
+ value = uiState.phoneNumberSIM2,
125
+ onValueChange = { },
126
+ label = { Text(stringResource(id = R.string.settings_sim_2)) },
127
+ modifier = Modifier.fillMaxWidth(),
128
+ enabled = false
129
+ )
130
+
131
+ SwitchSetting(
132
+ text = stringResource(id = R.string.settings_outgoing_messages_sim2),
133
+ checked = uiState.isActiveSIM2,
134
+ onCheckedChange = { viewModel.setActiveSIM2(context, it) }
135
+ )
136
+
137
+ SwitchSetting(
138
+ text = stringResource(id = R.string.settings_incoming_messages_sim2),
139
+ checked = uiState.isIncomingSIM2Enabled,
140
+ onCheckedChange = { viewModel.setIncomingSIM2Enabled(context, it) }
141
+ )
142
+
143
+ SwitchSetting(
144
+ text = stringResource(id = R.string.enable_sim2_incoming_call_events),
145
+ checked = uiState.isIncomingCallEventsSIM2Enabled,
146
+ onCheckedChange = { viewModel.setIncomingCallEventsSIM2Enabled(context, it) }
147
+ )
148
+ }
149
+
150
+ Spacer(modifier = Modifier.height(16.dp))
151
+
152
+ OutlinedTextField(
153
+ value = uiState.encryptionKey,
154
+ onValueChange = { viewModel.setEncryptionKey(context, it) },
155
+ label = { Text(stringResource(id = R.string.encryption_key)) },
156
+ modifier = Modifier.fillMaxWidth()
157
+ )
158
+
159
+ SwitchSetting(
160
+ text = stringResource(id = R.string.encrypt_received_messages),
161
+ checked = uiState.isEncryptReceivedMessagesEnabled,
162
+ onCheckedChange = { viewModel.setEncryptReceivedMessagesEnabled(context, it) },
163
+ enabled = uiState.encryptionKey.isNotEmpty()
164
+ )
165
+
166
+ SwitchSetting(
167
+ text = stringResource(id = R.string.enable_debug_logs),
168
+ checked = uiState.isDebugLogEnabled,
169
+ onCheckedChange = { viewModel.setDebugLogEnabled(context, it) }
170
+ )
171
+
172
+ Spacer(modifier = Modifier.height(24.dp))
173
+
174
+ Button(
175
+ onClick = onLogoutClick,
176
+ modifier = Modifier.align(Alignment.CenterHorizontally),
177
+ colors = ButtonDefaults.buttonColors(containerColor = Color.Black),
178
+ contentPadding = PaddingValues(horizontal = 32.dp, vertical = 16.dp)
179
+ ) {
180
+ Icon(
181
+ imageVector = Icons.AutoMirrored.Filled.Logout,
182
+ contentDescription = null,
183
+ tint = Color.White
184
+ )
185
+ Spacer(modifier = Modifier.width(8.dp))
186
+ Text(
187
+ stringResource(id = R.string.main_log_out),
188
+ color = Color.White,
189
+ fontSize = 18.sp
190
+ )
191
+ }
192
+ }
193
+ }
194
+ }
195
+
196
+ @Composable
197
+ fun SwitchSetting(
198
+ text: String,
199
+ checked: Boolean,
200
+ onCheckedChange: (Boolean) -> Unit,
201
+ enabled: Boolean = true
202
+ ) {
203
+ Row(
204
+ modifier = Modifier
205
+ .fillMaxWidth()
206
+ .padding(vertical = 8.dp),
207
+ verticalAlignment = Alignment.CenterVertically
208
+ ) {
209
+ Text(
210
+ text = text,
211
+ modifier = Modifier.weight(1f),
212
+ fontSize = 18.sp,
213
+ color = if (enabled) MaterialTheme.colorScheme.onBackground else MaterialTheme.colorScheme.onBackground.copy(alpha = 0.5f)
214
+ )
215
+ Switch(
216
+ checked = checked,
217
+ onCheckedChange = onCheckedChange,
218
+ enabled = enabled
219
+ )
220
+ }
221
+ }
android/app/src/main/java/com/httpsms/ui/settings/SettingsViewModel.kt ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms.ui.settings
2
+
3
+ import android.content.Context
4
+ import androidx.lifecycle.ViewModel
5
+ import com.httpsms.Constants
6
+ import com.httpsms.Settings
7
+ import kotlinx.coroutines.flow.MutableStateFlow
8
+ import kotlinx.coroutines.flow.asStateFlow
9
+
10
+ data class SettingsUiState(
11
+ val isDebugLogEnabled: Boolean = false,
12
+ val phoneNumberSIM1: String = "",
13
+ val isIncomingSIM1Enabled: Boolean = false,
14
+ val isActiveSIM1: Boolean = false,
15
+ val isIncomingCallEventsSIM1Enabled: Boolean = false,
16
+ val isDualSim: Boolean = false,
17
+ val phoneNumberSIM2: String = "",
18
+ val isIncomingSIM2Enabled: Boolean = false,
19
+ val isActiveSIM2: Boolean = false,
20
+ val isIncomingCallEventsSIM2Enabled: Boolean = false,
21
+ val encryptionKey: String = "",
22
+ val isEncryptReceivedMessagesEnabled: Boolean = false
23
+ )
24
+
25
+ class SettingsViewModel : ViewModel() {
26
+ private val _uiState = MutableStateFlow(SettingsUiState())
27
+ val uiState = _uiState.asStateFlow()
28
+
29
+ fun initialize(context: Context) {
30
+ _uiState.value = SettingsUiState(
31
+ isDebugLogEnabled = Settings.isDebugLogEnabled(context),
32
+ phoneNumberSIM1 = Settings.getSIM1PhoneNumber(context) ?: "",
33
+ isIncomingSIM1Enabled = Settings.isIncomingMessageEnabled(context, Constants.SIM1),
34
+ isActiveSIM1 = Settings.getActiveStatus(context, Constants.SIM1),
35
+ isIncomingCallEventsSIM1Enabled = Settings.isIncomingCallEventsEnabled(context, Constants.SIM1),
36
+ isDualSim = Settings.isDualSIM(context),
37
+ phoneNumberSIM2 = Settings.getSIM2PhoneNumber(context) ?: "",
38
+ isIncomingSIM2Enabled = Settings.isIncomingMessageEnabled(context, Constants.SIM2),
39
+ isActiveSIM2 = Settings.getActiveStatus(context, Constants.SIM2),
40
+ isIncomingCallEventsSIM2Enabled = Settings.isIncomingCallEventsEnabled(context, Constants.SIM2),
41
+ encryptionKey = Settings.getEncryptionKey(context) ?: "",
42
+ isEncryptReceivedMessagesEnabled = Settings.encryptReceivedMessages(context)
43
+ )
44
+ }
45
+
46
+ fun setDebugLogEnabled(context: Context, enabled: Boolean) {
47
+ Settings.setDebugLogEnabled(context, enabled)
48
+ _uiState.value = _uiState.value.copy(isDebugLogEnabled = enabled)
49
+ }
50
+
51
+ fun setIncomingSIM1Enabled(context: Context, enabled: Boolean) {
52
+ Settings.setIncomingActiveSIM1(context, enabled)
53
+ _uiState.value = _uiState.value.copy(isIncomingSIM1Enabled = enabled)
54
+ }
55
+
56
+ fun setActiveSIM1(context: Context, enabled: Boolean) {
57
+ Settings.setActiveStatusAsync(context, enabled, Constants.SIM1)
58
+ _uiState.value = _uiState.value.copy(isActiveSIM1 = enabled)
59
+ }
60
+
61
+ fun setIncomingCallEventsSIM1Enabled(context: Context, enabled: Boolean) {
62
+ Settings.setIncomingCallEventsEnabled(context, Constants.SIM1, enabled)
63
+ _uiState.value = _uiState.value.copy(isIncomingCallEventsSIM1Enabled = enabled)
64
+ }
65
+
66
+ fun setIncomingSIM2Enabled(context: Context, enabled: Boolean) {
67
+ Settings.setIncomingActiveSIM2(context, enabled)
68
+ _uiState.value = _uiState.value.copy(isIncomingSIM2Enabled = enabled)
69
+ }
70
+
71
+ fun setActiveSIM2(context: Context, enabled: Boolean) {
72
+ Settings.setActiveStatusAsync(context, enabled, Constants.SIM2)
73
+ _uiState.value = _uiState.value.copy(isActiveSIM2 = enabled)
74
+ }
75
+
76
+ fun setIncomingCallEventsSIM2Enabled(context: Context, enabled: Boolean) {
77
+ Settings.setIncomingCallEventsEnabled(context, Constants.SIM2, enabled)
78
+ _uiState.value = _uiState.value.copy(isIncomingCallEventsSIM2Enabled = enabled)
79
+ }
80
+
81
+ fun setEncryptionKey(context: Context, key: String) {
82
+ val trimmedKey = key.trim()
83
+ if (trimmedKey.isEmpty()) {
84
+ Settings.setEncryptionKey(context, null)
85
+ Settings.setEncryptReceivedMessages(context, false)
86
+ _uiState.value = _uiState.value.copy(encryptionKey = "", isEncryptReceivedMessagesEnabled = false)
87
+ } else {
88
+ Settings.setEncryptionKey(context, trimmedKey)
89
+ _uiState.value = _uiState.value.copy(encryptionKey = trimmedKey)
90
+ }
91
+ }
92
+
93
+ fun setEncryptReceivedMessagesEnabled(context: Context, enabled: Boolean) {
94
+ Settings.setEncryptReceivedMessages(context, enabled)
95
+ _uiState.value = _uiState.value.copy(isEncryptReceivedMessagesEnabled = enabled)
96
+ }
97
+
98
+ fun logout(context: Context, onLogoutComplete: () -> Unit) {
99
+ Settings.setApiKeyAsync(context, null)
100
+ Settings.setSIM1PhoneNumber(context, null)
101
+ Settings.setSIM2PhoneNumber(context, null)
102
+ Settings.setActiveStatusAsync(context, true, Constants.SIM1)
103
+ Settings.setActiveStatusAsync(context, true, Constants.SIM2)
104
+ Settings.setIncomingActiveSIM1(context, true)
105
+ Settings.setIncomingActiveSIM2(context, true)
106
+ Settings.setUserID(context, null)
107
+ Settings.setEncryptionKey(context, null)
108
+ Settings.setEncryptReceivedMessages(context, false)
109
+ Settings.setFcmTokenLastUpdateTimestampAsync(context, 0)
110
+ Settings.setIncomingCallEventsEnabled(context, Constants.SIM1, false)
111
+ Settings.setIncomingCallEventsEnabled(context, Constants.SIM2, false)
112
+ onLogoutComplete()
113
+ }
114
+ }
android/app/src/main/java/com/httpsms/ui/theme/Theme.kt ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms.ui.theme
2
+
3
+ import android.app.Activity
4
+ import android.os.Build
5
+ import androidx.compose.foundation.isSystemInDarkTheme
6
+ import androidx.compose.material3.MaterialTheme
7
+ import androidx.compose.material3.darkColorScheme
8
+ import androidx.compose.material3.dynamicDarkColorScheme
9
+ import androidx.compose.material3.dynamicLightColorScheme
10
+ import androidx.compose.material3.lightColorScheme
11
+ import androidx.compose.runtime.Composable
12
+ import androidx.compose.runtime.SideEffect
13
+ import androidx.compose.ui.graphics.Color
14
+ import androidx.compose.ui.graphics.toArgb
15
+ import androidx.compose.ui.platform.LocalContext
16
+ import androidx.compose.ui.platform.LocalView
17
+ import androidx.core.view.WindowCompat
18
+
19
+ val Blue500 = Color(0xFF2196F3)
20
+ val Pink500 = Color(0xFFE91E63)
21
+ val LogoGreen = Color(0xFF70AB5C)
22
+
23
+ private val DarkColorScheme = darkColorScheme(
24
+ primary = Blue500,
25
+ secondary = Pink500,
26
+ tertiary = Color.White
27
+ )
28
+
29
+ private val LightColorScheme = lightColorScheme(
30
+ primary = Blue500,
31
+ secondary = Pink500,
32
+ tertiary = Color.Black
33
+
34
+ /* Other default colors to override
35
+ background = Color(0xFFFFFBFE),
36
+ surface = Color(0xFFFFFBFE),
37
+ onPrimary = Color.White,
38
+ onSecondary = Color.White,
39
+ onTertiary = Color.White,
40
+ onBackground = Color(0xFF1C1B1F),
41
+ onSurface = Color(0xFF1C1B1F),
42
+ */
43
+ )
44
+
45
+ @Composable
46
+ fun HttpSmsTheme(
47
+ darkTheme: Boolean = isSystemInDarkTheme(),
48
+ // Dynamic color is available on Android 12+
49
+ dynamicColor: Boolean = true,
50
+ content: @Composable () -> Unit
51
+ ) {
52
+ val colorScheme = when {
53
+ dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
54
+ val context = LocalContext.current
55
+ if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
56
+ }
57
+
58
+ darkTheme -> DarkColorScheme
59
+ else -> LightColorScheme
60
+ }
61
+ val view = LocalView.current
62
+ if (!view.isInEditMode) {
63
+ SideEffect {
64
+ val window = (view.context as Activity).window
65
+ window.statusBarColor = colorScheme.background.toArgb()
66
+ WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme
67
+ }
68
+ }
69
+
70
+ MaterialTheme(
71
+ colorScheme = colorScheme,
72
+ typography = Typography,
73
+ content = content
74
+ )
75
+ }
android/app/src/main/java/com/httpsms/ui/theme/Typography.kt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package com.httpsms.ui.theme
2
+
3
+ import androidx.compose.material3.Typography
4
+ import androidx.compose.ui.text.TextStyle
5
+ import androidx.compose.ui.text.font.FontFamily
6
+ import androidx.compose.ui.text.font.FontWeight
7
+ import androidx.compose.ui.unit.sp
8
+
9
+ val Typography = Typography(
10
+ bodyLarge = TextStyle(
11
+ fontFamily = FontFamily.Default,
12
+ fontWeight = FontWeight.Normal,
13
+ fontSize = 16.sp,
14
+ lineHeight = 24.sp,
15
+ letterSpacing = 0.5.sp
16
+ )
17
+ )