Compare commits

..
1 Commits
Author SHA1 Message Date
flamexode cc072484a8 add product group mapping for cards 2026-05-23 23:51:50 +05:00
443 changed files with 3504 additions and 30450 deletions
+3 -1
View File
@@ -1,9 +1,11 @@
services:
release:
# image: git.shihaam.dev/dockerfiles/android-builder
image: git.shihaam.dev/dockerfiles/runners/gradle
hostname: isodroid
network_mode: host
env_file: .env
volumes:
- ./release:/release
- ../../:/source
- /root/.cache/cache-runners/gradle:/root/.gradle
# - /root/.cache/cache-runners/gradle:/root/.gradle
+14 -34
View File
@@ -17,8 +17,6 @@ jobs:
run: |
echo "${{ secrets.KEYSTORE_BASE64 }}" | tr -d '\n' | base64 -d > app/key.jks
echo "${{ secrets.DOTENV_BASE64 }}" | tr -d '\n' | base64 -d > .build/release/.env
echo "ACCOUNT_MVR=${{ vars.ACCOUNT_MVR }}" >> .build/release/.env
echo "ACCOUNT_USD=${{ vars.ACCOUNT_USD }}" >> .build/release/.env
- name: Build APK
working-directory: .build/release
@@ -27,21 +25,24 @@ jobs:
- name: Rename APK
run: |
APP_NAME="${{ gitea.repository }}"
APP_NAME="${APP_NAME//\//-}"
APP_NAME="${APP_NAME##*/}"
TAG="${{ gitea.ref_name }}"
find .build/release/release/ -maxdepth 1 -name "*.apk" | head -1 | xargs -I{} mv {} ".build/release/release/${APP_NAME}-${TAG}.apk"
- name: Extract release notes
run: |
VERSION_CODE=$(grep 'versionCode = ' app/build.gradle.kts | sed 's/.*versionCode = \([0-9]*\).*/\1/')
CHANGELOG="fastlane/metadata/android/en-US/changelogs/${VERSION_CODE}.txt"
if [ -f "$CHANGELOG" ]; then
cp "$CHANGELOG" release_notes.md
else
echo "No changelog found at $CHANGELOG"
echo "No release notes" > release_notes.md
fi
echo "No release notes" > release_notes.md
# VERSION="${{ gitea.ref_name }}"
# VERSION="${VERSION#v}"
#
# awk -v ver="$VERSION" '
# BEGIN { found=0 }
# /^## \[/ {
# if (found) exit
# if ($0 ~ "\\[" ver "\\]") { found=1; next }
# }
# found { print }
# ' CHANGELOG.md > release_notes.md
- name: Create Gitea Release
env:
@@ -50,7 +51,7 @@ jobs:
GITEA_TOKEN: ${{ secrets.PAT_GITEA }}
run: |
APP_NAME="${{ gitea.repository }}"
APP_NAME="${APP_NAME//\//-}"
APP_NAME="${APP_NAME##*/}"
TAG="${{ gitea.ref_name }}"
TITLE="${APP_NAME} ${TAG}"
NOTES_FILE="release_notes.md"
@@ -86,24 +87,3 @@ jobs:
--data-binary "@${ASSET_PATH}"
echo "Uploaded asset: $ASSET_NAME"
- name: Send APK to Telegram
env:
TG_BOT_TOKEN: ${{ secrets.TG_BOT_TOKEN }}
TG_CHAT_ID: ${{ vars.TG_CHAT_ID }}
run: |
if [ -z "$TG_BOT_TOKEN" ] || [ -z "$TG_CHAT_ID" ]; then
echo "TG_BOT_TOKEN or TG_CHAT_ID not set, skipping Telegram upload."
exit 0
fi
APP_NAME="${{ gitea.repository }}"
APP_NAME="${APP_NAME//\//-}"
TAG="${{ gitea.ref_name }}"
ASSET_PATH=".build/release/release/${APP_NAME}-${TAG}.apk"
CAPTION="$(printf '%s\n\n%s' "${APP_NAME} ${TAG}" "$(cat release_notes.md)" | head -c 1024)"
curl -s -X POST "https://api.telegram.org/bot${TG_BOT_TOKEN}/sendDocument" \
-F "chat_id=${TG_CHAT_ID}" \
-F "document=@${ASSET_PATH}" \
--form-string "caption=${CAPTION}"
-7
View File
@@ -1,4 +1,3 @@
.envrc
*.iml
.gradle
/local.properties
@@ -17,11 +16,5 @@ local.properties
docs/mibapi/tmp
docs/bmlapi/tmp
docs/fahipayapi/tmp
docs/mfaisaapi/tmp
docs/dhiraaguapi/tmp
docs/ooredooapi/tmp
docs/ooredooapi/tmp
tmp
app/key.jks
.kotlin/*
.claude/*
+3 -3
View File
@@ -3,11 +3,11 @@
<component name="deploymentTargetSelector">
<selectionStates>
<SelectionState runConfigName="app">
<option name="selectionMode" value="DROPDOWN" />
<DropdownSelection timestamp="2026-06-13T17:53:06.478193524Z">
<option name="selectionMode" value="DIALOG" />
<DropdownSelection timestamp="2026-05-22T00:11:32.873305232Z">
<Target type="DEFAULT_BOOT">
<handle>
<DeviceId pluginId="PhysicalDevice" identifier="serial=a703e092" />
<DeviceId pluginId="PhysicalDevice" identifier="serial=683a9830" />
</handle>
</Target>
</DropdownSelection>
+50 -21
View File
@@ -1,6 +1,6 @@
# Thijooree
# BasedBank
A native Android client for Maldivian banking services. It is a pure client: requests go directly from your device to the banks' own servers using the same protocols as their official apps. No proxy, no backend, no middleman.
A unified Android banking app for Maldivians that combines MIB (Faisanet), BML (Bank of Maldives), and Fahipay into a single interface — with no analytics, no tracking, and no phone-home behaviour outside the banks themselves.
[![AI Slop Inside](https://sladge.net/badge.svg)](https://sladge.net)
[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](LICENSE)
@@ -8,36 +8,65 @@ A native Android client for Maldivian banking services. It is a pure client: req
![Jetpack Compose](https://img.shields.io/badge/Jetpack%20Compose-4285F4?logo=jetpackcompose&logoColor=white)
![Maintained](https://img.shields.io/badge/Maintained-yes-green.svg)
## What it does
- **Multi-bank dashboard** — view balances across all your MIB, BML, and Fahipay accounts in one place, with a combined MVR and USD total
- **Transaction history** — paginated, searchable transaction history per account for MIB CASA, BML CASA, BML prepaid cards, and Fahipay wallet
- **Transfers** — send money between accounts and to saved contacts; supports MIB-to-MIB, BML-to-BML, and cross-bank (MIB↔BML via FAVARA)
- **Contacts** — manage saved beneficiaries across all banks; validates Dhiraagu and Ooredoo numbers and shows the account owner name before you add
- **Fahipay** — full wallet support including balance, history with merchant icons, and Fahipay favourites (Raastas, Reload, Ooredoo Bill, Dhiraagu Bill)
- **QR payments** — scan PayMV QR codes to pre-fill transfers
- **BML foreign limits** — view your foreign currency spending allowances and breakdowns by ATM / POS / ECOM
- **MIB financing** — view active financing deals
## Authentication
The app requires your existing credentials for each bank — the same username/password/OTP seed you use with the official apps. It stores them encrypted using AES-256-GCM backed by the Android Keystore (hardware secure enclave).
Each bank's 2FA uses TOTP, so you need to have your OTP seed (the same secret used by your authenticator app).
## Security
- All credentials encrypted at rest with **AES-256-GCM** (Android Keystore)
- Lock screen protected by **PBKDF2-HMAC-SHA256** (100,000 iterations) with optional biometric unlock
- **FLAG_SECURE** on by default — content hidden in app switcher and screenshots blocked
- All sensitive data excluded from Android cloud backup
- Zero analytics, crash reporters, or third-party SDKs — network traffic goes only to MIB, BML, Fahipay, and the Maldivian telecoms for number validation
See [`docs/AI_SECURITY_CHECK.md`](docs/AI_SECURITY_CHECK.md) for the full security audit.
## Supported banks
| Bank | Login | Accounts | History | Transfers | Contacts |
|---|---|---|---|---|---|
| MIB (Faisanet) | username + password + TOTP | ✓ | ✓ | ✓ | ✓ |
| BML (Bank of Maldives) | username + password + TOTP | ✓ | ✓ | ✓ | ✓ |
| Fahipay | national ID + password + TOTP | ✓ | ✓ | — | ✓ (favourites) |
## Requirements
- Android 8.0+ (API 26)
- Existing accounts with MIB, BML, or Fahipay
- Your TOTP seed (base32 secret from your authenticator app setup) for each bank. See [how to get your TOTP seed](docs/thijooree/faq/totpseed/README.md)
- Your TOTP seed (base32 secret from your authenticator app setup) for each bank
## Download APK
[Gitea Releases](https://git.shihaam.dev/shihaam/thijooree/releases)
[Telegram Channel](https://t.me/s/thijooreeapks)
## Building
## FAQ
Open in Android Studio and run. No API keys or secrets required — all protocol constants are derived from the official apps and are included in the source.
Common questions and setup guides are in the [FAQ](docs/thijooree/faq/README.md).
The release signing config reads from environment variables (`KEYSTORE_PASSWORD`, `KEY_ALIAS`, `KEY_PASSWORD`).
## How it works
BasedBank talks directly to each bank's existing mobile API using the same protocol as their official apps, reverse-engineered from the APKs. It does not use any intermediary server — requests go straight from your device to the bank.
- **MIB**: Blowfish/ECB encrypted JSON over HTTPS with a Diffie-Hellman session key exchange
- **BML**: PKCE OAuth 2.0 flow via the BML web login, exchanged for a Bearer token used on the mobile API
- **Fahipay**: multipart form login with TOTP, session maintained via `__Secure-sess` cookie and `authid` header
## Privacy
No data ever leaves your device except the API calls to the banking services themselves. See the [security audit](docs/thijooree/AI_SECURITY_CHECK.md) for a full list of every server the app connects to.
## Documentation
API reverse-engineering notes and app internals are in [`docs/`](docs/README.md).
No data ever leaves your device except the API calls to the banking services themselves. See the [security audit](docs/AI_SECURITY_CHECK.md) for a full list of every server the app connects to.
## Disclaimer
This is an unofficial third-party app. It is not affiliated with, endorsed by, or supported by MIB, BML, or Fahipay. Use at your own risk. Review the source code before entering your banking credentials.
## Contributing
<blockquote class="twitter-tweet"><p lang="en" dir="ltr">Talk is cheap, send patches.</p>&mdash; FFmpeg (@FFmpeg) <a href="https://x.com/FFmpeg/status/1762805900035686805?ref_src=twsrc%5Etfw">February 28, 2024</a></blockquote>
## License
GNU General Public License v3.0 - See [LICENSE](LICENSE) file for details
+2 -23
View File
@@ -1,18 +1,8 @@
import java.util.Properties
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
}
val localProps = Properties().also { props ->
val f = rootProject.file("local.properties")
if (f.exists()) props.load(f.inputStream())
}
fun localOrEnv(key: String, envKey: String) =
localProps.getProperty(key) ?: System.getenv(envKey) ?: ""
android {
namespace = "sh.sar.basedbank"
compileSdk = 36
@@ -21,13 +11,10 @@ android {
applicationId = "sh.sar.basedbank"
minSdk = 26
targetSdk = 36
versionCode = 36
versionName = "1.0.36"
versionCode = 7
versionName = "1.0.8"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
buildConfigField("String", "ACCOUNT_MVR", "\"${localOrEnv("account.mvr", "ACCOUNT_MVR")}\"")
buildConfigField("String", "ACCOUNT_USD", "\"${localOrEnv("account.usd", "ACCOUNT_USD")}\"")
}
signingConfigs {
@@ -40,10 +27,6 @@ android {
}
buildTypes {
debug {
applicationIdSuffix = ".debug"
versionNameSuffix = "-debug"
}
release {
signingConfig = signingConfigs.getByName("release")
isMinifyEnabled = false
@@ -62,7 +45,6 @@ android {
}
buildFeatures {
viewBinding = true
buildConfig = true
}
}
@@ -105,9 +87,6 @@ dependencies {
// Biometric authentication
implementation("androidx.biometric:biometric:1.1.0")
// Encrypted SharedPreferences (HCE token store)
implementation("androidx.security:security-crypto:1.1.0-alpha06")
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#CC0000"
android:pathData="M0,0h108v108h-108z" />
</vector>
-4
View File
@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_logo_background">#CC0000</color>
</resources>
-4
View File
@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Thijooree Debug</string>
</resources>
-43
View File
@@ -1,43 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
android:shortcutId="transfer"
android:enabled="true"
android:icon="@drawable/ic_shortcut_transfer"
android:shortcutShortLabel="@string/transfer"
android:shortcutLongLabel="@string/transfer">
<intent
android:action="sh.sar.basedbank.OPEN_TRANSFER"
android:targetPackage="sh.sar.basedbank.debug"
android:targetClass="sh.sar.basedbank.MainActivity" />
<categories android:name="android.shortcut.conversation" />
</shortcut>
<shortcut
android:shortcutId="scan_qr"
android:enabled="true"
android:icon="@drawable/ic_shortcut_scan_qr"
android:shortcutShortLabel="@string/transfer_scan_qr"
android:shortcutLongLabel="@string/transfer_scan_qr">
<intent
android:action="sh.sar.basedbank.OPEN_SCAN_QR"
android:targetPackage="sh.sar.basedbank.debug"
android:targetClass="sh.sar.basedbank.MainActivity" />
<categories android:name="android.shortcut.conversation" />
</shortcut>
<shortcut
android:shortcutId="tap_to_pay"
android:enabled="true"
android:icon="@drawable/ic_shortcut_pay_card"
android:shortcutShortLabel="@string/card_pay_nfc"
android:shortcutLongLabel="@string/card_pay_nfc">
<intent
android:action="sh.sar.basedbank.TAP_TO_PAY"
android:targetPackage="sh.sar.basedbank.debug"
android:targetClass="sh.sar.basedbank.MainActivity" />
<categories android:name="android.shortcut.conversation" />
</shortcut>
</shortcuts>
+1 -56
View File
@@ -7,18 +7,10 @@
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-feature android:name="android.hardware.nfc.hce" android:required="false" />
<application
android:name=".BasedBankApp"
android:allowBackup="false"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
@@ -32,38 +24,30 @@
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation"
android:exported="true"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.shortcuts"
android:resource="@xml/shortcuts" />
</activity>
<activity
android:name=".LockActivity"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation"
android:exported="false"
android:windowSoftInputMode="adjustResize" />
<activity
android:name=".ui.onboarding.OnboardingActivity"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation"
android:exported="false" />
<activity
android:name=".ui.login.LoginActivity"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation"
android:exported="false"
android:windowSoftInputMode="adjustResize" />
<activity
android:name=".ui.home.HomeActivity"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|locale|layoutDirection|fontScale|density"
android:exported="false"
android:windowSoftInputMode="adjustPan" />
@@ -72,45 +56,6 @@
android:exported="false"
android:screenOrientation="portrait" />
<activity
android:name=".nfc.BmlTapToPayActivity"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation"
android:exported="false"
android:launchMode="singleTop"
android:theme="@style/Theme.BasedBank" />
<service
android:name=".service.NotificationPollingService"
android:exported="false"
android:foregroundServiceType="dataSync" />
<service
android:name=".nfc.BmlHostCardEmulatorService"
android:exported="true"
android:permission="android.permission.BIND_NFC_SERVICE">
<intent-filter>
<action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<meta-data
android:name="android.nfc.cardemulation.host_apdu_service"
android:resource="@xml/bml_aid_list" />
</service>
<!-- Share-sheet alias: "Scan to Pay" receives shared images and decodes their QR code -->
<activity-alias
android:name=".ScanToPayActivity"
android:targetActivity=".MainActivity"
android:exported="true"
android:label="@string/transfer_scan_qr"
android:icon="@drawable/ic_qr_scan">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
</activity-alias>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 119 KiB

After

Width:  |  Height:  |  Size: 163 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 123 KiB

After

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 92 KiB

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 128 KiB

After

Width:  |  Height:  |  Size: 163 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 191 KiB

After

Width:  |  Height:  |  Size: 294 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 122 KiB

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 133 KiB

After

Width:  |  Height:  |  Size: 227 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 296 KiB

After

Width:  |  Height:  |  Size: 332 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 279 KiB

After

Width:  |  Height:  |  Size: 390 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 135 KiB

After

Width:  |  Height:  |  Size: 146 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 50 KiB

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 154 KiB

After

Width:  |  Height:  |  Size: 197 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 92 KiB

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 133 KiB

After

Width:  |  Height:  |  Size: 185 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 109 KiB

After

Width:  |  Height:  |  Size: 194 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 260 KiB

After

Width:  |  Height:  |  Size: 302 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 112 KiB

After

Width:  |  Height:  |  Size: 147 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 213 KiB

After

Width:  |  Height:  |  Size: 295 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 116 KiB

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 230 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 185 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 267 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 196 KiB

@@ -1 +0,0 @@
visa_bingaa.png
@@ -1 +0,0 @@
visa_bingaa.png
Binary file not shown.

Before

Width:  |  Height:  |  Size: 161 KiB

After

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 192 KiB

After

Width:  |  Height:  |  Size: 208 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

After

Width:  |  Height:  |  Size: 41 KiB

@@ -8,7 +8,6 @@ import sh.sar.basedbank.api.bml.BmlLoginFlow
import sh.sar.basedbank.api.bml.BmlProfile
import sh.sar.basedbank.api.bml.BmlSession
import sh.sar.basedbank.api.fahipay.FahipaySession
import sh.sar.basedbank.api.mfaisa.MfaisaSession
import sh.sar.basedbank.api.models.BankAccount
import sh.sar.basedbank.api.mib.MibLoginFlow
import sh.sar.basedbank.api.mib.MibProfile
@@ -17,13 +16,6 @@ import sh.sar.basedbank.util.CredentialStore
class BasedBankApp : Application() {
/**
* Set to true only after the user passes LockActivity or completes fresh login.
* Resets to false on every process restart so direct ADB/root activity launches
* cannot reach HomeActivity without re-authenticating.
*/
var isUnlocked = false
// Held in memory after successful login; cleared on logout
var accounts: List<BankAccount> = emptyList()
var fullName: String = ""
@@ -49,10 +41,6 @@ class BasedBankApp : Application() {
val fahipaySessions: MutableMap<String, FahipaySession> = mutableMapOf()
var fahipayAccounts: List<BankAccount> = emptyList()
/** Active M-Faisa sessions keyed by loginId (= msisdn). */
val mfaisaSessions: MutableMap<String, MfaisaSession> = mutableMapOf()
var mfaisaAccounts: List<BankAccount> = emptyList()
// ─── MIB helpers ──────────────────────────────────────────────────────────
/** Returns the MIB session for the given account (matched via loginTag). */
@@ -115,36 +103,12 @@ class BasedBankApp : Application() {
fun fahipaySessionFor(account: BankAccount): FahipaySession? =
fahipaySessions[account.loginTag.removePrefix("fahipay_")]
// ─── M-Faisa helpers ──────────────────────────────────────────────────────
/** Returns the M-Faisa session for the given account (matched via loginTag = "mfaisa_${msisdn}"). */
fun mfaisaSessionFor(account: BankAccount): MfaisaSession? =
mfaisaSessions[account.loginTag.removePrefix("mfaisa_")]
/**
* Re-runs `fetchSubscriber` + `doMobileLogin` using the saved credentials for [loginId] and
* replaces the cached session. Call this after catching [sh.sar.basedbank.api.mfaisa.MfaisaSessionExpiredException].
* Returns the fresh session, or null if no credentials are saved for that login.
*/
fun refreshMfaisaSession(loginId: String): MfaisaSession? {
val creds = CredentialStore(this).loadMfaisaCredentials(loginId) ?: return null
val flow = sh.sar.basedbank.api.mfaisa.MfaisaLoginFlow(this)
flow.fetchSubscriber(creds.msisdn)
val result = flow.doMobileLogin(creds.msisdn, creds.pin)
mfaisaSessions[loginId] = result.session
return result.session
}
/** Serialises all MIB profile-switch + request sequences to prevent session corruption. */
val mibMutex = Mutex()
override fun onCreate() {
super.onCreate()
// Only apply wallpaper-based dynamic colors in system theme mode.
// Light/dark modes use content-based accent colors applied per-activity via ThemeHelper.
DynamicColors.applyToActivitiesIfAvailable(this) { _, _ ->
getSharedPreferences("prefs", MODE_PRIVATE).getString("theme", "system") == "system"
}
DynamicColors.applyToActivitiesIfAvailable(this)
val theme = getSharedPreferences("prefs", MODE_PRIVATE).getString("theme", "system")
AppCompatDelegate.setDefaultNightMode(when (theme) {
@@ -21,8 +21,6 @@ import kotlinx.coroutines.withContext
import sh.sar.basedbank.databinding.ActivityLockBinding
import sh.sar.basedbank.ui.home.HomeActivity
import sh.sar.basedbank.util.CredentialStore
import sh.sar.basedbank.util.ThemeHelper
import sh.sar.basedbank.BasedBankApp
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
@@ -47,7 +45,6 @@ class LockActivity : AppCompatActivity() {
}
override fun onCreate(savedInstanceState: Bundle?) {
ThemeHelper.applyAccent(this)
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
binding = ActivityLockBinding.inflate(layoutInflater)
@@ -57,9 +54,6 @@ class LockActivity : AppCompatActivity() {
isAppearanceLightStatusBars = isLight
isAppearanceLightNavigationBars = isLight
}
val ta = obtainStyledAttributes(intArrayOf(android.R.attr.colorBackground))
window.statusBarColor = ta.getColor(0, if (isLight) android.graphics.Color.WHITE else android.graphics.Color.BLACK)
ta.recycle()
ViewCompat.setOnApplyWindowInsetsListener(binding.root) { view, insets ->
val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
view.setPadding(bars.left, bars.top, bars.right, bars.bottom)
@@ -124,17 +118,8 @@ class LockActivity : AppCompatActivity() {
else
com.google.android.material.R.attr.materialButtonOutlinedStyle
val btn = MaterialButton(this, null, style).apply {
if (key == "⌫" || key == "✓") {
text = ""
icon = ContextCompat.getDrawable(this@LockActivity,
if (key == "⌫") R.drawable.ic_backspace else R.drawable.ic_check)
iconGravity = MaterialButton.ICON_GRAVITY_TEXT_START
iconPadding = 0
iconSize = (28 * dp).toInt()
} else {
text = key
textSize = 24f
}
text = key
textSize = 24f
insetTop = 0; insetBottom = 0
minimumWidth = 0; minimumHeight = 0
cornerRadius = btnSize / 2
@@ -274,28 +259,10 @@ class LockActivity : AppCompatActivity() {
}
private fun proceed() {
(application as BasedBankApp).isUnlocked = true
if (intent.getBooleanExtra(EXTRA_RESUME, false)) {
finish()
} else {
val store = CredentialStore(this)
val hasCredentials = store.hasMibCredentials() || store.hasBmlCredentials() ||
store.hasFahipayCredentials() || store.hasMfaisaCredentials()
if (!hasCredentials) {
startActivity(Intent(this, sh.sar.basedbank.ui.login.LoginActivity::class.java))
finish()
return
}
val navDest = intent.getIntExtra("nav_destination", -1)
val autoScan = intent.getBooleanExtra("auto_scan", false)
val autoTapMode = intent.getBooleanExtra("auto_tap_mode", false)
val shareQrText = intent.getStringExtra("share_qr_text")
startActivity(Intent(this, HomeActivity::class.java).apply {
if (navDest != -1) putExtra("nav_destination", navDest)
if (autoScan) putExtra("auto_scan", true)
if (autoTapMode) putExtra("auto_tap_mode", true)
if (shareQrText != null) putExtra("share_qr_text", shareQrText)
})
startActivity(Intent(this, HomeActivity::class.java))
finish()
}
}
@@ -7,63 +7,16 @@ import sh.sar.basedbank.ui.home.HomeActivity
import sh.sar.basedbank.ui.login.LoginActivity
import sh.sar.basedbank.ui.onboarding.OnboardingActivity
import sh.sar.basedbank.util.CredentialStore
import sh.sar.basedbank.BasedBankApp
import sh.sar.basedbank.R
class MainActivity : AppCompatActivity() {
private fun decodeQrFromSharedImage(uri: android.net.Uri): String? {
return try {
val bitmap = contentResolver.openInputStream(uri)?.use {
android.graphics.BitmapFactory.decodeStream(it)
} ?: return null
val opts = de.markusfisch.android.zxingcpp.ZxingCpp.ReaderOptions(
tryHarder = true, tryRotate = true, tryInvert = true,
tryDownscale = true, maxNumberOfSymbols = 1,
textMode = de.markusfisch.android.zxingcpp.ZxingCpp.TextMode.PLAIN
)
val result = (de.markusfisch.android.zxingcpp.ZxingCpp.readBitmap(
bitmap, 0, 0, bitmap.width, bitmap.height, 0,
opts.apply { binarizer = de.markusfisch.android.zxingcpp.ZxingCpp.Binarizer.LOCAL_AVERAGE }
) ?: de.markusfisch.android.zxingcpp.ZxingCpp.readBitmap(
bitmap, 0, 0, bitmap.width, bitmap.height, 0,
opts.apply { binarizer = de.markusfisch.android.zxingcpp.ZxingCpp.Binarizer.GLOBAL_HISTOGRAM }
))?.firstOrNull()?.text
bitmap.recycle()
result
} catch (_: Exception) { null }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val prefs = getSharedPreferences("prefs", MODE_PRIVATE)
val onboardingDone = prefs.getBoolean("onboarding_done", false)
val securitySet = prefs.getString("security_method", null) != null
val store = CredentialStore(this)
val hasCredentials = store.hasMibCredentials() || store.hasBmlCredentials() ||
store.hasFahipayCredentials() || store.hasMfaisaCredentials()
// Image shared via "Scan to Pay" — decode QR here while we still hold the URI permission
val shareQrText: String? = if (intent?.action == Intent.ACTION_SEND &&
intent.type?.startsWith("image/") == true) {
val uri: android.net.Uri? =
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU)
intent.getParcelableExtra(Intent.EXTRA_STREAM, android.net.Uri::class.java)
else
@Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_STREAM)
if (uri != null) decodeQrFromSharedImage(uri) else null
} else null
val navDestination = when (intent?.action) {
"sh.sar.basedbank.OPEN_TRANSFER" -> R.id.nav_transfer
"sh.sar.basedbank.OPEN_SCAN_QR" -> R.id.nav_transfer
"sh.sar.basedbank.OPEN_PAY_WITH_CARD" -> R.id.nav_pay_with_card
"sh.sar.basedbank.TAP_TO_PAY" -> R.id.nav_pay_with_card
else -> -1
}
val autoScan = intent?.action == "sh.sar.basedbank.OPEN_SCAN_QR"
val autoTapMode = intent?.action == "sh.sar.basedbank.TAP_TO_PAY"
val hasCredentials = store.hasMibCredentials() || store.hasBmlCredentials() || store.hasFahipayCredentials()
val target = when {
!onboardingDone -> OnboardingActivity::class.java
@@ -71,17 +24,7 @@ class MainActivity : AppCompatActivity() {
securitySet -> LockActivity::class.java // proceed() → HomeActivity
else -> HomeActivity::class.java
}
// No lock screen configured — mark as unlocked so HomeActivity's guard passes
if (target == HomeActivity::class.java) {
(application as BasedBankApp).isUnlocked = true
}
startActivity(Intent(this, target).apply {
if (navDestination != -1) putExtra("nav_destination", navDestination)
if (autoScan) putExtra("auto_scan", true)
if (autoTapMode) putExtra("auto_tap_mode", true)
if (shareQrText != null) putExtra("share_qr_text", shareQrText)
})
startActivity(Intent(this, target))
finish()
}
}
@@ -7,8 +7,6 @@ import java.util.concurrent.TimeUnit
internal const val BML_BASE_URL = "https://www.bankofmaldives.com.mv/internetbanking"
internal val BML_USER_AGENT = "bml-mobile-banking/348 (${Build.MANUFACTURER}; Android ${Build.VERSION.RELEASE}; ${Build.MODEL})"
/** Browser User-Agent used for BML's web/Cloudflare-fronted endpoints (login, merchant pay page, ACS). */
internal val BML_WEB_USER_AGENT = "Mozilla/5.0 (Android ${Build.VERSION.RELEASE}; Mobile; rv:150.0) Gecko/150.0 Firefox/150.0"
internal const val BML_APP_VERSION = "2.1.44.348"
internal fun newBmlApiClient(): OkHttpClient = OkHttpClient.Builder()
@@ -16,15 +14,9 @@ internal fun newBmlApiClient(): OkHttpClient = OkHttpClient.Builder()
.readTimeout(30, TimeUnit.SECONDS)
.build()
/**
* Headers are sent in the order (and with the names) BML's own app uses. `accept` is not optional:
* handled errors come back as JSON either way, but when a route throws (HTTP 500) the server
* renders the Internet Banking HTML page — under HTTP 200 — unless the request asks for JSON.
*/
internal fun bmlApiRequest(session: BmlSession, url: String): Request =
Request.Builder().url(url)
.header("accept", "application/json")
.header("Authorization", "Bearer ${session.accessToken}")
.header("User-Agent", BML_USER_AGENT)
.header("x-app-version", BML_APP_VERSION)
.header("user-agent", BML_USER_AGENT)
.header("authorization", "Bearer ${session.accessToken}")
.build()
@@ -1,55 +0,0 @@
package sh.sar.basedbank.api.bml
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import sh.sar.basedbank.api.models.BankServerException
data class BmlCardActionResult(
val success: Boolean,
val message: String
)
class BmlCardClient {
private val client = newBmlApiClient()
/**
* Freezes or unfreezes a BML card.
* @param cardId BML card UUID (BankAccount.internalId)
* @param action "freeze" or "unfreeze"
*/
fun setCardFreezeState(session: BmlSession, cardId: String, action: String): BmlCardActionResult {
val body = JSONObject().apply {
put("card", cardId)
put("action", action)
}.toString().toRequestBody("application/json".toMediaType())
val request = Request.Builder()
.url("$BML_BASE_URL/api/mobile/services/card/freeze")
.post(body)
.header("Authorization", "Bearer ${session.accessToken}")
.header("User-Agent", BML_USER_AGENT)
.header("x-app-version", BML_APP_VERSION)
.header("accept", "application/json")
.build()
val resp = client.newCall(request).execute()
val code = resp.code
val responseBody = resp.body?.string()
resp.close()
if (code == 401 || code == 419) throw AuthExpiredException()
if (code in 500..599) throw BankServerException("BML")
return try {
val json = JSONObject(responseBody ?: "")
val ok = json.optBoolean("success") && json.optInt("code") == 0
BmlCardActionResult(
success = ok,
message = json.optString("payload").ifBlank { json.optString("message") }
)
} catch (_: Exception) {
BmlCardActionResult(success = false, message = "")
}
}
}
@@ -4,17 +4,10 @@ import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import sh.sar.basedbank.api.models.BankServerException
import sh.sar.basedbank.api.models.BankTransaction
import java.text.SimpleDateFormat
import java.util.Locale
data class BmlCardHistoryResult(
val statement: List<BankTransaction>,
val outstanding: List<BankTransaction>,
val unbilled: List<BankTransaction>
)
class BmlHistoryClient {
private val client = newBmlApiClient()
@@ -37,7 +30,6 @@ class BmlHistoryClient {
val json = resp.body?.string() ?: return Pair(emptyList(), 0)
resp.close()
if (code == 401 || code == 419) throw AuthExpiredException()
if (code in 500..599) throw BankServerException("BML")
return try {
val root = JSONObject(json)
if (!root.optBoolean("success")) return Pair(emptyList(), 0)
@@ -76,7 +68,7 @@ class BmlHistoryClient {
accountDisplayName: String,
accountNumber: String,
month: String
): BmlCardHistoryResult {
): List<BankTransaction> {
val body = """{"card":"$cardId","month":"$month"}"""
.toRequestBody("application/json".toMediaType())
val resp = client.newCall(
@@ -87,95 +79,74 @@ class BmlHistoryClient {
.build()
).execute()
val code = resp.code
val json = resp.body?.string() ?: return BmlCardHistoryResult(emptyList(), emptyList(), emptyList())
resp.close()
if (code == 401 || code == 419) throw AuthExpiredException()
if (code in 500..599) throw BankServerException("BML")
return try {
val root = JSONObject(json)
if (!root.optBoolean("success")) return BmlCardHistoryResult(emptyList(), emptyList(), emptyList())
val payload = root.optJSONObject("payload")
?: return BmlCardHistoryResult(emptyList(), emptyList(), emptyList())
val outstanding = parseCardArray(
payload.optJSONObject("outstanding")?.optJSONArray("CardOutStdAuthDetails"),
idPrefix = "auth", accountNumber, accountDisplayName
)
val unbilled = parseCardArray(
payload.optJSONObject("unbilled")?.optJSONArray("CardUnbillTxnDetails"),
idPrefix = "unbilled", accountNumber, accountDisplayName
)
val statement = parseCardArray(
payload.optJSONArray("cardstatement"),
idPrefix = "stmt", accountNumber, accountDisplayName
)
BmlCardHistoryResult(statement, outstanding, unbilled)
} catch (_: Exception) { BmlCardHistoryResult(emptyList(), emptyList(), emptyList()) }
}
private fun parseCardArray(
arr: org.json.JSONArray?,
idPrefix: String,
accountNumber: String,
accountDisplayName: String
): List<BankTransaction> {
if (arr == null) return emptyList()
return (0 until arr.length()).map { i ->
val item = arr.getJSONObject(i)
val ref = item.optString("TranApprCode")
BankTransaction(
id = "${idPrefix}_${ref.ifBlank { i.toString() }}",
date = item.optString("DateTime"),
description = item.optString("TranDesc").trim(),
amount = item.optDouble("BillingAmount", 0.0),
currency = item.optString("BillingCcy", "MVR"),
counterpartyName = null,
reference = ref.takeIf { it.isNotBlank() },
accountNumber = accountNumber,
accountDisplayName = accountDisplayName,
source = "BML_CARD"
)
}
}
fun fetchPendingHistory(
session: BmlSession,
accountId: String,
accountDisplayName: String,
accountNumber: String
): List<BankTransaction> {
val resp = client.newCall(
Request.Builder().url("$BML_BASE_URL/api/mobile/history/pending/$accountId")
.header("Authorization", "Bearer ${session.accessToken}")
.header("User-Agent", BML_USER_AGENT)
.header("x-app-version", BML_APP_VERSION)
.build()
).execute()
val code = resp.code
val json = resp.body?.string() ?: return emptyList()
resp.close()
if (code == 401 || code == 419) throw AuthExpiredException()
if (code in 500..599) throw BankServerException("BML")
return try {
val root = JSONObject(json)
if (!root.optBoolean("success")) return emptyList()
val payload = root.optJSONArray("payload") ?: return emptyList()
(0 until payload.length()).map { i ->
val item = payload.getJSONObject(i)
BankTransaction(
id = item.optString("LockedID"),
date = item.optString("FromDate"),
description = "Pending",
amount = -item.optDouble("LockedAmount", 0.0),
currency = "MVR",
counterpartyName = item.optString("Description").trim().takeIf { it.isNotBlank() },
reference = null,
accountNumber = accountNumber,
accountDisplayName = accountDisplayName,
source = "BML"
)
val payload = root.optJSONObject("payload") ?: return emptyList()
val result = mutableListOf<BankTransaction>()
val authDetails = payload.optJSONObject("outstanding")
?.optJSONArray("CardOutStdAuthDetails")
if (authDetails != null) {
for (i in 0 until authDetails.length()) {
val item = authDetails.getJSONObject(i)
result.add(BankTransaction(
id = "auth_${item.optString("TranApprCode")}_$i",
date = item.optString("DateTime"),
description = item.optString("TranDesc").trim(),
amount = item.optDouble("BillingAmount", 0.0),
currency = item.optString("BillingCcy", "MVR"),
counterpartyName = null,
reference = item.optString("TranApprCode").takeIf { it.isNotBlank() },
accountNumber = accountNumber,
accountDisplayName = accountDisplayName,
source = "BML_CARD"
))
}
}
val unbilled = payload.optJSONObject("unbilled")
?.optJSONArray("CardUnbillTxnDetails")
if (unbilled != null) {
for (i in 0 until unbilled.length()) {
val item = unbilled.getJSONObject(i)
result.add(BankTransaction(
id = "unbilled_${item.optString("TranApprCode")}_$i",
date = item.optString("DateTime"),
description = item.optString("TranDesc").trim(),
amount = item.optDouble("BillingAmount", 0.0),
currency = item.optString("BillingCcy", "MVR"),
counterpartyName = null,
reference = item.optString("TranApprCode").takeIf { it.isNotBlank() },
accountNumber = accountNumber,
accountDisplayName = accountDisplayName,
source = "BML_CARD"
))
}
}
val statement = payload.optJSONArray("cardstatement")
if (statement != null) {
for (i in 0 until statement.length()) {
val item = statement.getJSONObject(i)
result.add(BankTransaction(
id = "stmt_${item.optString("TranRef", i.toString())}",
date = item.optString("TransDate", item.optString("TranDate", "")),
description = item.optString("TranDesc", item.optString("Description", "")).trim(),
amount = -item.optDouble("TranAmount", 0.0),
currency = item.optString("TranCcy", "MVR"),
counterpartyName = null,
reference = item.optString("TranRef").takeIf { it.isNotBlank() },
accountNumber = accountNumber,
accountDisplayName = accountDisplayName,
source = "BML_CARD"
))
}
}
result
} catch (_: Exception) { emptyList() }
}
@@ -27,7 +27,7 @@ class BmlLoginFlow {
private val REDIRECT_URI = "https://app.bankofmaldives.com.mv/oauth/mobile-callback"
private val APP_USER_AGENT = "bml-mobile-banking/348 (${android.os.Build.MANUFACTURER}; Android ${android.os.Build.VERSION.RELEASE}; ${android.os.Build.MODEL})"
private val APP_VERSION = "2.1.44.348"
private val WEB_USER_AGENT = BML_WEB_USER_AGENT
private val WEB_USER_AGENT = "Mozilla/5.0 (Android ${android.os.Build.VERSION.RELEASE}; Mobile; rv:150.0) Gecko/150.0 Firefox/150.0"
private val cookieStore = mutableMapOf<String, MutableList<Cookie>>()
private val cookieJar = object : CookieJar {
@@ -1,365 +0,0 @@
package sh.sar.basedbank.api.bml
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.FormBody
import okhttp3.HttpUrl
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import sh.sar.basedbank.api.bml.BmlMerchantTxnClient.Companion.API_BASE
import sh.sar.basedbank.api.bml.BmlMerchantTxnClient.Companion.PAGE_ORIGIN
import java.security.KeyFactory
import java.security.spec.MGF1ParameterSpec
import java.security.spec.X509EncodedKeySpec
import java.util.concurrent.TimeUnit
import javax.crypto.Cipher
import javax.crypto.spec.OAEPParameterSpec
import javax.crypto.spec.PSource
import android.util.Base64
/**
* Pays a BML Merchant Services payment link by card, for merchants that don't have BML Pay
* enabled. It performs the same request sequence the link's own card form (Pomelo JS) and the
* issuer's 3-D Secure page perform in a browser:
*
* 1. `GET public-client/credentials/<id>` (auth header: the page's `pomeloJsKey`) → RSA public
* key + Pomelo API key.
* 2. `POST api.pay.pomelopay.com/bin-lookup` with the PAN, CVV and `YYMM` expiry, each
* RSA-OAEP(SHA-1) encrypted with that key → a card `tokenId`.
* 3. `POST public-client/transactions/next-action` RATE_OPTIONS, polling while the server says
* WAIT, until it returns a `3dsUrl`.
* 4. The 3-D Secure challenge on BML's Wibmo ACS: the render page auto-posts the `creq`, we pick
* the "Authenticator" channel and submit the BML token's TOTP. The ACS then auto-posts the
* result to the Mastercard gateway, which posts it back to BML's `mpgsNotification`.
* 5. Poll next-action until TRANSACTION_CONFIRMED. A decline after 3-D Secure (e.g. insufficient
* funds) doesn't show up there: it's a new `paymentErrorHistory` entry on the transaction,
* checked alongside.
* 6. Return to the merchant: `GET <txn>?wait=1` redirects to the merchant's `redirectUrl` with a
* signed `state=CONFIRMED` — the browser's last hop, and how merchants (Dhiraagu, Ooredoo)
* learn they were paid. Without it the card is charged but the merchant never delivers.
*
* Every call blocks, so run it on an IO thread. Use one instance per payment — it keeps the ACS
* session cookies.
*/
class BmlMerchantCardPayClient {
data class Card(
val pan: String,
val expiryMonth: String, // "07"
val expiryYear: String, // "28"
val cvv: String,
val holderName: String
)
sealed class Result {
/** Paid. [merchantNotified] is false when the return to the merchant (step 6) failed. */
data class Success(val merchantNotified: Boolean) : Result()
data class Failure(val message: String) : Result()
}
private val cookies = mutableMapOf<String, MutableList<Cookie>>()
private val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(45, TimeUnit.SECONDS)
// Credentials/next-action tolerate okhttp, but the Cloudflare-fronted ACS does not — send a
// browser UA on everything (only when the caller didn't set one).
.addInterceptor { chain ->
val req = chain.request()
chain.proceed(
if (req.header("User-Agent") == null)
req.newBuilder().header("User-Agent", BML_WEB_USER_AGENT).build()
else req
)
}
.cookieJar(object : CookieJar {
override fun saveFromResponse(url: HttpUrl, newCookies: List<Cookie>) {
val list = cookies.getOrPut(url.host) { mutableListOf() }
for (c in newCookies) { list.removeAll { it.name == c.name }; list.add(c) }
}
override fun loadForRequest(url: HttpUrl): List<Cookie> =
cookies.values.flatten().filter { it.matches(url) }
})
.build()
/**
* Runs the whole payment. [otp] returns the current BML token code; it is called again with
* `retry = true` if the ACS rejects a code (it can expire between generating and submitting).
*/
fun pay(page: BmlMerchantTxnClient.PayPage, card: Card, otp: (retry: Boolean) -> String): Result {
val pk = page.pomeloKey ?: return Result.Failure("This merchant doesn't accept card payments")
val txnId = page.transactionId
val txnClient = BmlMerchantTxnClient()
val browserId = runCatching { txnClient.announceBrowser(txnId) }.getOrNull()
// Earlier attempts' declines are already in the history; only newer ones are ours
val priorErrors = browserId?.let { id -> runCatching { txnClient.paymentErrors(txnId, id).size }.getOrNull() }
// 1-2. Credentials, then tokenise the card with Pomelo
val creds = getJson("$API_BASE/public-client/credentials/$txnId", pk)
val keyInfo = creds.getJSONObject("publicKey")
val publicKey = parsePublicKey(keyInfo.getString("publicKeyPem"))
val binBody = JSONObject()
.put("encryptedCardNumber", encrypt(publicKey, card.pan))
.put("encryptedCardSecurityCode", encrypt(publicKey, card.cvv))
.put("encryptedCardExpiry", encrypt(publicKey, card.expiryYear + card.expiryMonth))
.put("externalId", txnId)
.put("cardHolderName", card.holderName)
.put("encryptedCardExpiryMonth", card.expiryMonth)
.put("encryptedCardExpiryYear", card.expiryYear)
.put("encSerialId", keyInfo.getString("publicKeyId"))
val binReq = Request.Builder()
.url(creds.optString("binLookupUrl").ifBlank { "https://api.pay.pomelopay.com/bin-lookup" })
.post(binBody.toString().toRequestBody(JSON))
.header("tenant", "bankofmaldives")
.header("x-api-key", creds.getString("apiKey"))
.header("x-tenant-id", creds.optString("tid"))
.build()
val bin = execJson(binReq)
val tokenId = bin.optString("tokenId").ifBlank { return Result.Failure("Card was not accepted") }
// 3. Rate options → poll while WAIT → 3-D Secure URL
val cardFields = JSONObject()
.put("transactionId", txnId)
.put("tokenId", tokenId)
.put("bin8", bin.optString("bin8"))
.put("cardBrand", bin.optString("brand"))
for ((from, to) in listOf("issuer" to "cardIssuer", "country" to "cardCountry",
"cardCategory" to "cardCategory", "isCommercial" to "isCommercial",
"isPrepaid" to "isPrepaid", "isReloadable" to "isReloadable", "paddedPan" to "paddedPan")) {
if (bin.has(from) && !bin.isNull(from)) cardFields.put(to, bin.get(from))
}
var action = nextAction(pk, copy(cardFields).put("action", "RATE_OPTIONS").withBrowserInfo())
val resolved = setOf("WAIT", "POLL", "TRANSACTION_CONFIRMED", "TRANSACTION_FAILED")
if (action.optString("action") !in resolved && action.optString("3dsUrl").isBlank()) {
action = nextAction(pk, copy(cardFields).put("action", "THREEDS").withBrowserInfo())
}
var threeDsUrl: String? = null
for (attempt in 0..MAX_POLLS) {
when (action.optString("action")) {
"TRANSACTION_CONFIRMED" -> return confirmed(txnId)
"TRANSACTION_FAILED" -> return Result.Failure("The bank declined the payment")
}
threeDsUrl = action.optString("3dsUrl").ifBlank { null }
if (threeDsUrl != null) break
if (attempt == MAX_POLLS) return Result.Failure("Timed out waiting for the bank")
Thread.sleep(POLL_MS)
action = poll(pk, txnId)
}
// 4. 3-D Secure challenge (handles the authenticator channel + TOTP)
runThreeDs(threeDsUrl!!, otp)?.let { return it }
// 5. Wait for the gateway's verdict to reach BML
repeat(MAX_POLLS * 2) {
when (poll(pk, txnId).optString("action")) {
"TRANSACTION_CONFIRMED" -> return confirmed(txnId)
"TRANSACTION_FAILED" -> return Result.Failure("The bank declined the payment")
}
if (browserId != null && priorErrors != null) {
runCatching { txnClient.paymentErrors(txnId, browserId) }.getOrNull()
?.drop(priorErrors)?.lastOrNull()
?.let { return Result.Failure(it.message.ifBlank { "The bank declined the payment" }) }
}
Thread.sleep(POLL_MS / 2)
}
return Result.Failure("Payment status unknown — check with the merchant before retrying")
}
/** The payment went through: return to the merchant, then report success either way. */
private fun confirmed(txnId: String) = Result.Success(merchantNotified = returnToMerchant(txnId))
/**
* What the browser does once the payment page sees the confirmation: loads `<txn>?wait=1`,
* which 302s to the merchant's `redirectUrl` (`…?transactionId=<id>&state=CONFIRMED&signature=…`)
* and on to its receipt page. Some merchants' callback page instead auto-submits a form on
* load (Ooredoo's posts the result on to its own site), so those forms are submitted too.
* Retries a couple of times; true when the chain ended on a 2xx page.
*/
private fun returnToMerchant(txnId: String): Boolean {
repeat(RETURN_ATTEMPTS) { attempt ->
if (attempt > 0) Thread.sleep(RETURN_RETRY_MS)
val ok = runCatching {
var request = browserNav(Request.Builder().url("$PAGE_ORIGIN/$txnId?wait=1"))
for (hop in 0..MAX_AUTO_SUBMITS) {
val (code, html, url) = client.newCall(request).execute().use {
Triple(it.code, it.body?.string().orEmpty(), it.request.url.toString())
}
if (code !in 200..299) return@runCatching false
// A page that only exists to post itself onward, like the ACS's own hops
if (hop == MAX_AUTO_SUBMITS || !AUTO_SUBMIT.containsMatchIn(html)) return@runCatching true
val form = AcsForm.parse(html, url) ?: return@runCatching true
request = browserNav(form.toRequest().newBuilder())
}
true
}.getOrDefault(false)
if (ok) return true
}
return false
}
private fun browserNav(builder: Request.Builder): Request = builder
.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
.header("Accept-Language", "en-US,en;q=0.9")
.build()
/** Drives the ACS challenge. Returns null on success, or a Failure to stop the payment. */
private fun runThreeDs(threeDsUrl: String, otp: (Boolean) -> String): Result? {
// render-tds: an auto-submitting form (with an explicit action) that posts the creq to the
// issuer's ACS. The ACS's own channel/OTP forms carry no action attribute — their JS posts
// back to this same creq URL — so it is the fallback action for everything that follows.
var form = AcsForm.parse(execText(get(threeDsUrl)), null)
?: return Result.Failure("Couldn't start card authentication")
val acsUrl = form.action
var html = execText(form.toRequest())
// Channel picker (Mobile / Email / Authenticator). The BML token is the "token" channel.
if (html.contains("name=\"destValue\"")) {
form = AcsForm.parse(html, acsUrl) ?: return Result.Failure("Unexpected authentication page")
form.fields["destValue"] = "token"
form.fields["selectChannel"] = "token"
form.fields["authMethod"] = "OOB"
form.fields["otpDest"] = ""
form.fields["formReqType"] = "SUBMIT"
html = execText(form.toRequest())
}
// OTP entry. Submit the token code; if it expired, ask for a fresh one once and retry.
// A rejected code comes back as the OTP page again with "The OTP code you entered is
// incorrect Please try again."
var retry = false
for (attempt in 0..1) {
form = AcsForm.parse(html, acsUrl) ?: break
if (!form.fields.containsKey("otpValue")) break
form.fields["otpValue"] = otp(retry)
form.fields["formReqType"] = "SUBMIT"
html = execText(form.toRequest())
if (!otpRejected(html)) break
retry = true
}
if (otpRejected(html)) return Result.Failure("The bank rejected the BML token code. Check the phone's clock and try again.")
// On success the ACS returns an auto-posting form to the gateway; follow it (and the
// gateway's own auto-post back to BML) so the verdict is recorded before we poll.
repeat(3) {
val next = AcsForm.parse(html, acsUrl) ?: return null
if (next.fields.keys.none { it == "cres" || it == "order.id" }) return null
html = execText(next.toRequest())
}
return null
}
private fun otpRejected(html: String) = html.contains("name=\"otpValue\"") &&
(html.contains("incorrect", true) || html.contains("expired", true))
// ── next-action helpers ──────────────────────────────────────────────────
private fun nextAction(pk: String, body: JSONObject): JSONObject =
execJson(Request.Builder()
.url("$API_BASE/public-client/transactions/next-action")
.post(body.toString().toRequestBody(JSON))
.header("Authorization", pk)
.build())
private fun poll(pk: String, txnId: String): JSONObject =
nextAction(pk, JSONObject().put("action", "POLL").put("transactionId", txnId))
private fun JSONObject.withBrowserInfo(): JSONObject = this
.put("javaEnabled", false).put("javascriptEnabled", true)
.put("language", "en-US").put("colorDepth", 24)
.put("screenHeight", 1850).put("screenWidth", 1080)
.put("tz", java.util.TimeZone.getDefault().getOffset(System.currentTimeMillis()) / -60000)
.put("userAgent", "Mozilla/5.0 (Android ${android.os.Build.VERSION.RELEASE}; Mobile)")
private fun copy(o: JSONObject) = JSONObject(o.toString())
// ── HTTP ─────────────────────────────────────────────────────────────────
private fun get(url: String) = Request.Builder().url(url).build()
private fun getJson(url: String, auth: String): JSONObject =
execJson(Request.Builder().url(url).header("Authorization", auth).header("Accept", "application/json").build())
private fun execJson(request: Request): JSONObject = client.newCall(request).execute().use { r ->
val text = r.body?.string().orEmpty()
if (!r.isSuccessful) throw Exception("Request failed (HTTP ${r.code})")
if (text.isBlank()) JSONObject() else JSONObject(text)
}
private fun execText(request: Request): String = client.newCall(request).execute().use { r ->
r.body?.string().orEmpty()
}
// ── RSA-OAEP(SHA-1), matching the Pomelo JS crypto.subtle config ──────────
private fun parsePublicKey(pem: String): java.security.PublicKey {
val der = Base64.decode(pem
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replace(Regex("\\s"), ""), Base64.DEFAULT)
return KeyFactory.getInstance("RSA").generatePublic(X509EncodedKeySpec(der))
}
private fun encrypt(key: java.security.PublicKey, value: String): String {
val cipher = Cipher.getInstance("RSA/ECB/OAEPPadding")
cipher.init(Cipher.ENCRYPT_MODE, key, OAEPParameterSpec(
"SHA-1", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT))
return Base64.encodeToString(cipher.doFinal(value.toByteArray(Charsets.UTF_8)), Base64.NO_WRAP)
}
/**
* One `application/x-www-form-urlencoded` form scraped from an ACS HTML page: its POST target
* plus every `<input>` name/value. [fields] is mutable so the caller can fill in the chosen
* channel and the OTP before re-submitting.
*/
private class AcsForm(val action: String, val fields: MutableMap<String, String>) {
fun toRequest(): Request {
val body = FormBody.Builder()
for ((k, v) in fields) body.add(k, v)
return Request.Builder().url(action).post(body.build()).build()
}
companion object {
private val FORM = Regex("<form\\b[^>]*>", RegexOption.IGNORE_CASE)
private val ACTION = Regex("action\\s*=\\s*[\"']([^\"']+)[\"']", RegexOption.IGNORE_CASE)
private val INPUT = Regex("<input\\b[^>]*>", RegexOption.IGNORE_CASE)
private val NAME = Regex("name\\s*=\\s*[\"']([^\"']+)[\"']", RegexOption.IGNORE_CASE)
private val VALUE = Regex("value\\s*=\\s*[\"']([^\"']*)[\"']", RegexOption.IGNORE_CASE)
/**
* The first `<form>` and its inputs. The form's `action` is used when present;
* otherwise [defaultAction] (the ACS pages set it via JS to the current creq URL).
* Null only when there is no form, or no action at all.
*/
fun parse(html: String, defaultAction: String?): AcsForm? {
val form = FORM.find(html) ?: return null
val action = ACTION.find(form.value)?.groupValues?.get(1)?.let { unescape(it) }
?: defaultAction ?: return null
val fields = linkedMapOf<String, String>()
for (m in INPUT.findAll(html)) {
val name = NAME.find(m.value)?.groupValues?.get(1) ?: continue
fields[unescape(name)] = unescape(VALUE.find(m.value)?.groupValues?.get(1) ?: "")
}
return AcsForm(action, fields)
}
private fun unescape(s: String) = s
.replace("&amp;", "&").replace("&quot;", "\"")
.replace("&#34;", "\"").replace("&#39;", "'").replace("&lt;", "<").replace("&gt;", ">")
}
}
companion object {
private val JSON = "application/json".toMediaType()
private const val POLL_MS = 5_000L
private const val MAX_POLLS = 10
private const val RETURN_ATTEMPTS = 3
private const val RETURN_RETRY_MS = 2_000L
/** Auto-submitting merchant pages followed on the way back; Ooredoo has one. */
private const val MAX_AUTO_SUBMITS = 2
/** `<body onload="document.forms['x'].submit()">` and the like. */
private val AUTO_SUBMIT = Regex("""onload\s*=\s*("[^"]*|'[^']*)\.submit\(\)""", RegexOption.IGNORE_CASE)
}
}
@@ -1,185 +0,0 @@
package sh.sar.basedbank.api.bml
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONArray
import org.json.JSONObject
/**
* BML Merchant Services payment links (`https://transaction.merchants.bankofmaldives.com.mv/<id>`),
* e.g. the bill links Fenaka sends. Merchants with BML Pay enabled get their QR's text fetched so it
* can go through the regular BML QR payment flow; card-only merchants are paid by
* [BmlMerchantCardPayClient] instead — [fetchPayPage] tells the two apart.
*/
class BmlMerchantTxnClient {
private val client = newBmlApiClient()
/** What the payment page knows about a transaction, from its embedded `window.appData`. */
data class PayPage(
val transactionId: String,
val merchantName: String,
val merchantAddress: String,
/** Major units (the page's amounts are in cents). */
val amount: Double,
val currency: String,
val state: String,
/** BML Pay (`bml_mpos`) is offered: pay through [fetchQrPayload] and the QR flow. */
val supportsBmlPay: Boolean,
/** Card entry (MPGS via Pomelo) is offered: pay with [BmlMerchantCardPayClient]. */
val supportsCard: Boolean,
/** `pk_production_…` key the page's card form authenticates with. */
val pomeloKey: String?
) {
val isPaid get() = state == "CONFIRMED"
}
/**
* Loads `/<id>/paynow`. The page is server-rendered with everything inline: the transaction,
* the merchant, `availableProviders` (lists `bml_mpos` when BML Pay is enabled — empty for
* card-only merchants) and the card form's `pomeloJsKey` / `pomeloJsProviders`.
*/
fun fetchPayPage(transactionId: String): PayPage {
val request = Request.Builder()
.url("$PAGE_ORIGIN/$transactionId/paynow")
// The page host is behind Cloudflare, which 403s non-browser User-Agents.
.header("User-Agent", BML_WEB_USER_AGENT)
.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
.header("Accept-Language", "en-US,en;q=0.9")
.build()
val html = client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw Exception("Payment page failed (HTTP ${response.code})")
response.body?.string().orEmpty()
}
val start = html.indexOf(APP_DATA_PREFIX).takeIf { it >= 0 }
?.let { it + APP_DATA_PREFIX.length } ?: throw Exception("Payment page has no app data")
val end = html.indexOf("</script>", start).takeIf { it >= 0 } ?: throw Exception("Payment page has no app data")
val data = JSONObject(html.substring(start, end))
val txn = data.optJSONObject("transaction") ?: throw Exception("Payment page has no transaction")
val merchant = data.optJSONObject("merchant")
val providers = data.optJSONArray("availableProviders") ?: JSONArray()
val bmlPay = (0 until providers.length()).any {
val p = providers.optJSONObject(it)
p?.optString("value") == PROVIDER_BML && p.optBoolean("enabled", true)
}
val pomeloProviders = data.optJSONArray("pomeloJsProviders") ?: JSONArray()
val pomeloKey = data.optString("pomeloJsKey").ifBlank { null }
val card = pomeloKey != null && (0 until pomeloProviders.length()).any { pomeloProviders.optString(it) == "mpgs" }
val cents = if (txn.isNull("payAmount")) txn.optLong("amount") else txn.optLong("payAmount")
return PayPage(
transactionId = transactionId,
merchantName = merchant?.optString("tradingName")?.ifBlank { null }
?: merchant?.optString("registeredName").orEmpty(),
merchantAddress = listOfNotNull(
merchant?.optString("address1")?.ifBlank { null },
merchant?.optString("city")?.ifBlank { null }
).joinToString(", "),
amount = cents / 100.0,
currency = txn.optString("payCurrency").ifBlank { txn.optString("currency", "MVR") },
state = txn.optString("state"),
supportsBmlPay = bmlPay,
supportsCard = card,
pomeloKey = pomeloKey
)
}
/**
* Returns the transaction's EMV QR payload (`vendorQrCode`).
*
* A GET on the transaction is 401 without the page's Cognito credentials, but the PATCHes the
* page itself sends need no auth and return the full transaction:
* - on load, `activeBrowserId` (`<id>_<epoch millis>`);
* - on picking "BML" as the payment method, `provider: bml_mpos`.
*
* A fresh link has no provider yet, so `vendorQrCode` is null until the second PATCH selects
* one. Links already opened with BML chosen return it from the first.
*/
fun fetchQrPayload(transactionId: String): String {
val browserId = JSONObject()
.put("activeBrowserId", "${transactionId}_${System.currentTimeMillis()}")
patch(transactionId, browserId).vendorQrCode()?.let { return it }
// Whether the provider PATCH returns the QR itself or it is generated a moment later has
// not been observed, so re-read a few times before giving up. Re-reads use the load PATCH:
// each provider PATCH counts as another payment attempt.
var txn = patch(transactionId, JSONObject().put("provider", PROVIDER_BML))
repeat(3) {
txn.vendorQrCode()?.let { return it }
Thread.sleep(1000)
txn = patch(transactionId, browserId)
}
return txn.vendorQrCode() ?: throw Exception("Transaction has no QR")
}
/**
* The PATCHes the page sends on load: register this "browser" and clear any FX selection.
* Returns the browser id, for [paymentErrors].
*/
fun announceBrowser(transactionId: String): String {
val browserId = "${transactionId}_${System.currentTimeMillis()}"
patch(transactionId, JSONObject().put("activeBrowserId", browserId))
patch(transactionId, JSONObject().put("fx", "reset"))
return browserId
}
/**
* The transaction's failed payment attempts, oldest first, read with the page's load PATCH
* as [browserId]. A declined card (e.g. `INSUFFICIENT_FUNDS`) lands here while the
* transaction stays payable — `state` doesn't change, `hasError` turns true.
*/
fun paymentErrors(transactionId: String, browserId: String): List<PaymentError> {
val history = patch(transactionId, JSONObject().put("activeBrowserId", browserId))
.optJSONArray("paymentErrorHistory") ?: return emptyList()
return (0 until history.length()).mapNotNull { history.optJSONObject(it) }.map {
PaymentError(
code = it.optString("code"),
message = it.optString("customerVisibleDescription").ifBlank { it.optString("reason") }
)
}
}
/** One entry of `paymentErrorHistory`: the gateway's code and the wording BML shows for it. */
data class PaymentError(val code: String, val message: String)
private fun patch(transactionId: String, body: JSONObject): JSONObject {
val request = Request.Builder()
.url("$API_BASE/transactions/$transactionId")
.patch(body.toString().toRequestBody("application/json".toMediaType()))
.header("Accept", "*/*")
.header("Origin", PAGE_ORIGIN)
.header("Referer", "$PAGE_ORIGIN/")
.build()
return client.newCall(request).execute().use { response ->
val text = response.body?.string().orEmpty()
if (!response.isSuccessful || !text.trimStart().startsWith("{"))
throw Exception("Transaction lookup failed (HTTP ${response.code})")
JSONObject(text)
}
}
/**
* No state check: only QR_CODE_GENERATED has been observed, and BML's payrequest lookup
* already rejects a paid or expired QR with its own message. `isNull` first — `optString`
* turns a JSON null into the string "null".
*/
private fun JSONObject.vendorQrCode(): String? =
if (isNull("vendorQrCode")) null else optString("vendorQrCode").ifBlank { null }
companion object {
internal const val API_BASE = "https://api.merchants.bankofmaldives.com.mv"
internal const val PAGE_ORIGIN = "https://transaction.merchants.bankofmaldives.com.mv"
private const val APP_DATA_PREFIX = "window.appData = "
private const val PROVIDER_BML = "bml_mpos"
private val TXN_URL = Regex("^https?://transaction\\.merchants\\.bankofmaldives\\.com\\.mv/([0-9a-fA-F]{24})(?:[/?#].*)?$")
private val TXN_ID = Regex("^[0-9a-fA-F]{24}$")
/** The transaction ID from a bare 24-hex ID or a pasted payment link, else null. */
fun parseTransactionId(input: String): String? {
val s = input.trim()
val id = if (TXN_ID.matches(s)) s else TXN_URL.find(s)?.groupValues?.get(1)
return id?.lowercase()
}
}
}
@@ -66,38 +66,6 @@ data class BmlLoanDetail(
val overdueAmount: Double
)
data class BmlQrPayInfo(
val requestId: String, // base64-encoded full QR URL (trxn_hash)
val merchantName: String, // narrative1
val merchantAddress: String, // narrative2 + narrative3
val amount: Double, // 0.0 for static QR
val currency: String
)
/**
* The pay-request lookup answered `success: false` — [message] is BML's own wording, safe to show
* (e.g. code 103 "The payment request has expired", 112 "Unsupported payment link"). Network and
* parse failures stay plain exceptions so the generic message is used for those instead.
*/
class BmlQrPayLookupException(val code: Int, message: String) : Exception(message)
data class BmlQrPayResult(
val success: Boolean,
val merchant: String = "",
val amount: String = "",
val currency: String = "",
val errorMessage: String = ""
)
data class BmlWalletToken(
val token: String,
val expiry: String,
val appCode: String, // AID hex, e.g. "A0000000031010"
val serviceCode: String,
val data: String,
val validUntil: String // "YYYY-MM-DD HH:mm:ss.SSS"
)
data class BmlForeignLimit(
val type: String,
val used: Double,
@@ -1,95 +0,0 @@
package sh.sar.basedbank.api.bml
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import sh.sar.basedbank.ui.home.AppNotification
import java.text.SimpleDateFormat
import java.util.Locale
private const val BML_NOTIF_BASE = "https://app.bankofmaldives.com.mv"
class BmlNotificationsClient {
private val client = newBmlApiClient()
private val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US)
data class FetchResult(
val items: List<AppNotification>,
val total: Int
)
fun fetchNotifications(
session: BmlSession,
loginId: String,
group: String = "ALL",
page: Int = 1
): FetchResult {
val url = "$BML_NOTIF_BASE/api/v2/notifications?group=$group&page=$page"
return try {
val resp = client.newCall(bmlApiRequest(session, url)).execute()
if (!resp.isSuccessful) { resp.close(); return FetchResult(emptyList(), 0) }
val body = resp.body?.string().also { resp.close() } ?: return FetchResult(emptyList(), 0)
parseResponse(body, loginId)
} catch (_: Exception) { FetchResult(emptyList(), 0) }
}
fun markAllRead(session: BmlSession): Boolean {
val url = "$BML_NOTIF_BASE/api/v2/notifications/read"
val reqBody = """{"all":true}""".toRequestBody("application/json".toMediaType())
val req = Request.Builder().url(url)
.header("Authorization", "Bearer ${session.accessToken}")
.header("User-Agent", BML_USER_AGENT)
.header("x-app-version", BML_APP_VERSION)
.header("accept", "application/json")
.put(reqBody)
.build()
return try {
val resp = client.newCall(req).execute()
val ok = resp.isSuccessful
resp.close()
ok
} catch (_: Exception) { false }
}
private fun parseResponse(body: String, loginId: String): FetchResult {
val json = JSONObject(body)
if (!json.optBoolean("success")) return FetchResult(emptyList(), 0)
val total = json.optInt("total", 0)
val payload = json.optJSONArray("payload") ?: return FetchResult(emptyList(), total)
val items = (0 until payload.length()).map { i ->
val obj = payload.getJSONObject(i)
val dataObj = obj.optJSONObject("data")
val detailFields = mutableListOf<Pair<String, String>>()
detailFields.add("Bank" to "BML")
detailFields.add("Group" to obj.optString("group"))
detailFields.add("Type" to obj.optString("type"))
if (dataObj != null) {
dataObj.keys().forEach { key ->
val v = dataObj.opt(key)?.toString()?.takeIf { it.isNotBlank() } ?: return@forEach
detailFields.add(formatKey(key) to v)
}
}
val createdAt = obj.optString("created_at")
val tsMs = try { sdf.parse(createdAt)?.time ?: System.currentTimeMillis() }
catch (_: Exception) { System.currentTimeMillis() }
AppNotification(
id = obj.optString("id"),
bank = "BML",
loginId = loginId,
group = obj.optString("group", "ALERTS"),
title = obj.optString("title"),
message = obj.optString("message"),
timestampMs = tsMs,
isRead = obj.optBoolean("is_read", true),
detailFields = detailFields
)
}
return FetchResult(items, total)
}
private fun formatKey(key: String): String =
key.replace('_', ' ').split(' ').joinToString(" ") { it.replaceFirstChar(Char::uppercase) }
}
@@ -1,164 +0,0 @@
package sh.sar.basedbank.api.bml
import android.util.Base64
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
class BmlQrPayClient {
private val client = newBmlApiClient()
/**
* Resolves a BML QR to merchant details. [payTarget] is the QR URL, or for POS QRs the bare
* `35` → `20` → `01` reference.
*
* The key is Base64-encoded here without padding, as BML's own app sends it. The padded form
* resolves too, so this is parity rather than a requirement.
*/
fun lookupPayRequest(session: BmlSession, payTarget: String): BmlQrPayInfo {
val key = Base64.encodeToString(
payTarget.toByteArray(Charsets.UTF_8), Base64.NO_WRAP or Base64.NO_PADDING)
val request = bmlApiRequest(session,
"$BML_BASE_URL/api/mobile/walletpayments/payrequest/$key")
return client.newCall(request).execute().use { response ->
val body = response.body?.string() ?: throw Exception("No response")
// A server-side error renders an HTML page under HTTP 200 rather than an error JSON.
if (!body.trimStart().startsWith("{"))
throw Exception("Unexpected non-JSON response (HTTP ${response.code})")
val json = JSONObject(body)
if (!json.optBoolean("success"))
throw BmlQrPayLookupException(
json.optInt("code"),
json.optString("message").ifBlank { "Lookup failed" })
val payload = json.getJSONObject("payload")
val addr2 = payload.optString("narrative2").trim()
val addr3 = payload.optString("narrative3").trim()
val address = listOf(addr2, addr3).filter { it.isNotBlank() }.joinToString(", ")
BmlQrPayInfo(
requestId = payload.optString("trxn_hash"),
merchantName = payload.optString("narrative1").trim(),
merchantAddress = address,
amount = payload.optString("amount").toDoubleOrNull() ?: 0.0,
currency = payload.optString("currency").ifBlank { "MVR" }
)
}
}
/**
* Pre-initiate step required for gateway QR (pay.bml.com.mv).
* POST without channel — expects code 99 (OTP channel selection required).
*/
fun preInitiatePayment(
session: BmlSession,
debitAccount: String,
requestId: String,
amount: Double,
currency: String
): Boolean {
val jo = JSONObject().apply {
put("action", "approve")
put("debitAccount", debitAccount)
put("requestId", requestId)
put("amount", amount)
put("currency", currency)
}
val request = Request.Builder()
.url("$BML_BASE_URL/api/mobile/walletpayments/pay")
.post(jo.toString().toRequestBody("application/json".toMediaType()))
.header("Authorization", "Bearer ${session.accessToken}")
.header("User-Agent", BML_USER_AGENT)
.header("x-app-version", BML_APP_VERSION)
.header("accept", "application/json")
.build()
return client.newCall(request).execute().use { response ->
val body = response.body?.string() ?: return@use false
val json = try { JSONObject(body) } catch (_: Exception) { return@use false }
json.optBoolean("success") && json.optInt("code") == 99
}
}
/**
* Step 1 — initiate: POST with channel but no OTP.
* Returns true when server responds with code 22 (OTP generated).
*/
fun initiatePayment(
session: BmlSession,
debitAccount: String,
requestId: String,
amount: Double,
currency: String
): Boolean {
val jo = JSONObject().apply {
put("action", "approve")
put("debitAccount", debitAccount)
put("requestId", requestId)
put("amount", amount)
put("currency", currency)
put("channel", "token")
}
val request = Request.Builder()
.url("$BML_BASE_URL/api/mobile/walletpayments/pay")
.post(jo.toString().toRequestBody("application/json".toMediaType()))
.header("Authorization", "Bearer ${session.accessToken}")
.header("User-Agent", BML_USER_AGENT)
.header("x-app-version", BML_APP_VERSION)
.header("accept", "application/json")
.build()
return client.newCall(request).execute().use { response ->
val body = response.body?.string() ?: return@use false
val json = try { JSONObject(body) } catch (_: Exception) { return@use false }
json.optBoolean("success") && json.optInt("code") == 22
}
}
/**
* Step 2 — confirm: POST with channel + OTP.
* Returns [BmlQrPayResult] with success/error.
*/
fun confirmPayment(
session: BmlSession,
debitAccount: String,
requestId: String,
amount: Double,
currency: String,
otp: String
): BmlQrPayResult {
val jo = JSONObject().apply {
put("action", "approve")
put("debitAccount", debitAccount)
put("requestId", requestId)
put("amount", amount)
put("currency", currency)
put("channel", "token")
put("otp", otp)
}
val request = Request.Builder()
.url("$BML_BASE_URL/api/mobile/walletpayments/pay")
.post(jo.toString().toRequestBody("application/json".toMediaType()))
.header("Authorization", "Bearer ${session.accessToken}")
.header("User-Agent", BML_USER_AGENT)
.header("x-app-version", BML_APP_VERSION)
.header("accept", "application/json")
.build()
return client.newCall(request).execute().use { response ->
val body = response.body?.string()
?: return@use BmlQrPayResult(false, errorMessage = "No response")
val json = try { JSONObject(body) } catch (_: Exception) {
return@use BmlQrPayResult(false, errorMessage = "Parse error")
}
if (!json.optBoolean("success")) {
BmlQrPayResult(false, errorMessage = json.optString("message").ifBlank { "Payment failed" })
} else {
val payload = json.optJSONObject("payload")
BmlQrPayResult(
success = true,
merchant = payload?.optString("merchant") ?: "",
amount = payload?.optString("amount") ?: "",
currency = payload?.optString("currency") ?: currency
)
}
}
}
}
@@ -1,79 +0,0 @@
package sh.sar.basedbank.api.bml
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONArray
import org.json.JSONObject
class BmlTapToPayClient {
private val client = newBmlApiClient()
/**
* Fetches up to [quantity] single-use payment tokens for [cardId].
* [otp] is a TOTP code generated from the stored BML OTP seed.
*
* Flow:
* 1. POST → code 99 (OTP required) or 0 (direct, unlikely)
* 2. POST with channel=token → code 22 (OTP generated on BML side, but we use TOTP)
* 3. POST with otp=TOTP → code 0, payload = token list
*/
fun fetchTokens(
session: BmlSession,
cardId: String,
otp: String,
quantity: Int = 3
): List<BmlWalletToken> {
val url = "$BML_BASE_URL/api/mobile/walletpayments/gettoken"
// Step 1: initiate
val base = JSONObject().apply {
put("type", "track2")
put("cardid", cardId)
put("quantity", quantity)
}
val step1 = post(session, url, base)
if (step1.optInt("code") == 0) return parseTokens(step1.optJSONArray("payload"))
if (step1.optInt("code") != 99) throw Exception(step1.optString("message", "Token request failed"))
// Step 2: request OTP channel (triggers BML to validate we can use TOTP)
val body2 = JSONObject(base.toString()).apply { put("channel", "token") }
val step2 = post(session, url, body2)
if (step2.optInt("code") != 22) throw Exception(step2.optString("message", "OTP channel request failed"))
// Step 3: submit TOTP
val body3 = JSONObject(body2.toString()).apply { put("otp", otp) }
val step3 = post(session, url, body3)
if (step3.optInt("code") != 0) throw Exception(step3.optString("message", "Token fetch failed"))
return parseTokens(step3.optJSONArray("payload"))
}
private fun post(session: BmlSession, url: String, body: JSONObject): JSONObject {
val req = okhttp3.Request.Builder()
.url(url)
.post(body.toString().toRequestBody("application/json".toMediaType()))
.header("Authorization", "Bearer ${session.accessToken}")
.header("User-Agent", BML_USER_AGENT)
.header("x-app-version", BML_APP_VERSION)
.build()
return client.newCall(req).execute().use { resp ->
JSONObject(resp.body?.string() ?: throw Exception("Empty response"))
}
}
private fun parseTokens(arr: JSONArray?): List<BmlWalletToken> {
arr ?: return emptyList()
return (0 until arr.length()).map { i ->
val o = arr.getJSONObject(i)
BmlWalletToken(
token = o.getString("token"),
expiry = o.getString("expiry"),
appCode = o.getString("app_code"),
serviceCode = o.getString("service_code"),
data = o.optString("data", ""),
validUntil = o.optString("valid_until", "")
)
}
}
}
@@ -84,8 +84,7 @@ class BmlTransferClient {
try {
val json = JSONObject(bodyStr)
if (!json.optBoolean("success")) {
val payloadStr = json.optString("payload").takeIf { it.isNotBlank() && it != "null" }
BmlTransferResult(false, errorMessage = payloadStr ?: json.optString("message").ifBlank { "Transfer failed" })
BmlTransferResult(false, errorMessage = json.optString("message").ifBlank { "Transfer failed" })
} else {
val payload = json.optJSONObject("payload")
BmlTransferResult(
@@ -71,8 +71,7 @@ class BmlValidateClient {
originalInput = account,
name = root.optString("name"),
alias = null,
// BML's MIB verify endpoint doesn't return the MIB account's currency.
currency = "",
currency = "MVR",
agnt = root.optString("agnt").takeIf { it.isNotBlank() }
)
} catch (_: Exception) { null }
@@ -1,210 +0,0 @@
package sh.sar.basedbank.api.dhiraagu
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONArray
import org.json.JSONObject
import sh.sar.basedbank.api.models.BankServerException
import java.math.BigDecimal
import java.math.RoundingMode
import java.util.Locale
import java.util.concurrent.TimeUnit
/**
* Dhiraagu prepaid reload ("Easy TopUp") and bill payment ("Easy Pay") through dhiraagu.com.mv,
* paid by card on BML's merchant gateway. Dhiraagu only builds the order; the money moves on the
* BML Merchant Services transaction handed back, which is paid like any card-only BML merchant
* link. See `docs/dhiraaguapi/02-reload.md` and `docs/dhiraaguapi/03-bill-pay.md`.
*
* Every call blocks, so run it on an IO thread.
*/
class DhiraaguPaymentClient {
private val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
/**
* Creates the reload order for [number] and the BML transaction paying for it: cart →
* merchant (the BML gateway entry) → payment → BML transaction. [amount] is the whole MVR
* amount paid, GST included. Returns the 24-hex BML transaction id. Throws with Dhiraagu's
* wording when a step is refused.
*/
fun createReloadTransaction(number: String, amount: Int): String {
val topupNonce = pageNonce("$BASE/services/easy-topup")
val gst = gstOf(amount)
val cart = api("cart", "recharge", topupNonce, JSONObject()
.put("formId", FORM_RELOAD)
.put("serviceNumber", number)
.put("amount", amount)
.put("amountGST", gst.toDouble())
.put("amountRecharge", (BigDecimal(amount) - gst).toDouble())
.put("gstRate", GST_RATE)
.put("memberId", "").put("memberName", "").put("memberNId", "")
.put("customerId", "").put("customerCode", "")
.put("version", 2))
return payCart(FORM_RELOAD, cart, BigDecimal(amount))
}
/**
* Creates the bill payment order for postpaid [number] and the BML transaction paying for
* it: lookup (for the billing account) → cart → merchant → payment → BML transaction.
* [amount] is MVR, up to 2 decimal places. Returns the 24-hex BML transaction id. Throws
* with Dhiraagu's wording when a step is refused.
*/
fun createBillPayTransaction(number: String, amount: BigDecimal): String {
val easyPayNonce = pageNonce("$BASE/services/easy-pay")
// The cart needs the billing account the number belongs to, which only the lookup gives
val info = call("dhiraaguIO", "infoUnlisted", easyPayNonce, JSONObject().put("number", number))
if (info.optJSONArray("serviceDetails")?.optJSONObject(0)?.optString("prepaidIndicator") == "Y") {
throw Exception("Prepaid number is not allowed.")
}
val accountNumber = info.optString("accountNumber").ifBlank { throw Exception("Invalid account/service number") }
// The page refuses some account statuses and customer types before ordering; so do we
val rules = runCatching { get("setting", "bill", easyPayNonce).getJSONObject("resp").getJSONObject("settingAppJson1") }.getOrNull()
val status = info.optString("accountStatus")
if (rules != null && status in rules.blockedValues("accountStatus")) {
throw Exception("Dhiraagu can't accept payment for this service. Contact Dhiraagu customer service. [Account Status: $status]")
}
val customerType = info.optString("customerType")
if (rules != null && customerType in rules.blockedValues("customerType")) {
throw Exception("The number is not allowed. [Customer Type: $customerType]")
}
val cart = api("cart", "easyPay", easyPayNonce, JSONObject()
.put("formId", FORM_BILL)
.put("serviceNumber", number)
.put("accountNumber", accountNumber)
.put("amount", money(amount))
.put("memberId", "").put("memberName", "").put("memberNId", "")
.put("billRef", "")
.put("billType", if (info.optString("type") == BILL_WRITE_OFF) BILL_WRITE_OFF else BILL_PAYMENT))
return payCart(FORM_BILL, cart, amount)
}
/**
* The payment page's half, shared by every form: picks the BML gateway, creates the payment
* for [cart] and has Dhiraagu create the BML transaction. Returns its 24-hex id.
*/
private fun payCart(formId: Int, cart: JSONObject, amount: BigDecimal): String {
val cartId = cart.optString("cartId").ifBlank { throw Exception("Dhiraagu didn't create the order") }
// The payment page carries its own nonce, used for the rest of the order
val paymentNonce = pageNonce("$BASE/services/payment-v2?cartid=$cartId")
val merchants = apiList("merchant", "form", paymentNonce, JSONObject().put("formId", formId))
val bml = (0 until merchants.length()).map { merchants.getJSONObject(it) }
.firstOrNull { it.optInt("gatewayId") == GATEWAY_BML }
?: throw Exception("Dhiraagu isn't taking BML card payments right now")
val payment = api("payment", "create", paymentNonce, JSONObject()
.put("formId", formId)
.put("cartId", cartId)
.put("gatewayId", GATEWAY_BML)
.put("dhiraaguPayNumber", "")
.put("amount", money(amount))
.put("paymentMerchantId", bml.getString("merchantId"))
.put("memberId", "").put("tokenize", "").put("paymentType", "")
.put("recurringFrequency", "").put("bmlTokenId", ""))
val paymentId = payment.optString("paymentId").ifBlank { throw Exception("Dhiraagu didn't create the payment") }
val txn = api("bml", "createV2", paymentNonce, JSONObject().put("paymentId", paymentId))
return TXN_URL.find(txn.optString("url"))?.groupValues?.get(1)
?: throw Exception("BML didn't create the transaction")
}
private fun money(amount: BigDecimal) =
String.format(Locale.US, "%.2f", amount.setScale(2, RoundingMode.HALF_UP))
/** The `val` list of a `setting` rule, e.g. `{"accountStatus":{"val":["F"]}}`. */
private fun JSONObject.blockedValues(rule: String): Set<String> {
val vals = optJSONObject(rule)?.optJSONArray("val") ?: return emptySet()
return (0 until vals.length()).map { vals.optString(it) }.toSet()
}
// ── HTTP ─────────────────────────────────────────────────────────────────
/** Every page embeds a `var nonce = "…"` that its API calls send as the `nonce` header. */
private fun pageNonce(url: String): String =
NONCE.find(page(url))?.groupValues?.get(1) ?: throw Exception("Dhiraagu page didn't load")
private fun page(url: String): String = client.newCall(
Request.Builder().url(url)
.header("User-Agent", UA)
.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
.build()
).execute().use { r ->
if (r.code in 500..599) throw BankServerException("Dhiraagu")
r.body?.string().orEmpty()
}
private fun api(sub: String, act: String, nonce: String, body: JSONObject): JSONObject =
call(sub, act, nonce, body).getJSONObject("resp")
private fun apiList(sub: String, act: String, nonce: String, body: JSONObject): JSONArray =
call(sub, act, nonce, body).getJSONArray("resp")
/** POSTs to `sdk-dhr-webapi.ashx`; throws unless `respStatus` is OK. */
private fun call(sub: String, act: String, nonce: String, body: JSONObject): JSONObject =
send(sub, act, nonce, body.toString().toRequestBody(JSON))
/** GETs from `sdk-dhr-webapi.ashx` (the settings calls); throws unless `respStatus` is OK. */
private fun get(sub: String, act: String, nonce: String): JSONObject = send(sub, act, nonce, null)
private fun send(sub: String, act: String, nonce: String, body: okhttp3.RequestBody?): JSONObject {
val text = client.newCall(
Request.Builder().url("$API?website_id=$WEBSITE_ID&sub=$sub&act=$act")
.apply { if (body != null) post(body) }
.header("User-Agent", UA)
.header("Accept", "application/json, text/javascript, */*; q=0.01")
.header("X-Requested-With", "XMLHttpRequest")
.header("Origin", BASE)
.header("nonce", nonce)
.build()
).execute().use { r ->
if (r.code in 500..599) throw BankServerException("Dhiraagu")
r.body?.string().orEmpty()
}
val obj = try { JSONObject(text) } catch (_: Exception) {
throw Exception("Unexpected response from Dhiraagu")
}
if (obj.optString("respStatus") != "OK") {
throw Exception(obj.optString("respMsg").ifBlank { obj.optString("resp") }.ifBlank { "Dhiraagu refused the payment" })
}
return obj
}
companion object {
private const val BASE = "https://www.dhiraagu.com.mv"
private const val API = "$BASE/api/sdk-dhr-webapi.ashx"
private const val WEBSITE_ID = "CA2BB809-3A22-485B-A518-DA6B6DE653A5"
private const val UA = "Mozilla/5.0 (X11; Linux x86_64; rv:150.0) Gecko/20100101 Firefox/150.0"
private val JSON = "application/json".toMediaType()
private val NONCE = Regex("""var nonce = "([^"]+)"""")
private val TXN_URL = Regex("""transaction\.merchants\.bankofmaldives\.com\.mv/([0-9a-fA-F]{24})""")
/** Easy Pay's (bill payment) form id across cart / merchant / payment. */
private const val FORM_BILL = 1
/** Easy TopUp's form id across cart / merchant / payment. */
private const val FORM_RELOAD = 2
/** Bank of Maldives in `merchant&act=form` (1 = BML, 2 = MIB, 3 = DhiraaguPay). */
private const val GATEWAY_BML = 1
private const val GST_RATE = 0.08
/** Easy Pay's `billType`s; the lookup's `type` says which applies. */
private const val BILL_PAYMENT = "BillPayment"
private const val BILL_WRITE_OFF = "writeOffPayments"
/**
* The GST inside a GST-inclusive reload [amount], as the page works it out:
* `amount × rate / (1 + rate)`, to 2 places. The number is credited `amount − gst`.
*/
fun gstOf(amount: Int): BigDecimal {
val rate = BigDecimal(GST_RATE.toString())
return (BigDecimal(amount) * rate).divide(BigDecimal.ONE + rate, 2, RoundingMode.HALF_UP)
}
}
}
@@ -1,47 +0,0 @@
package sh.sar.basedbank.api.fahipay
import android.os.Build
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okio.Buffer
/** Form-body helpers shared by the Fahipay POST endpoints (login, OTP, payments). */
internal object FahipayForm {
/** The `device[...]` fields every Fahipay POST carries. */
fun deviceParts(deviceUuid: String): Array<Pair<String, String>> = arrayOf(
"device[available]" to "true",
"device[platform]" to "Android",
"device[uuid]" to deviceUuid,
"device[model]" to Build.MODEL,
"device[manufacturer]" to Build.MANUFACTURER,
"device[isVirtual]" to "false",
"device[serial]" to "unknown"
)
/**
* Builds a multipart/form-data body with lowercase "content-disposition" headers,
* which is what the Fahipay server requires.
*/
fun body(vararg parts: Pair<String, String>): RequestBody {
val boundary = java.util.UUID.randomUUID().toString()
val buf = Buffer()
for ((name, value) in parts) {
val valueBytes = value.toByteArray(Charsets.UTF_8)
buf.writeUtf8("--$boundary\r\n")
buf.writeUtf8("content-disposition: form-data; name=\"$name\"\r\n")
buf.writeUtf8("Content-Length: ${valueBytes.size}\r\n")
buf.writeUtf8("\r\n")
buf.write(valueBytes)
buf.writeUtf8("\r\n")
}
buf.writeUtf8("--$boundary--\r\n")
val snapshot = buf.readByteString()
val mediaType = "multipart/form-data; boundary=$boundary".toMediaType()
return object : RequestBody() {
override fun contentType() = mediaType
override fun contentLength() = snapshot.size.toLong()
override fun writeTo(sink: okio.BufferedSink) { sink.write(snapshot) }
}
}
}
@@ -3,7 +3,6 @@ package sh.sar.basedbank.api.fahipay
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import sh.sar.basedbank.api.models.BankServerException
import sh.sar.basedbank.api.models.BankTransaction
import java.util.concurrent.TimeUnit
@@ -33,10 +32,8 @@ class FahipayHistoryClient {
.header("User-Agent", UA)
.build()
).execute()
val code = resp.code
val json = resp.body?.string() ?: return Pair(emptyList(), 0)
resp.close()
if (code in 500..599) throw BankServerException("Fahipay")
return try {
val obj = JSONObject(json)
val total = obj.optInt("total", 0)
@@ -4,8 +4,11 @@ import android.os.Build
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okio.Buffer
import org.json.JSONObject
import java.security.SecureRandom
import java.util.concurrent.TimeUnit
@@ -71,14 +74,14 @@ class FahipayLoginFlow {
*/
fun login(idCard: String, password: String, deviceUuid: String): FahipayLoginStep {
initSession()
val body = FahipayForm.body(
val body = buildFormBody(
"email" to idCard,
"password" to password,
"grant_type" to "auth_id",
"lang" to "en",
"version" to "2.0.0",
"platform" to "thijooree",
*FahipayForm.deviceParts(deviceUuid)
"platform" to "BasedBank",
*deviceParts(deviceUuid)
)
val resp = client.newCall(
@@ -106,15 +109,15 @@ class FahipayLoginFlow {
* Returns authId.
*/
fun verifyTotp(code: String, deviceUuid: String): String {
val body = FahipayForm.body(
val body = buildFormBody(
"code" to code,
"channel" to "totp",
"action" to "login",
"grant_type" to "auth_id",
"lang" to "en",
"version" to "2.0.0",
"platform" to "thijooree",
*FahipayForm.deviceParts(deviceUuid)
"platform" to "BasedBank",
*deviceParts(deviceUuid)
)
val resp = client.newCall(
@@ -135,6 +138,42 @@ class FahipayLoginFlow {
?: throw Exception("No authID in OTP response")
}
private fun deviceParts(deviceUuid: String): Array<Pair<String, String>> = arrayOf(
"device[available]" to "true",
"device[platform]" to "Android",
"device[uuid]" to deviceUuid,
"device[model]" to Build.MODEL,
"device[manufacturer]" to Build.MANUFACTURER,
"device[isVirtual]" to "false",
"device[serial]" to "unknown"
)
/**
* Builds a multipart/form-data body with lowercase "content-disposition" headers,
* which is what the Fahipay server requires.
*/
private fun buildFormBody(vararg parts: Pair<String, String>): RequestBody {
val boundary = java.util.UUID.randomUUID().toString()
val buf = Buffer()
for ((name, value) in parts) {
val valueBytes = value.toByteArray(Charsets.UTF_8)
buf.writeUtf8("--$boundary\r\n")
buf.writeUtf8("content-disposition: form-data; name=\"$name\"\r\n")
buf.writeUtf8("Content-Length: ${valueBytes.size}\r\n")
buf.writeUtf8("\r\n")
buf.write(valueBytes)
buf.writeUtf8("\r\n")
}
buf.writeUtf8("--$boundary--\r\n")
val snapshot = buf.readByteString()
val mediaType = "multipart/form-data; boundary=$boundary".toMediaType()
return object : RequestBody() {
override fun contentType() = mediaType
override fun contentLength() = snapshot.size.toLong()
override fun writeTo(sink: okio.BufferedSink) { sink.write(snapshot) }
}
}
companion object {
fun generateDeviceUuid(): String {
val bytes = ByteArray(8)
@@ -1,71 +0,0 @@
package sh.sar.basedbank.api.fahipay
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import sh.sar.basedbank.api.models.BankServerException
import java.util.concurrent.TimeUnit
/**
* Pays a phone number from the Fahipay wallet: Ooredoo Raastas, Ooredoo bill pay, Dhiraagu
* reload and Dhiraagu bill pay. All four are the same POST, only the path differs — see
* `docs/fahipayapi/09-payments.md`.
*/
class FahipayPaymentClient {
private val BASE_URL = "https://fahipay.mv"
private val UA = "okhttp/4.12.0"
private val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build()
/**
* A payment the server accepted. [message] is its wording, e.g. "Transaction successful." or,
* for Dhiraagu bill pay, "Transaction will be processed shortly.". [transactionId] (`tid`) is
* only returned by the reload / Raastas endpoints.
*/
data class Result(val message: String, val transactionId: String?)
/**
* POSTs the payment to [path] (e.g. `actions/payment/ooredoo/recharge/`). [amount] is sent as
* typed — the caller checks the service's limits first. Returns on success; throws with the
* server's message when it refuses, [BankServerException] on a 5xx, and IOException when the
* request doesn't get through. Blocking — call from IO.
*/
fun pay(session: FahipaySession, path: String, number: String, amount: String, deviceUuid: String): Result {
val body = FahipayForm.body(
"number" to number,
"amount" to amount,
"lang" to "en",
"version" to "2.0.2",
"build" to "329",
"platform" to "thijooree",
*FahipayForm.deviceParts(deviceUuid)
)
val resp = client.newCall(
Request.Builder().url("$BASE_URL/$path")
.post(body)
.header("authid", session.authId)
.header("Cookie", "__Secure-sess=${session.sessionCookie}")
.header("User-Agent", UA)
.header("accept", "application/json")
.build()
).execute()
val code = resp.code
val json = resp.body?.string().orEmpty()
resp.close()
if (code in 500..599) throw BankServerException("Fahipay")
val obj = try { JSONObject(json) } catch (_: Exception) {
throw Exception("Unexpected response from Fahipay (HTTP $code)")
}
val message = obj.optString("msg").ifBlank { obj.optString("title") }
if (obj.optString("type") != "success") throw Exception(message.ifBlank { "Payment failed" })
return Result(
message = message,
transactionId = obj.optString("tid").takeIf { it.isNotBlank() }
)
}
}
@@ -1,35 +0,0 @@
package sh.sar.basedbank.api.mfaisa
import sh.sar.basedbank.api.models.BankAccount
object MfaisaAccountClient {
/**
* Build one BankAccount per pocket from a login result.
* `loginTag` is "mfaisa_<msisdn>" (one per M-Faisa account on the device).
*/
fun buildAccounts(result: MfaisaLoginResult, loginTag: String): List<BankAccount> {
val displayName = result.profile.name.ifBlank { "M-Faisa" }
return result.pockets.map { p ->
val balance = "%.2f".format(p.balance)
BankAccount(
bank = "MFAISA",
profileName = displayName,
profileType = if (p.pocketValueType == "PAYPAL_USD") "MFAISA_PAYPAL" else "MFAISA",
accountNumber = p.pocketId,
accountBriefName = p.nickname.ifBlank { p.displayName.ifBlank { "M-Faisa" } },
currencyName = p.currency,
accountTypeName = p.displayName.ifBlank { "Mobile Wallet" },
availableBalance = balance,
currentBalance = balance,
blockedAmount = "0.00",
mvrBalance = if (p.currency == "MVR") balance else "0.00",
statusDesc = p.statusType.ifBlank { "ACTIVE" },
profileImageHash = null,
loginTag = loginTag,
profileId = result.profile.subscriberId,
internalId = result.profile.walletId
)
}
}
}
@@ -1,67 +0,0 @@
package sh.sar.basedbank.api.mfaisa
import android.util.Base64
import java.math.BigInteger
import java.security.KeyFactory
import java.security.PublicKey
import java.security.SecureRandom
import java.security.spec.MGF1ParameterSpec
import java.security.spec.RSAPublicKeySpec
import javax.crypto.Cipher
import javax.crypto.spec.OAEPParameterSpec
import javax.crypto.spec.PSource
/**
* Field-level encryption for Ooredoo M-Faisa request payloads.
*
* Both keys live (obfuscated) in libnative-lib.so and were extracted by hooking
* the live app with Frida.
*/
object MfaisaCrypto {
// 1024-bit RSA key. Used for mdnId / mobileNumber / userName.
// Plaintext is "960" + msisdn. Cipher is OAEP/SHA-256.
private val MOBILE_N = BigInteger(
"125043708524451715642963973698406708755269502293565460606118930542682275971580032704131362488150174351194407172452175275612284031366512484449720820404229217064541745811143629538982383390723079478499614160620616911679256603296752844216620113064874342531851472851319065258962732556596958868200227678294957694889"
)
private val MOBILE_E = BigInteger("65537")
// 2048-bit RSA key. Used for mPin. Plaintext is `pin + <6-char alphanumeric salt>`.
// Cipher is OAEP/SHA-1. Output is hex.
private val PIN_N = BigInteger(
"30853988905151679601945771998041800603731623930944610745590884250489036547584511246061683594739124713335100655247634233703624305850983479131604065498722268916133039937128796419041248167624160300158401049118446352988895953596475734156239882174799821436218294725935232359347780127398770443981734096915599443841496235741614376221345134752344583283770986295156829944214841171989893291834036934949311011654192369326666754259268756426483563391867503815261490458479377640385950664660570354934951526319509191336410208609648686869010157285218492218371799827560010164293202383337546810220755107741865769246084291990864545504123"
)
private val PIN_E = BigInteger("65537")
private val mobileKey: PublicKey by lazy { rsaPublicKey(MOBILE_N, MOBILE_E) }
private val pinKey: PublicKey by lazy { rsaPublicKey(PIN_N, PIN_E) }
private val random = SecureRandom()
private const val SALT_ALPHABET =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
/** Encrypts "960" + MSISDN. Output is non-deterministic (OAEP random padding). */
fun encryptMobile(msisdn: String): String {
val cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding")
val params = OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT)
cipher.init(Cipher.ENCRYPT_MODE, mobileKey, params)
val ct = cipher.doFinal(("960" + msisdn).toByteArray(Charsets.UTF_8))
return Base64.encodeToString(ct, Base64.NO_WRAP)
}
/** Encrypts `pin + <6-char random alphanumeric salt>`. Output is hex (lowercase). */
fun encryptPin(pin: String): String {
val salt = buildString {
repeat(6) { append(SALT_ALPHABET[random.nextInt(SALT_ALPHABET.length)]) }
}
val plaintext = (pin + salt).toByteArray(Charsets.UTF_8)
val cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding")
val params = OAEPParameterSpec("SHA-1", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT)
cipher.init(Cipher.ENCRYPT_MODE, pinKey, params)
val ct = cipher.doFinal(plaintext)
return ct.joinToString("") { "%02x".format(it) }
}
private fun rsaPublicKey(n: BigInteger, e: BigInteger): PublicKey =
KeyFactory.getInstance("RSA").generatePublic(RSAPublicKeySpec(n, e))
}
@@ -1,181 +0,0 @@
package sh.sar.basedbank.api.mfaisa
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import org.json.JSONObject
import sh.sar.basedbank.api.models.BankServerException
import sh.sar.basedbank.api.models.BankTransaction
import java.security.SecureRandom
import java.util.concurrent.TimeUnit
import java.util.zip.Adler32
/**
* Fetches the M-Faisa transaction summary for the active subscriber session.
*
* Endpoint: POST /transactionInquiry/fetchSummary
*
* Two extra anti-replay fields are required:
* - rndValue : RSA-OAEP-SHA1 encryption of a fresh timestamp+salt with the mPin key
* (i.e. the same routine as [MfaisaCrypto.encryptPin] applied to a timestamp)
* - csValue : Adler32(formDataJson + timestampPlaintext), as a decimal string
*/
class MfaisaHistoryClient {
private val baseUrl = "https://superapp.ooredoo.mv/api/mfaisaa-bff/mfino/v1.1/web"
private val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
private val random = SecureRandom()
/**
* Fetches one page (`pageNo` is 1-based; recordSize defaults to 70 — the official app's value).
* Returns the parsed transactions and a flag indicating whether the server returned a full
* page (= more pages may be available).
*/
data class Page(val transactions: List<BankTransaction>, val hasMore: Boolean)
fun fetchHistory(
session: MfaisaSession,
accountNumber: String,
accountDisplayName: String,
pageNo: Int,
recordSize: Int = 70
): Page {
if (session.loginExchangeKey.isBlank() || session.subscriberId.isBlank() || session.msisdn.isBlank()) {
throw IllegalStateException("M-Faisa session is missing fields required for fetchSummary")
}
val innerMdn = MfaisaCrypto.encryptMobile(session.msisdn)
val outerMdn = MfaisaCrypto.encryptMobile(session.msisdn) // independent encryption
val formData = JSONObject()
.put("actorRole", "RETAIL_SUBSCRIBER")
.put("actorRoleId", session.subscriberId)
.put("fromDate", "")
.put("mdnId", innerMdn)
.put("pageNo", pageNo.toString())
.put("recordSize", recordSize.toString())
.put("toDate", "")
.put("transactionType", "")
val formJson = formData.toString().matchGsonHtmlSafe()
// Anti-replay: nonce_str = (currentTimeMillis() + offset). Offset is small noise (0..5).
val offset = (random.nextInt(5) + 10) xor 0xE
val nonceStr = (System.currentTimeMillis() + offset).toString()
// rndValue uses the same key/cipher as the mPin encryption — see [MfaisaCrypto.encryptPin].
val rndValue = MfaisaCrypto.encryptPin(nonceStr)
val csValue = Adler32().apply { update((formJson + nonceStr).toByteArray(Charsets.UTF_8)) }
.value.toString()
val body = FormBody.Builder()
.add("role", "RETAIL_SUBSCRIBER")
.add("channel", "SubscriberApp")
.add("rndValue", rndValue)
.add("loginExchangeKey", session.loginExchangeKey)
.add("formData", formJson)
.add("mdnId", outerMdn)
.add("csValue", csValue)
.build()
val resp = client.newCall(
Request.Builder().url("$baseUrl/transactionInquiry/fetchSummary").post(body).build()
).execute()
val code = resp.code
val raw = resp.body?.string() ?: throw Exception("Empty history response")
resp.close()
if (code in 500..599) throw BankServerException("Ooredoo M-Faisa")
// The server returns its error envelope as a JSON array even on HTTP 200.
val trimmed = raw.trimStart()
if (trimmed.startsWith("[")) {
val errArr = JSONArray(trimmed)
val first = errArr.optJSONObject(0)
val errObj = first?.optJSONArray("error")?.optJSONObject(0)
val attrVal = errObj?.optString("attributeValue")
val errCode = errObj?.optString("errorCode")
if (attrVal == "SESSION_EXPIRED" || errCode == "SESSION_EXPIRED") {
throw MfaisaSessionExpiredException()
}
val msg = errObj?.optString("errorMessage") ?: first?.optString("message")
throw Exception(msg?.ifBlank { null } ?: "M-Faisa history failed")
}
val obj = JSONObject(trimmed)
val arr = obj.optJSONArray("transactionInquiryDTOList") ?: JSONArray()
val out = mutableListOf<BankTransaction>()
for (i in 0 until arr.length()) {
val o = arr.getJSONObject(i) ?: continue
out += parse(o, accountNumber, accountDisplayName)
}
// The server returns nothing useful for "total"; assume more pages exist when this page is full.
return Page(out, hasMore = arr.length() >= recordSize)
}
private fun parse(o: JSONObject, accountNumber: String, accountDisplayName: String): BankTransaction {
val trnDate = o.optString("trnDate") // "yyyy-MM-dd HH:mm:ss" — already in target format
val trnType = o.optString("trnType") // CASH_IN | PURCHASE | TRANSFER | …
val status = o.optString("status") // SUCCESS | FAILED
val amtObj = o.optJSONObject("transactionAmount") ?: JSONObject()
val amount = amtObj.optDouble("amount", 0.0)
val currency = amtObj.optString("currencyCode", "MVR")
val refId = o.optString("referenceId").ifBlank { o.optString("requestId") }
val narration = o.optString("narrationString").ifBlank { trnType.replace("_", " ").lowercase().replaceFirstChar { it.uppercase() } }
// Direction: CASH_IN / TRANSFER_IN etc. are credits, everything else is a debit
val isCredit = trnType.endsWith("_IN") ||
trnType == "CASH_IN" ||
trnType == "RECEIVE_MONEY"
val signedAmount = if (isCredit) amount else -amount
// Counterparty hint: parse the typeSummaryString for richer info if present
val counterparty = extractCounterparty(o)
// Failed transactions still appear in the list — we still show them but tag in the description.
val description = if (status == "FAILED") "$narration · Failed" else narration
return BankTransaction(
id = refId,
date = trnDate,
description = description,
amount = signedAmount,
currency = currency,
counterpartyName = counterparty,
reference = refId.ifBlank { null },
accountNumber = accountNumber,
accountDisplayName = accountDisplayName,
source = "MFAISA"
)
}
/** Best-effort counterparty / merchant name extraction from the response's nested JSON. */
private fun extractCounterparty(o: JSONObject): String? {
// typeSummaryString is itself a JSON-encoded array string
val ts = o.optString("typeSummaryString").trim()
if (ts.startsWith("[")) {
try {
val arr = JSONArray(ts)
for (i in 0 until arr.length()) {
val item = arr.optJSONObject(i) ?: continue
item.optString("Merchant Name").takeIf { it.isNotBlank() }?.let { return it }
item.optString("Receiver Name").takeIf { it.isNotBlank() }?.let { return it }
item.optString("Sender Name").takeIf { it.isNotBlank() }?.let { return it }
}
} catch (_: Exception) { /* fall through */ }
}
// sourceMDN like "Shiham-DT Pocket-9609198026" — the bit before the first dash is the user-facing name
val source = o.optString("sourceMDN")
if (source.isNotBlank() && source.contains("-")) return source.substringBefore("-")
return null
}
/**
* Match the official app's Gson serialiser: replace `=` with the Unicode-escaped equivalent so
* the M-Faisa server's strict parser accepts the payload (same trick as in [MfaisaLoginFlow]).
*/
private fun String.matchGsonHtmlSafe(): String =
replace("\\/", "/").replace("=", "\\u003d")
}
@@ -1,202 +0,0 @@
package sh.sar.basedbank.api.mfaisa
import android.content.Context
import android.os.Build
import android.provider.Settings
import okhttp3.FormBody
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import sh.sar.basedbank.api.models.BankServerException
import java.util.concurrent.TimeUnit
class MfaisaLoginFlow(context: Context) {
private val BASE_URL = "https://superapp.ooredoo.mv/api/mfaisaa-bff/mfino/v1.1/web"
// Do NOT set User-Agent explicitly: Cloudflare in front of superapp.ooredoo.mv
// fingerprints header order, and an explicit .header("User-Agent", ...) call
// pushes it to the front of the request, returning 400. Letting OkHttp's
// BridgeInterceptor add its default "okhttp/4.12.0" at the end matches the
// official app's on-wire ordering and gets 200.
private val appContext = context.applicationContext
private val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
/**
* Step 0: look up the subscriber by MSISDN and verify they have Full KYC.
* Throws [MfaisaKycRequiredException] if kycStatus != "Full KYC".
* Throws [MfaisaWalletNotReadyException] if the wallet isn't registered / activated / PIN-set.
*/
fun fetchSubscriber(msisdn: String): JSONObject {
val body = JSONObject()
.put("mdnId", MfaisaCrypto.encryptMobile(msisdn))
.toString()
.matchGsonHtmlSafe()
.toRequestBody("application/json; charset=UTF-8".toMediaType())
val resp = client.newCall(
Request.Builder().url("$BASE_URL/fetchSubscriberByMDN")
.post(body)
.build()
).execute()
val code = resp.code
val raw = resp.body?.string() ?: throw Exception("Empty subscriber response")
resp.close()
if (code in 500..599) throw BankServerException("Ooredoo M-Faisa")
val obj = JSONObject(raw)
if (!obj.optBoolean("success", false)) {
throw Exception(obj.optString("message").ifBlank { "Could not look up this number" })
}
if (!obj.optBoolean("subscriberRegistered", false)) {
throw MfaisaNotRegisteredException()
}
if (!obj.optBoolean("passwordCreated", false)) {
throw MfaisaWalletNotReadyException("Set your M-Faisa mPIN in the Ooredoo SuperApp first, then try again.")
}
if (obj.optBoolean("activationPending", false)) {
throw MfaisaWalletNotReadyException("Your M-Faisa wallet activation is still pending. Complete it in the Ooredoo SuperApp first.")
}
val kyc = obj.optString("kycStatus")
if (kyc != "Full KYC") {
throw MfaisaKycRequiredException(kyc)
}
return obj
}
/**
* Step 1: submit the PIN. Returns parsed login result on success.
* Throws [MfaisaInvalidPinException] on a rejected PIN (with [MfaisaInvalidPinException.lastAttempt] = true
* if the server's message says "one more wrong attempt will lock your account").
*/
fun doMobileLogin(msisdn: String, pin: String): MfaisaLoginResult {
val mobileEnc = MfaisaCrypto.encryptMobile(msisdn)
val userNameEnc = MfaisaCrypto.encryptMobile(msisdn) // independent encryption, same plaintext
val pinEnc = MfaisaCrypto.encryptPin(pin)
val deviceId = androidId()
val deviceGeo = JSONObject()
.put("appType", "CustomerAndroid")
.put("appversion", "1.0")
.put("deviceId", deviceId)
.put("deviceManufacturer", Build.MANUFACTURER)
.put("imieNumber", deviceId)
.put("ipaddress", "11.22.33.55")
.put("latitude", "0.0")
.put("longitude", "0.0")
.put("simId", deviceId)
val formData = JSONObject()
.put("deviceGeoInfo", deviceGeo)
.put("mPin", pinEnc)
.put("mobileNumber", mobileEnc)
.put("role", "RETAIL_SUBSCRIBER")
.put("tenantCode", "ooredoo")
.put("userName", userNameEnc)
.toString()
.matchGsonHtmlSafe()
val body = FormBody.Builder()
.add("channel", "C03")
.add("formData", formData)
.add("formDataCs", "null")
.build()
val resp = client.newCall(
Request.Builder().url("$BASE_URL/doMobileLogin")
.post(body)
.build()
).execute()
val code = resp.code
val raw = resp.body?.string() ?: throw Exception("Empty login response")
resp.close()
if (code in 500..599) throw BankServerException("Ooredoo M-Faisa")
// Wrong-PIN response is a JSON array; success is an object.
val trimmed = raw.trimStart()
if (trimmed.startsWith("[")) {
val arr = JSONArray(trimmed)
val first = arr.optJSONObject(0)
val errObj = first?.optJSONArray("error")?.optJSONObject(0)
val msg = errObj?.optString("errorMessage")
?: first?.optString("message") ?: "Login failed"
val lastAttempt = msg.contains("one more", ignoreCase = true) ||
msg.contains("will lock", ignoreCase = true)
throw MfaisaInvalidPinException(msg, lastAttempt)
}
val obj = try { JSONObject(trimmed) } catch (e: JSONException) {
throw Exception("Unexpected login response")
}
if (!obj.optBoolean("success", false)) {
throw MfaisaInvalidPinException(obj.optString("message").ifBlank { "Login failed" }, false)
}
// Defensive: server also returns kycStatus on success.
val kyc = obj.optString("kycStatus")
if (kyc.isNotBlank() && kyc != "Full KYC") {
throw MfaisaKycRequiredException(kyc)
}
val session = MfaisaSession(
loginExchangeKey = obj.optString("loginExchangeKey"),
sessionTimeoutSec = obj.optString("mobileLoginSessionTimeout").toIntOrNull() ?: 240,
msisdn = msisdn,
subscriberId = obj.optString("suscriberId")
)
// pocketDetails[0] holds this user's identity + pockets.
val pd = obj.optJSONArray("pocketDetails")?.optJSONObject(0) ?: JSONObject()
val profile = MfaisaUserProfile(
name = pd.optString("name").ifBlank { "M-Faisa" },
email = pd.optString("eMailId"),
mdnId = pd.optString("mdnId").ifBlank { msisdn },
roleId = pd.optString("roleId"),
walletId = pd.optString("walletId"),
subscriberId = obj.optString("suscriberId"),
offerId = pd.optString("offerId")
)
val pockets = mutableListOf<MfaisaPocket>()
val pktArr = pd.optJSONArray("pocketSummaryDetailsArrayDTO") ?: JSONArray()
for (i in 0 until pktArr.length()) {
val p = pktArr.getJSONObject(i)
val bal = p.optJSONObject("balanceAmount") ?: JSONObject()
pockets += MfaisaPocket(
pocketId = p.optString("pocketId"),
pocketType = p.optString("pocketType"),
pocketValueType = p.optString("pocketValueType"),
nickname = p.optString("nickName"),
currency = bal.optString("currencyCode", "MVR"),
balance = bal.optDouble("amount", 0.0),
isDefault = p.optBoolean("isDefaultPocket", false),
isSecondary = p.optBoolean("isSecondaryPocket", false),
statusType = p.optString("statusType"),
displayName = p.optString("displayName")
)
}
return MfaisaLoginResult(session, profile, pockets)
}
private fun androidId(): String {
return Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID)
?: "0000000000000000"
}
/**
* Make the body byte-identical to what the official app's Gson serializer emits:
* 1. `\/` (org.json's default escape for `/`) → `/`
* 2. `=` → `=` (Gson `htmlSafe` mode)
* Both are technically valid JSON either way, but the M-Faisa server's parser appears strict.
*/
private fun String.matchGsonHtmlSafe(): String =
replace("\\/", "/").replace("=", "\\u003d")
}
@@ -1,69 +0,0 @@
package sh.sar.basedbank.api.mfaisa
data class MfaisaSession(
val loginExchangeKey: String,
val sessionTimeoutSec: Int,
val msisdn: String = "",
val subscriberId: String = ""
)
/** Subset of the doMobileLogin success response we keep around. */
data class MfaisaUserProfile(
val name: String,
val email: String,
val mdnId: String,
val roleId: String,
val walletId: String,
val subscriberId: String,
val offerId: String
)
/** Pocket = M-Faisa balance bucket (E-Money MVR, IMT MVR, PayPal USD). */
data class MfaisaPocket(
val pocketId: String,
val pocketType: String, // INTERNAL, ...
val pocketValueType: String, // EMONEY, PAYPAL_USD, ...
val nickname: String,
val currency: String, // MVR, USD
val balance: Double,
val isDefault: Boolean,
val isSecondary: Boolean,
val statusType: String,
val displayName: String
)
data class MfaisaLoginResult(
val session: MfaisaSession,
val profile: MfaisaUserProfile,
val pockets: List<MfaisaPocket>
)
/** Thrown when the wallet is not "Full KYC" — login must abort. */
class MfaisaKycRequiredException(val kycStatus: String) :
Exception("M-Faisa wallet is not fully verified (kycStatus=$kycStatus)")
/** Thrown when this MSISDN has no M-Faisa wallet at all — user must sign up in the Ooredoo SuperApp. */
class MfaisaNotRegisteredException : Exception("This number does not have an M-Faisa wallet")
/** Thrown when fetchSubscriberByMDN says the wallet exists but is not yet usable (no PIN, activation pending, …). */
class MfaisaWalletNotReadyException(message: String) : Exception(message)
/**
* Thrown for an invalid PIN. The PIN field should be re-enabled.
* [lastAttempt] is true when the server's message warns the user one more wrong attempt will lock their account.
*/
class MfaisaInvalidPinException(message: String, val lastAttempt: Boolean = false) : Exception(message)
/**
* Thrown when a session-scoped M-Faisa endpoint returns the
* `[{ ..., "attributeValue": "SESSION_EXPIRED", ... }]` envelope (still as HTTP 200).
* Callers should re-run the login (`fetchSubscriber` + `doMobileLogin`) using the saved
* credentials and retry the request once.
*/
class MfaisaSessionExpiredException : Exception("M-Faisa session expired")
/** Thrown by [MfaisaTransferClient.searchRecipient] when no M-Faisa wallet exists for the queried MSISDN. */
class MfaisaRecipientNotFoundException : Exception("No M-Faisa wallet found for this number")
/** Thrown by [MfaisaTransferClient.confirmTransfer] when the OTP is rejected. */
class MfaisaInvalidOtpException(message: String) : Exception(message)
@@ -1,199 +0,0 @@
package sh.sar.basedbank.api.mfaisa
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import org.json.JSONObject
import sh.sar.basedbank.api.models.BankServerException
import java.security.SecureRandom
import java.util.concurrent.TimeUnit
import java.util.zip.Adler32
/**
* M-Faisa merchant QR payment ("smart pay") flow:
* 1. [fetchQrDetails] POST /QRCodeUtility/fetchQRCodeById — resolve qrCodeId to merchant
* 2. [initiatePurchase] POST /initiateNewBuy — start the purchase, returns referenceId.
* Server returns 2FARequired=NONE for wallet QR pay,
* so no OTP is required.
* 3. [confirmPurchase] POST /confirmNewBuy — settles the purchase. `transactionAuthDetails`
* is sent as the literal string "null".
*
* Anti-replay scheme is the same as [MfaisaTransferClient]: rndValue = encryptPin(timestampStr),
* csValue = Adler32(formDataJson + timestampStr). The server responds with `[{...}]` envelopes
* for both success and error — callers must check the `success` flag.
*/
class MfaisaQrPayClient {
private val baseUrl = "https://superapp.ooredoo.mv/api/mfaisaa-bff/mfino/v1.1/web"
private val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
private val random = SecureRandom()
/** Resolved merchant for a scanned M-Faisa QR. */
data class QrMerchant(
val qrCodeId: String,
val merchantId: String, // customerId from the lookup response
val merchantName: String, // commercialName
val merchantMsisdn: String, // mobileNumber — already includes "960" prefix
val currencyCode: String, // e.g. "MVR"
/** Pre-set amount for a dynamic QR; null for a static QR (user enters amount). */
val txnAmount: String?,
val status: String // "Active" for usable QRs
)
// ─── Step 1: resolve qrCodeId → merchant details ─────────────────────────
fun fetchQrDetails(session: MfaisaSession, qrCodeId: String): QrMerchant {
val formData = JSONObject()
.put("qrCodeId", qrCodeId)
.put("tenantCode", "ooredoo")
.toString().matchGsonHtmlSafe()
val (rnd, cs) = makeAntiReplay(formData)
// Note: fetchQRCodeById uses role=R01 (not RETAIL_SUBSCRIBER like the other two endpoints).
val body = FormBody.Builder()
.add("role", "R01")
.add("channel", "C03")
.add("rndValue", rnd)
.add("formData", formData)
.add("loginExchangeKey", session.loginExchangeKey)
.add("csValue", cs)
.build()
val first = postAndUnwrap("$baseUrl/QRCodeUtility/fetchQRCodeById", body, "QR lookup failed")
val response = first.optJSONArray("response")?.optJSONObject(0)
?: throw Exception("QR code not found")
if (!response.optString("status").equals("Active", ignoreCase = true)) {
throw Exception("QR code is not active")
}
// The lookup response stores absent values as the literal JSON null (decoded by org.json as
// `JSONObject.NULL`) — optString surfaces that as the string "null". Guard against both.
fun strOrNull(name: String): String? = response.opt(name)
?.takeIf { it != JSONObject.NULL }
?.toString()
?.takeIf { it.isNotBlank() && it != "null" }
return QrMerchant(
qrCodeId = strOrNull("qrCodeId") ?: qrCodeId,
merchantId = strOrNull("customerId") ?: throw Exception("Merchant id missing"),
merchantName = strOrNull("commercialName") ?: throw Exception("Merchant name missing"),
merchantMsisdn = strOrNull("mobileNumber") ?: throw Exception("Merchant number missing"),
currencyCode = strOrNull("currencyCode") ?: "MVR",
txnAmount = strOrNull("txnAmount"),
status = response.optString("status")
)
}
// ─── Step 2: initiate the purchase ───────────────────────────────────────
/** Returns the `referenceId` to be passed to [confirmPurchase]. */
fun initiatePurchase(
session: MfaisaSession,
sourcePocketId: String,
sourceMsisdn: String, // user's "960..." MSISDN
merchant: QrMerchant,
amount: String,
description: String = ""
): String {
val formData = JSONObject()
.put("channel", "SubscriberApp")
.put("commodityType", "WALLET")
.put("description", description)
.put("merchantId", merchant.merchantId)
.put("mobileNumber", merchant.merchantMsisdn)
.put("sourceDetails", JSONObject()
.put("MDNId", sourceMsisdn)
.put("actorRoleType", "RETAIL_SUBSCRIBER")
.put("pocketId", sourcePocketId))
.put("transactionAmount", amount)
.put("transactionCurrency", merchant.currencyCode)
.put("transactionType", "PURCHASE")
.toString().matchGsonHtmlSafe()
val (rnd, cs) = makeAntiReplay(formData)
val body = FormBody.Builder()
.add("role", "RETAIL_SUBSCRIBER")
.add("channel", "C03")
.add("rndValue", rnd)
.add("formData", formData)
.add("loginExchangeKey", session.loginExchangeKey)
.add("csValue", cs)
.build()
val first = postAndUnwrap("$baseUrl/initiateNewBuy", body, "Payment initiation failed")
// We've only seen 2FARequired=NONE for wallet QR pay. If the server ever asks for OTP we
// surface a clear error instead of silently completing a no-op confirm.
val twoFa = first.optString("2FARequired").ifBlank { "NONE" }
if (!twoFa.equals("NONE", ignoreCase = true)) {
throw Exception("This QR requires 2FA ($twoFa) which is not yet supported")
}
val responseObj = first.optJSONArray("response")?.optJSONObject(0)?.optJSONObject("responseObject")
?: throw Exception("Missing responseObject")
val refId = responseObj.optString("referenceId")
if (refId.isBlank()) throw Exception("Server did not return a referenceId")
return refId
}
// ─── Step 3: confirm (no OTP) ────────────────────────────────────────────
fun confirmPurchase(session: MfaisaSession, referenceId: String) {
val formData = JSONObject().put("referenceId", referenceId).toString().matchGsonHtmlSafe()
val (rnd, cs) = makeAntiReplay(formData)
val body = FormBody.Builder()
.add("role", "RETAIL_SUBSCRIBER")
.add("channel", "C03")
.add("rndValue", rnd)
// Literal string "null" — matches the captured request from the official app.
.add("transactionAuthDetails", "null")
.add("formData", formData)
.add("loginExchangeKey", session.loginExchangeKey)
.add("csValue", cs)
.build()
postAndUnwrap("$baseUrl/confirmNewBuy", body, "Payment confirmation failed")
}
// ─── Helpers ─────────────────────────────────────────────────────────────
/** POSTs [body] to [url], unwraps the `[{...}]` envelope, throws on non-success / session expiry. */
private fun postAndUnwrap(url: String, body: okhttp3.RequestBody, fallbackError: String): JSONObject {
val resp = client.newCall(Request.Builder().url(url).post(body).build()).execute()
val code = resp.code
val raw = resp.body?.string() ?: throw Exception("Empty response")
resp.close()
if (code in 500..599) throw BankServerException("Ooredoo M-Faisa")
val arr = JSONArray(raw.trimStart())
val first = arr.optJSONObject(0) ?: throw Exception(fallbackError)
handleSessionExpiry(first)
if (!first.optBoolean("success", false)) {
val errObj = first.optJSONArray("error")?.optJSONObject(0)
throw Exception(errObj?.optString("errorMessage")?.ifBlank { null }
?: first.optString("message").ifBlank { fallbackError })
}
return first
}
private fun handleSessionExpiry(envelope: JSONObject?) {
val attr = envelope?.optJSONArray("error")?.optJSONObject(0)?.optString("attributeValue")
val code = envelope?.optJSONArray("error")?.optJSONObject(0)?.optString("errorCode")
if (attr == "SESSION_EXPIRED" || code == "SESSION_EXPIRED") throw MfaisaSessionExpiredException()
}
private fun makeAntiReplay(formJson: String): Pair<String, String> {
val offset = (random.nextInt(5) + 10) xor 0xE
val nonceStr = (System.currentTimeMillis() + offset).toString()
val rndValue = MfaisaCrypto.encryptPin(nonceStr)
val csValue = Adler32().apply {
update((formJson + nonceStr).toByteArray(Charsets.UTF_8))
}.value.toString()
return rndValue to csValue
}
private fun String.matchGsonHtmlSafe(): String =
replace("\\/", "/").replace("=", "\\u003d")
}
@@ -1,269 +0,0 @@
package sh.sar.basedbank.api.mfaisa
import android.os.Build
import android.provider.Settings
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import org.json.JSONObject
import sh.sar.basedbank.api.models.BankServerException
import java.security.SecureRandom
import java.util.concurrent.TimeUnit
import java.util.zip.Adler32
/**
* Three-step M-Faisa transfer flow:
* 1. [searchRecipient] POST /Pocket/basicBeneDetails — look up the recipient
* 2. [initiateTransfer] POST /initiateFTRequest — kicks off the transfer; server SMSes an OTP
* 3. [confirmTransfer] POST /confirmFTRequest — submit the OTP to actually move the money
*
* Every request uses the same anti-replay scheme as the history endpoint (see [MfaisaHistoryClient]):
* `rndValue` = `encryptPin(timestampStr)` and `csValue` = `Adler32(formDataJson + timestampStr)`.
*
* On a session timeout the server returns `[{... "attributeValue":"SESSION_EXPIRED" ...}]` with HTTP 200;
* each method throws [MfaisaSessionExpiredException] in that case so the caller can re-login and retry.
*/
class MfaisaTransferClient(private val deviceId: String) {
private val baseUrl = "https://superapp.ooredoo.mv/api/mfaisaa-bff/mfino/v1.1/web"
private val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
private val random = SecureRandom()
// ─── Step 1: recipient lookup ────────────────────────────────────────────
/**
* Result of [searchRecipient]. The MVR pocket (`isMvr`) is the only target for outgoing transfers
* in Thijooree — PayPal pockets are not supported as recipients.
*/
data class Recipient(
val name: String,
val msisdn: String, // already includes the "960" prefix, as returned by the server
val mvrPocketId: String?,
val paypalPocketId: String?,
val walletId: String,
val actorId: String
) {
val isMvr: Boolean get() = mvrPocketId != null
}
/** @throws MfaisaRecipientNotFoundException if no M-Faisa wallet exists for [recipientMsisdn]. */
fun searchRecipient(session: MfaisaSession, recipientMsisdn: String): Recipient {
require(session.msisdn.isNotBlank() && session.subscriberId.isNotBlank()) {
"session is missing fields required for basicBeneDetails"
}
val formData = JSONObject()
.put("beneficaryDetails", JSONObject()
.put("MDNId", MfaisaCrypto.encryptMobile(recipientMsisdn))
.put("actorRoleType", "RETAIL_SUBSCRIBER"))
.put("initiatorDetailsDTO", JSONObject()
.put("initiatingMDN", MfaisaCrypto.encryptMobile(session.msisdn))
.put("initiatingRoleId", session.subscriberId)
.put("initiatorRole", "RETAIL_SUBSCRIBER"))
.toString().matchGsonHtmlSafe()
val (rnd, cs) = makeAntiReplay(formData)
val body = FormBody.Builder()
.add("role", "RETAIL_SUBSCRIBER")
.add("channel", "SubscriberApp")
.add("rndValue", rnd)
.add("formData", formData)
.add("loginExchangeKey", session.loginExchangeKey)
.add("csValue", cs)
.build()
val raw = execute("$baseUrl/Pocket/basicBeneDetails", body)
// Response shape: `[{ success, response: [[pocket1, pocket2, ...]] }]`
val arr = JSONArray(raw.trimStart())
val first = arr.optJSONObject(0) ?: throw Exception("Unexpected response")
if (!first.optBoolean("success", false)) {
handleSessionExpiry(first)
val msg = first.optString("message")
if (msg.contains("not found", ignoreCase = true)) throw MfaisaRecipientNotFoundException()
throw Exception(msg.ifBlank { "Recipient lookup failed" })
}
val outer = first.optJSONArray("response") ?: throw Exception("Empty recipient list")
val pockets = outer.optJSONArray(0) ?: throw MfaisaRecipientNotFoundException()
if (pockets.length() == 0) throw MfaisaRecipientNotFoundException()
var name = ""
var msisdn = ""
var mvr: String? = null
var paypal: String? = null
var wallet = ""
var actor = ""
for (i in 0 until pockets.length()) {
val p = pockets.getJSONObject(i)
if (name.isBlank()) name = p.optString("name")
if (msisdn.isBlank()) msisdn = p.optString("MDNId")
if (wallet.isBlank()) wallet = p.optString("walletId")
if (actor.isBlank()) actor = p.optString("actorId")
when (p.optString("pocketValueType")) {
"EMONEY" -> mvr = p.optString("pocketId")
"PAYPAL_USD" -> paypal = p.optString("pocketId")
}
}
return Recipient(name, msisdn, mvr, paypal, wallet, actor)
}
// ─── Step 2: initiate (server sends OTP) ─────────────────────────────────
/** Returns the `referenceId` to be passed to [confirmTransfer]. */
fun initiateTransfer(
session: MfaisaSession,
sourcePocketId: String,
recipient: Recipient,
amount: String,
description: String
): String {
require(recipient.isMvr) { "M-Faisa transfers can only target the recipient's MVR pocket" }
// Inner formData JSON. The server expects PLAINTEXT mobile numbers here (already
// prefixed with "960" — recipient.msisdn already includes that), unlike step 1 which
// encrypts them.
val formData = JSONObject()
.put("MDNId", recipient.msisdn)
.put("beneDetails", JSONObject()
.put("miscDetails", description)
.put("transferMode", "MOBILE"))
.put("channel", "SubscriberApp")
.put("commodityType", "WALLET")
.put("description", description)
.put("inputDetailsDTO", JSONObject()
.put("deviceId", deviceId)
.put("simId", deviceId))
.put("mfs-transactionType", "send-money-to-mobile")
.put("pocketId", "")
.put("sourceDetails", JSONObject()
.put("MDNId", "960${session.msisdn}")
.put("actorRoleType", "RETAIL_SUBSCRIBER")
.put("pocketId", sourcePocketId))
.put("transactionAmount", amount)
.put("transactionCurrency", "MVR")
.put("transferMode", "MOBILE")
.toString().matchGsonHtmlSafe()
val (rnd, cs) = makeAntiReplay(formData)
// The "identifier" top-level field is the recipient MDN re-encrypted (matches step 1's
// `beneficaryDetails.MDNId` plaintext; independent OAEP randomness gives a different ciphertext).
val identifier = MfaisaCrypto.encryptMobile(recipient.msisdn.removePrefix("960"))
val body = FormBody.Builder()
.add("identifier", identifier)
.add("role", "RETAIL_SUBSCRIBER")
.add("transferMode", "MOBILE")
.add("channel", "C03") // NB: top-level "C03", inner formData.channel is "SubscriberApp"
.add("rndValue", rnd)
.add("formData", formData)
.add("loginExchangeKey", session.loginExchangeKey)
.add("tPin", "")
.add("csValue", cs)
.build()
val raw = execute("$baseUrl/initiateFTRequest", body)
val trimmed = raw.trimStart()
if (trimmed.startsWith("[")) {
val errArr = JSONArray(trimmed)
handleSessionExpiry(errArr.optJSONObject(0))
val errObj = errArr.optJSONObject(0)?.optJSONArray("error")?.optJSONObject(0)
throw Exception(errObj?.optString("errorMessage")?.ifBlank { null } ?: "Transfer initiation failed")
}
val obj = JSONObject(trimmed)
if (!obj.optBoolean("success", false)) {
throw Exception(obj.optString("message").ifBlank { "Transfer initiation failed" })
}
val responseArr = obj.optJSONArray("response") ?: throw Exception("Missing response array")
val responseObj = responseArr.optJSONObject(0)?.optJSONObject("responseObject")
?: throw Exception("Missing responseObject")
val refId = responseObj.optString("referenceId")
if (refId.isBlank()) throw Exception("Server did not return a referenceId")
return refId
}
// ─── Step 3: confirm with OTP ────────────────────────────────────────────
/** Submits [otpCode] for [referenceId]. Throws on invalid OTP / server failure. */
fun confirmTransfer(session: MfaisaSession, referenceId: String, otpCode: String) {
val formData = JSONObject().put("referenceId", referenceId).toString().matchGsonHtmlSafe()
val transactionAuthDetails = JSONObject()
.put("authenticationType", "OTP")
.put("authenticationValue", MfaisaCrypto.encryptPin(otpCode)) // same cipher as PIN
.put("otpTransactionType", "TRANSACTION")
.put("referenceId", referenceId)
.toString().matchGsonHtmlSafe()
val (rnd, cs) = makeAntiReplay(formData)
val body = FormBody.Builder()
.add("role", "RETAIL_SUBSCRIBER")
.add("channel", "C03")
.add("rndValue", rnd)
.add("transactionAuthDetails", transactionAuthDetails)
.add("formData", formData)
.add("loginExchangeKey", session.loginExchangeKey)
.add("csValue", cs)
.build()
val raw = execute("$baseUrl/confirmFTRequest", body)
val trimmed = raw.trimStart()
if (trimmed.startsWith("[")) {
val errArr = JSONArray(trimmed)
handleSessionExpiry(errArr.optJSONObject(0))
val errObj = errArr.optJSONObject(0)?.optJSONArray("error")?.optJSONObject(0)
val attr = errObj?.optString("attributeName")
val msg = errObj?.optString("errorMessage")?.ifBlank { null }
?: errArr.optJSONObject(0)?.optString("message")
if (attr.equals("OTP", ignoreCase = true) || (msg ?: "").contains("OTP", ignoreCase = true)) {
throw MfaisaInvalidOtpException(msg ?: "Invalid OTP")
}
throw Exception(msg ?: "Transfer confirmation failed")
}
val obj = JSONObject(trimmed)
if (!obj.optBoolean("success", false)) {
throw Exception(obj.optString("message").ifBlank { "Transfer confirmation failed" })
}
}
// ─── Helpers ─────────────────────────────────────────────────────────────
private fun execute(url: String, body: okhttp3.RequestBody): String {
val resp = client.newCall(Request.Builder().url(url).post(body).build()).execute()
val code = resp.code
val raw = resp.body?.string() ?: throw Exception("Empty response")
resp.close()
if (code in 500..599) throw BankServerException("Ooredoo M-Faisa")
return raw
}
private fun handleSessionExpiry(envelope: JSONObject?) {
val attr = envelope?.optJSONArray("error")?.optJSONObject(0)?.optString("attributeValue")
val code = envelope?.optJSONArray("error")?.optJSONObject(0)?.optString("errorCode")
if (attr == "SESSION_EXPIRED" || code == "SESSION_EXPIRED") throw MfaisaSessionExpiredException()
}
private fun makeAntiReplay(formJson: String): Pair<String, String> {
val offset = (random.nextInt(5) + 10) xor 0xE
val nonceStr = (System.currentTimeMillis() + offset).toString()
val rndValue = MfaisaCrypto.encryptPin(nonceStr)
val csValue = Adler32().apply {
update((formJson + nonceStr).toByteArray(Charsets.UTF_8))
}.value.toString()
return rndValue to csValue
}
private fun String.matchGsonHtmlSafe(): String =
replace("\\/", "/").replace("=", "\\u003d")
companion object {
/** Convenience factory that pulls the device identifier the way [MfaisaLoginFlow] does. */
fun forContext(context: android.content.Context): MfaisaTransferClient {
val id = Settings.Secure.getString(context.applicationContext.contentResolver, Settings.Secure.ANDROID_ID)
?: "0000000000000000"
// suppress "unused" — kept for symmetry with MfaisaLoginFlow if we later read Build.MANUFACTURER.
@Suppress("UNUSED_VARIABLE") val mfg = Build.MANUFACTURER
return MfaisaTransferClient(id)
}
}
}
@@ -1,135 +0,0 @@
package sh.sar.basedbank.api.mib
import android.os.Build
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import sh.sar.basedbank.ui.home.AppNotification
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.concurrent.TimeUnit
private val SKIP_TYPES = setOf("Switch Profile", "Log in")
private const val MIB_WV_URL = "https://faisamobilex-wv-v2.mib.com.mv"
class MibActivityHistoryClient {
private val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
private val sdf = SimpleDateFormat("dd MMM yyyy HH:mm", Locale.US)
data class FetchResult(
val items: List<AppNotification>, // already filtered (no Switch Profile)
val rawCount: Int, // raw items returned by API before filtering
val totalCount: Int,
val nextStart: Int
)
fun fetchActivity(
session: MibSession,
loginId: String,
start: Int,
end: Int
): FetchResult {
val cookieHeader = "mbmodel=AND-1.0; " +
"xxid=${session.xxid}; " +
"IBSID=${session.xxid}; " +
"mbnonce=${session.nonceGenerator}; " +
"time-tracker=597"
val formBody = FormBody.Builder()
.add("start", start.toString())
.add("end", end.toString())
.add("includeCount", "1")
.build()
val req = Request.Builder()
.url("$MIB_WV_URL/aProfile/getPagedActivityHistory")
.header("Cookie", cookieHeader)
.header("User-Agent", "Mozilla/5.0 (Linux; Android ${Build.VERSION.RELEASE}; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/129.0.6668.70 Mobile Safari/537.36")
.header("X-Requested-With", "XMLHttpRequest")
.post(formBody)
.build()
val body = try {
val resp = client.newCall(req).execute()
if (!resp.isSuccessful) { resp.close(); return FetchResult(emptyList(), 0, 0, end + 1) }
resp.body?.string().also { resp.close() } ?: return FetchResult(emptyList(), 0, 0, end + 1)
} catch (_: Exception) { return FetchResult(emptyList(), 0, 0, end + 1) }
return try {
val json = JSONObject(body)
if (!json.optBoolean("success")) return FetchResult(emptyList(), 0, 0, end + 1)
val totalCount = json.optString("total_count", "0").toIntOrNull() ?: 0
val dataArr = json.optJSONArray("data") ?: return FetchResult(emptyList(), 0, totalCount, end + 1)
val items = mutableListOf<AppNotification>()
val rawCount = dataArr.length()
for (i in 0 until rawCount) {
val obj = dataArr.getJSONObject(i)
val activityType = obj.optString("activityType")
if (activityType in SKIP_TYPES) continue
val pa = obj.optString("pa")
val activity = obj.optString("activity")
val pb = obj.optString("pb")
val dateStr = obj.optString("date")
val message = buildString {
append(pa)
if (activity.isNotBlank()) { append(" "); append(activity) }
if (pb.isNotBlank()) { append(" "); append(pb) }
}
val tsMs = try { sdf.parse(dateStr)?.time ?: System.currentTimeMillis() }
catch (_: Exception) { System.currentTimeMillis() }
val detailFields = mutableListOf<Pair<String, String>>().apply {
add("Bank" to "MIB")
add("Type" to activityType)
if (pa.isNotBlank()) add("By" to pa)
if (activity.isNotBlank() && pb.isNotBlank()) add("Action" to "$activity $pb")
if (dateStr.isNotBlank()) add("Date" to dateStr)
}
items.add(AppNotification(
id = obj.optString("aid"),
bank = "MIB",
loginId = loginId,
group = "ALERTS",
title = activityType,
message = message,
timestampMs = tsMs,
isRead = false, // resolved from cache in the sheet
detailFields = detailFields
))
}
FetchResult(items, rawCount, totalCount, end + 1)
} catch (_: Exception) { FetchResult(emptyList(), 0, 0, end + 1) }
}
// Keeps fetching pages until at least `minCount` non-Switch-Profile items found or all pages exhausted.
fun fetchUntilEnough(
session: MibSession,
loginId: String,
minCount: Int = 5,
pageSize: Int = 100
): FetchResult {
val accumulated = mutableListOf<AppNotification>()
var start = 1
var totalCount = 0
while (accumulated.size < minCount) {
val result = fetchActivity(session, loginId, start, start + pageSize - 1)
totalCount = result.totalCount
accumulated.addAll(result.items)
if (result.rawCount == 0 || start + pageSize - 1 >= totalCount) break
start = result.nextStart
}
return FetchResult(accumulated, accumulated.size, totalCount, start)
}
}
@@ -7,17 +7,9 @@ import okhttp3.Request
import org.json.JSONObject
import java.util.concurrent.TimeUnit
data class MibCardActionResult(
val success: Boolean,
val message: String,
val currentStatusCode: String
)
class MibCardsClient {
private val BASE_WV_URL = "https://faisamobilex-wv-v2.mib.com.mv"
private val USER_AGENT = "Mozilla/5.0 (Linux; Android ${Build.VERSION.RELEASE}; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/129.0.6668.70 Mobile Safari/537.36"
private val BASE_WV_URL = "https://faisamobilex-wv.mib.com.mv"
private val client = OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
@@ -25,10 +17,10 @@ class MibCardsClient {
.build()
private fun cookieHeader(session: MibSession) =
"mbmodel=AND-1.0; xxid=${session.xxid}; IBSID=${session.xxid}; " +
"mbmodel=IOS-1.0; xxid=${session.xxid}; IBSID=${session.xxid}; " +
"mbnonce=${session.nonceGenerator}; time-tracker=597"
fun fetchCards(session: MibSession, loginTag: String, profileId: String = ""): List<MibCard> {
fun fetchCards(session: MibSession, loginTag: String): List<MibCard> {
val body = FormBody.Builder()
.add("name", "")
.add("start", "1")
@@ -40,7 +32,7 @@ class MibCardsClient {
.url("$BASE_WV_URL/ajaxDebitCard/fetchCardInfos")
.post(body)
.header("Cookie", cookieHeader(session))
.header("User-Agent", USER_AGENT)
.header("User-Agent", "Mozilla/5.0 (Linux; Android ${Build.VERSION.RELEASE}; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/129.0.6668.70 Mobile Safari/537.36")
.header("X-Requested-With", "XMLHttpRequest")
.header("Accept", "*/*")
.header("Origin", BASE_WV_URL)
@@ -63,42 +55,9 @@ class MibCardsClient {
customerId = item.optString("customerId"),
phoneNumber = item.optString("phoneNumber"),
cardHolderName = item.optString("cardHolderName"),
loginTag = loginTag,
profileId = profileId
loginTag = loginTag
)
}
}
}
/** Freezes a MIB card. action = "freeze" or "unfreeze". */
fun setCardFreezeState(session: MibSession, cardId: String, action: String, comments: String): MibCardActionResult {
val body = FormBody.Builder()
.add("cardId", cardId)
.add("comments", comments)
.build()
val request = Request.Builder()
.url("$BASE_WV_URL/ajaxDebitCard/$action")
.post(body)
.header("Cookie", cookieHeader(session))
.header("User-Agent", USER_AGENT)
.header("X-Requested-With", "XMLHttpRequest")
.header("Accept", "*/*")
.header("Origin", BASE_WV_URL)
.header("Referer", "$BASE_WV_URL//debitCards/manage?cardId=$cardId&dashurl=1")
.build()
return client.newCall(request).execute().use { response ->
val bodyStr = response.body?.string()
?: return MibCardActionResult(false, "", "")
val json = try { JSONObject(bodyStr) } catch (_: Exception) {
return MibCardActionResult(false, "", "")
}
MibCardActionResult(
success = json.optBoolean("success"),
message = json.optString("reasonText"),
currentStatusCode = json.optString("currentStatusCode")
)
}
}
}
@@ -1,83 +1,135 @@
package sh.sar.basedbank.api.mib
import android.os.Build
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import java.util.concurrent.TimeUnit
class MibContactsClient(private val flow: MibLoginFlow) {
class MibContactsClient {
fun fetchCategories(session: MibSession): List<MibBeneficiaryCategory> =
fetchContactsAndCategories(session).second
private val TAG = "MibContactsClient"
private val BASE_WV_URL = "https://faisamobilex-wv.mib.com.mv"
fun fetchContacts(session: MibSession): List<MibBeneficiary> =
fetchContactsAndCategories(session).first
private val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
/**
* Pages through B41. Every page also carries the full category list.
* start/end select rows by their 1-based `rnum`, both ends inclusive.
*/
fun fetchContactsAndCategories(session: MibSession): Pair<List<MibBeneficiary>, List<MibBeneficiaryCategory>> {
val all = mutableListOf<MibBeneficiary>()
val seen = mutableSetOf<String>()
var categories = emptyList<MibBeneficiaryCategory>()
val pageSize = 10 // the official app always requests 10-row windows
var start = 1
while (true) {
val resp = flow.request(session, "B41") {
put("start", start)
put("end", start + pageSize - 1)
put("benefType", "A")
put("search", "")
put("includeCount", 1)
put("searchCategoryId", 0)
put("sortBenef", "")
}
if (!resp.optBoolean("success")) break
if (start == 1) categories = parseCategories(resp)
val totalCount = resp.optString("total_count", "0").toIntOrNull() ?: 0
val arr = resp.optJSONArray("data") ?: break
val page = (0 until arr.length()).map { parseContact(arr.getJSONObject(it)) }
for (c in page) if (seen.add(c.benefNo)) all.add(c)
val isLast = arr.length() == 0 ||
arr.getJSONObject(arr.length() - 1).optString("last") == "1"
if (isLast || all.size >= totalCount) break
start += pageSize
}
return Pair(all, categories)
}
private fun cookieHeader(session: MibSession) =
"mbmodel=IOS-1.0; xxid=${session.xxid}; IBSID=${session.xxid}; " +
"mbnonce=${session.nonceGenerator}; time-tracker=597"
private fun parseCategories(resp: JSONObject): List<MibBeneficiaryCategory> {
val arr = resp.optJSONArray("categories") ?: return emptyList()
return (0 until arr.length()).map { i ->
val o = arr.getJSONObject(i)
MibBeneficiaryCategory(
id = o.getString("id"),
categoryName = o.getString("categoryName"),
numBenef = o.optString("numBenef", "0").toIntOrNull() ?: 0
)
}
}
private fun parseContact(o: JSONObject): MibBeneficiary {
val hash = o.optString("customerImgHash")
return MibBeneficiary(
benefNo = o.optString("benefNo"),
benefName = o.optString("benefName"),
benefNickName = o.optString("benefNickName")
.ifBlank { o.optString("benefName") },
benefAccount = o.optString("benefAccount"),
benefType = o.optString("benefType"),
bankColor = o.optString("bankColor", "#888888"),
benefBankName = o.optString("benefBankName"),
bankCode = o.optString("bankCode"),
benefStatus = o.optString("benefStatus"),
transferCyDesc = o.optString("transferCyDesc", "MVR"),
customerImgHash = hash.takeIf { it.isNotBlank() && it != "null" },
benefCategoryId = o.optString("benefCategoryID", "0")
private fun Request.Builder.withSessionHeaders(session: MibSession): Request.Builder = this
.header("Cookie", cookieHeader(session))
.header(
"User-Agent",
"Mozilla/5.0 (Linux; Android ${Build.VERSION.RELEASE}; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/129.0.6668.70 Mobile Safari/537.36"
)
.header("X-Requested-With", "XMLHttpRequest")
.header("Accept", "*/*")
.header("Origin", BASE_WV_URL)
.header("Referer", "$BASE_WV_URL/beneficiary?dashurl=1")
fun fetchCategories(session: MibSession): List<MibBeneficiaryCategory> {
val request = Request.Builder()
.url("$BASE_WV_URL/ajaxBeneficiary/getCategories")
.post(FormBody.Builder().build())
.withSessionHeaders(session)
.build()
return client.newCall(request).execute().use { response ->
if (!response.isSuccessful) return emptyList()
parseCategories(response.body?.string() ?: return emptyList())
}
}
private fun parseCategories(json: String): List<MibBeneficiaryCategory> {
return try {
val arr = JSONObject(json).getJSONArray("data")
(0 until arr.length()).map { i ->
val o = arr.getJSONObject(i)
MibBeneficiaryCategory(
id = o.getString("id"),
categoryName = o.getString("categoryName"),
numBenef = o.optString("numBenef", "0").toIntOrNull() ?: 0
)
}
} catch (e: Exception) {
emptyList()
}
}
fun fetchContacts(session: MibSession): List<MibBeneficiary> {
val all = mutableListOf<MibBeneficiary>()
var page = 1
val pageSize = 100
while (true) {
val start = (page - 1) * pageSize + 1
val end = page * pageSize
val body = FormBody.Builder()
.add("page", page.toString())
.add("search", "")
.add("searchCategoryId", "0")
.add("benefType", "A")
.add("sortBenef", "name")
.add("sortDir", "asc")
.add("start", start.toString())
.add("end", end.toString())
.add("includeCount", "1")
.build()
val request = Request.Builder()
.url("$BASE_WV_URL/ajaxBeneficiary/main")
.post(body)
.withSessionHeaders(session)
.build()
val (contacts, totalCount) = client.newCall(request).execute().use { response ->
if (!response.isSuccessful) return all
parseContacts(response.body?.string() ?: return all)
}
all.addAll(contacts)
if (all.size >= totalCount || contacts.isEmpty()) break
page++
}
return all
}
private fun parseContacts(json: String): Pair<List<MibBeneficiary>, Int> {
return try {
val obj = JSONObject(json)
val totalCount = obj.optString("total_count", "0").toIntOrNull() ?: 0
val arr = obj.getJSONArray("data")
val contacts = (0 until arr.length()).map { i ->
val o = arr.getJSONObject(i)
val hash = o.optString("customerImgHash")
MibBeneficiary(
benefNo = o.optString("benefNo"),
benefName = o.optString("benefName"),
benefNickName = o.optString("benefNickName")
.ifBlank { o.optString("benefName") },
benefAccount = o.optString("benefAccount"),
benefType = o.optString("benefType"),
bankColor = o.optString("bankColor", "#888888"),
benefBankName = o.optString("benefBankName"),
bankCode = o.optString("bankCode"),
benefStatus = o.optString("benefStatus"),
transferCyDesc = o.optString("transferCyDesc", "MVR"),
customerImgHash = hash.takeIf { it.isNotBlank() && it != "null" },
benefCategoryId = o.optString("benefCategoryID", "0")
)
}
Pair(contacts, totalCount)
} catch (e: Exception) {
Pair(emptyList(), 0)
}
}
/** Creates a beneficiary via B43. The server rejects nicknames longer than ~20 chars. */
fun createContact(
session: MibSession,
benefType: String, // "I" = MIB internal, "L" = local/BML
bankNo: Int, // 2 = MIB, 3 = BML
benefAccount: String,
benefName: String,
@@ -86,62 +138,82 @@ class MibContactsClient(private val flow: MibLoginFlow) {
categoryId: String = "0",
imageBase64: String = ""
): Boolean {
val (bankName, bankSwift) = bankInfo(bankNo)
val resp = flow.request(session, "B43") {
put("benefName", benefName)
put("benefAccount", benefAccount)
put("bankNo", bankNo.toString())
put("nickName", nickName)
put("transferCy", transferCy)
put("categoryId", categoryId)
if (imageBase64.isNotBlank()) put("image", imageBase64)
put("bankName", bankName)
put("bankSwift", bankSwift)
val body = FormBody.Builder()
.add("benefType", benefType)
.add("imageSet", if (imageBase64.isNotBlank()) "1" else "0")
.add("benefAccount", benefAccount)
.add("benefIban", "")
.add("benefName", benefName)
.add("nickName", nickName)
.add("transferCy", transferCy)
.add("transferCySwift", "840")
.add("benefAddress", "")
.add("benefCity", "")
.add("benefCountry", "4")
.add("benefBankSwift", "")
.add("bankNo", bankNo.toString())
.add("benefBankName", "")
.add("benefBankBranch", "")
.add("benefBankAddress", "")
.add("benefBankCity", "")
.add("benefBankCountry", "4")
.add("intBankSwift", "")
.add("intBankName", "")
.add("intBankAddress", "")
.add("intBankBranch", "")
.add("intBankCity", "")
.add("intBankCountry", "4")
.add("categoryId", categoryId)
.add("email", "")
.add("contactNumber", "")
.add("website", "")
.add("image", imageBase64)
.build()
val request = Request.Builder()
.url("$BASE_WV_URL/ajaxBeneficiary/createLocalBeneficiary")
.post(body)
.withSessionHeaders(session)
.header("Referer", "$BASE_WV_URL/beneficiary/createNew")
.build()
return client.newCall(request).execute().use { response ->
val bodyStr = response.body?.string() ?: return@use false
try { JSONObject(bodyStr).optBoolean("success") } catch (_: Exception) { false }
}
return resp.optBoolean("success")
}
/** Updates a beneficiary via B52. A blank [imageBase64] keeps the current photo. */
fun updateContact(
session: MibSession,
benefNo: String,
bankNo: Int, // 2 = MIB, 3 = BML
benefAccount: String,
benefName: String,
nickName: String,
transferCy: String = "462",
categoryId: String = "0",
imageBase64: String = ""
): Boolean {
val (bankName, bankSwift) = bankInfo(bankNo)
val resp = flow.request(session, "B52") {
put("benefName", benefName)
put("benefAccount", benefAccount)
put("bankNo", bankNo.toString())
put("nickName", nickName)
put("transferCy", transferCy)
put("categoryId", categoryId)
put("benefNo", benefNo)
put("imageChanged", if (imageBase64.isNotBlank()) "1" else "0")
if (imageBase64.isNotBlank()) put("image", imageBase64)
put("bankName", bankName)
put("bankSwift", bankSwift)
fun deleteContact(session: MibSession, benefNo: String): Boolean {
val body = FormBody.Builder().add("benefNo", benefNo).build()
val request = Request.Builder()
.url("$BASE_WV_URL/ajaxBeneficiary/deleteBeneficiary")
.post(body)
.withSessionHeaders(session)
.build()
return client.newCall(request).execute().use { response ->
val bodyStr = response.body?.string() ?: return@use false
try { JSONObject(bodyStr).optBoolean("success") } catch (_: Exception) { false }
}
return resp.optBoolean("success")
}
/** Bank name/SWIFT as listed by B49 for the bank IDs we support. */
private fun bankInfo(bankNo: Int): Pair<String, String> = when (bankNo) {
2 -> "Maldives Islamic Bank" to "MADVMVMV"
else -> "Bank of Maldives PLC" to "MALBMVMV"
}
fun deleteContact(session: MibSession, benefNo: String): Boolean =
flow.request(session, "B48") { put("benefNo", benefNo) }.optBoolean("success")
fun fetchProfileImageBase64(session: MibSession, imageHash: String): String? {
val resp = flow.request(session, "B46") { put("imageHash", imageHash) }
if (!resp.optBoolean("success")) return null
return resp.optString("profileImage").takeIf { it.isNotBlank() }
val body = FormBody.Builder()
.add("imageHash", imageHash)
.build()
val request = Request.Builder()
.url("$BASE_WV_URL/ajaxBeneficiary/getProfileImage")
.post(body)
.withSessionHeaders(session)
.build()
return client.newCall(request).execute().use { response ->
if (!response.isSuccessful) return null
try {
val json = response.body?.string() ?: return null
JSONObject(json).optString("profileImage").takeIf { it.isNotBlank() }
} catch (e: Exception) {
null
}
}
}
}
@@ -9,7 +9,7 @@ import kotlin.math.ceil
class MibFinancingClient {
private val TAG = "MibFinancingClient"
private val BASE_WV_URL = "https://faisamobilex-wv-v2.mib.com.mv"
private val BASE_WV_URL = "https://faisamobilex-wv.mib.com.mv"
private val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
@@ -17,7 +17,7 @@ class MibFinancingClient {
.build()
fun fetchFinancing(session: MibSession): List<MibFinanceDeal> {
val cookieHeader = "mbmodel=AND-1.0; " +
val cookieHeader = "mbmodel=IOS-1.0; " +
"xxid=${session.xxid}; " +
"IBSID=${session.xxid}; " +
"mbnonce=${session.nonceGenerator}; " +
@@ -1,9 +1,27 @@
package sh.sar.basedbank.api.mib
class MibHistoryClient(private val flow: MibLoginFlow) {
import android.os.Build
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import java.util.concurrent.TimeUnit
class MibHistoryClient {
private val BASE_WV_URL = "https://faisamobilex-wv.mib.com.mv"
private val client = OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build()
private fun cookieHeader(session: MibSession) =
"mbmodel=IOS-1.0; xxid=${session.xxid}; IBSID=${session.xxid}; " +
"mbnonce=${session.nonceGenerator}; time-tracker=597"
/**
* Fetches transaction history for a single MIB account via the encrypted `A84` route.
* Fetches transaction history for a single MIB account.
* @param start 1-based index; use 1 for first page, 21 for second, etc. (pageSize=20)
* @return Pair of (transactions, totalCount)
*/
@@ -14,36 +32,57 @@ class MibHistoryClient(private val flow: MibLoginFlow) {
start: Int = 1,
pageSize: Int = 20
): Pair<List<Transaction>, Int> {
// A84 uses a 0-based inclusive range: first page is start=0, end=19
val json = flow.request(session, "A84") {
put("accountNo", accountNo)
put("start", start - 1)
put("end", start - 1 + pageSize - 1)
put("includeCount", true)
put("trxType", 0)
put("sortTrx", "date")
put("sortDir", "desc")
}
if (!json.optBoolean("success")) return Pair(emptyList(), 0)
val total = json.optString("total_count", "0").toIntOrNull() ?: 0
val data = json.optJSONArray("data") ?: return Pair(emptyList(), total)
val transactions = (0 until data.length()).map { i ->
val item = data.getJSONObject(i)
Transaction(
id = item.optString("trxNumber"),
date = item.optString("trxDate"),
description = item.optString("descr1").trim(),
amount = item.optString("foreignAmount", "0").toDoubleOrNull() ?: 0.0,
currency = item.optString("curCodeDesc"),
counterpartyName = item.optString("benefName").takeIf {
it.isNotBlank() && it != "null"
},
reference = item.optString("trxNumber2").takeIf { it.isNotBlank() },
accountNumber = accountNo,
accountDisplayName = accountDisplayName,
source = "MIB"
val body = FormBody.Builder()
.add("accountNo", accountNo)
.add("trxNo", "")
.add("trxType", "0")
.add("sortTrx", "date")
.add("sortDir", "desc")
.add("fromDate", "")
.add("toDate", "")
.add("start", start.toString())
.add("end", (start + pageSize - 1).toString())
.add("includeCount", "1")
.build()
val request = Request.Builder()
.url("$BASE_WV_URL/ajaxAccounts/trxHistory")
.post(body)
.header("Cookie", cookieHeader(session))
.header(
"User-Agent",
"Mozilla/5.0 (Linux; Android ${Build.VERSION.RELEASE}; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/129.0.6668.70 Mobile Safari/537.36"
)
.header("X-Requested-With", "XMLHttpRequest")
.header("Accept", "*/*")
.header("Origin", BASE_WV_URL)
.header("Referer", "$BASE_WV_URL//accountDetails?trxh=1&dashurl=1&accountNo=$accountNo")
.build()
return client.newCall(request).execute().use { response ->
val bodyStr = response.body?.string() ?: return Pair(emptyList(), 0)
val json = try { JSONObject(bodyStr) } catch (_: Exception) { return Pair(emptyList(), 0) }
if (!json.optBoolean("success")) return Pair(emptyList(), 0)
val total = json.optString("total_count", "0").toIntOrNull() ?: 0
val data = json.optJSONArray("data") ?: return Pair(emptyList(), total)
val transactions = (0 until data.length()).map { i ->
val item = data.getJSONObject(i)
Transaction(
id = item.optString("trxNumber"),
date = item.optString("trxDate"),
description = item.optString("descr1").trim(),
amount = item.optString("baseAmount", "0").toDoubleOrNull() ?: 0.0,
currency = item.optString("curCodeDesc"),
counterpartyName = item.optString("benefName").takeIf {
it.isNotBlank() && it != "null"
},
reference = item.optString("trxNumber2").takeIf { it.isNotBlank() },
accountNumber = accountNo,
accountDisplayName = accountDisplayName,
source = "MIB"
)
}
Pair(transactions, total)
}
return Pair(transactions, total)
}
}
@@ -7,20 +7,15 @@ import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import java.security.MessageDigest
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.math.abs
import kotlin.random.Random
class SessionExpiredException : Exception("MIB session expired")
class MibLoginFlow(private val credentialStore: CredentialStore) {
private val BASE_URL = "https://faisamobilex-smvc-v2.mib.com.mv/index/"
private val BASE_URL = "https://faisanet.mib.com.mv/faisamobilex_smvc/"
/** The active session after a successful login, usable for subsequent WebView requests. */
var lastSession: MibSession? = null
@@ -30,12 +25,6 @@ class MibLoginFlow(private val credentialStore: CredentialStore) {
var lastProfiles: List<MibProfile> = emptyList()
private set
/** Full name and email from the last A41 login response. */
var lastFullName: String = ""
private set
var lastEmail: String = ""
private set
/** Called after automatic session recovery so callers can update their session reference. */
var onSessionRefreshed: ((MibSession, List<MibProfile>) -> Unit)? = null
@@ -50,22 +39,16 @@ class MibLoginFlow(private val credentialStore: CredentialStore) {
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.addNetworkInterceptor { chain ->
.addInterceptor { chain ->
val req = chain.request().newBuilder()
.header("User-Agent", "android/2.0")
.header("User-Agent", "android/1.0")
.header("Accept", "application/json")
.header("X-Request-ID", generateRequestId())
.header("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
.build()
chain.proceed(req)
}
.build()
/** Swap the seed used for silent re-login after the user replaces it on the OTP screen. */
fun updateOtpSeed(otpSeed: String) {
if (storedOtpSeed != null) storedOtpSeed = otpSeed
}
// ─── Public entry point ───────────────────────────────────────────────────
/**
@@ -155,8 +138,6 @@ class MibLoginFlow(private val credentialStore: CredentialStore) {
}
val profiles = parseProfiles(loginResp)
lastFullName = loginResp.optString("fullName").takeIf { it != "null" } ?: ""
lastEmail = loginResp.optString("email").takeIf { it != "null" } ?: ""
lastSession = session2
lastProfiles = profiles // keep ALL profiles so settings can show them all
@@ -187,7 +168,7 @@ class MibLoginFlow(private val credentialStore: CredentialStore) {
accountTypeName = a.optString("accountTypeName"),
availableBalance = a.optString("availableBalance"),
currentBalance = a.optString("currentBalance"),
blockedAmount = absBlockedAmount(a.optString("blockedAmount")),
blockedAmount = a.optString("blockedAmount"),
mvrBalance = a.optString("mvrBalance"),
statusDesc = a.optString("statusDesc"),
profileImageHash = profile.customerImage,
@@ -207,13 +188,6 @@ class MibLoginFlow(private val credentialStore: CredentialStore) {
// ─── Helpers ─────────────────────────────────────────────────────────────
/** MIB returns blockedAmount as a signed decimal where negative = funds held.
* Normalize to a positive magnitude so downstream code can treat it uniformly. */
private fun absBlockedAmount(raw: String): String {
val v = raw.toDoubleOrNull() ?: return raw
return "%.2f".format(abs(v))
}
private fun initialKeyExchange(
appId: String, encKey: String, sfunc: String, key2: String? = null
): Pair<MibSession, String> {
@@ -313,13 +287,6 @@ class MibLoginFlow(private val credentialStore: CredentialStore) {
put("xxid", session.xxid)
}
/**
* Sends an encrypted `sfunc=n` request for [routePath] with the base fields plus [fields].
* Expired sessions are recovered the same way as login requests.
*/
fun request(session: MibSession, routePath: String, fields: JSONObject.() -> Unit = {}): JSONObject =
doRequest(session, baseData(session, routePath).apply(fields), "n")
/**
* Activates [profile] server-side via P47, setting the session role context so that
* subsequent WebView requests run under that profile.
@@ -358,7 +325,7 @@ class MibLoginFlow(private val credentialStore: CredentialStore) {
accountTypeName = a.optString("accountTypeName"),
availableBalance = a.optString("availableBalance"),
currentBalance = a.optString("currentBalance"),
blockedAmount = absBlockedAmount(a.optString("blockedAmount")),
blockedAmount = a.optString("blockedAmount"),
mvrBalance = a.optString("mvrBalance"),
statusDesc = a.optString("statusDesc"),
profileImageHash = profile.customerImage,
@@ -399,34 +366,6 @@ class MibLoginFlow(private val credentialStore: CredentialStore) {
return resp.optString("profileImage").takeIf { it.isNotBlank() }
}
/**
* Uploads a profile image via P40.
* [imageBase64] is a base64-encoded JPEG string.
* Returns the new imageHash on success, or null on failure.
*/
fun uploadProfileImage(session: MibSession, profile: MibProfile, imageBase64: String): String? {
val payload = baseData(session, "P40").apply {
put("profileId", profile.profileId)
put("profileImage", imageBase64)
}
val resp = doRequest(session, payload, "n")
if (!resp.optBoolean("success", false)) return null
return resp.optString("imageHash").takeIf { it.isNotBlank() }
?: resp.optString("customerImage").takeIf { it.isNotBlank() }
}
/**
* Deletes the profile image via P42.
* Returns true on success.
*/
fun deleteProfileImage(session: MibSession, profile: MibProfile): Boolean {
val payload = baseData(session, "P42").apply {
put("profileId", profile.profileId)
}
val resp = doRequest(session, payload, "n")
return resp.optBoolean("success", false)
}
private fun post(body: FormBody): String {
val request = Request.Builder()
.url(BASE_URL)
@@ -444,16 +383,6 @@ class MibLoginFlow(private val credentialStore: CredentialStore) {
return sha256Upper(clientSalt + h2)
}
private fun generateRequestId(): String {
val sdf = SimpleDateFormat("yyyyMMddHHmmss", Locale.US).apply {
timeZone = TimeZone.getTimeZone("UTC")
}
val timestamp = sdf.format(Date())
val millis = System.currentTimeMillis() % 1000
val randomHex = Random.nextBytes(8).joinToString("") { "%02x".format(it) }
return "$timestamp${millis.toString().padStart(3, '0')}-$randomHex"
}
companion object {
/** Returns SHA-256(password) as uppercase hex. Store this instead of the raw password. */
fun hashPassword(password: String): String =
@@ -35,16 +35,14 @@ data class MibTransferResult(
val success: Boolean,
val trxId: String = "",
val date: String = "",
val errorMessage: String = "",
val reasonCode: String = ""
val errorMessage: String = ""
)
data class MibIpsAccountInfo(
val accountName: String,
val accountNumber: String,
val bankId: String,
val currency: String = "" // "MVR", "USD", or "" if unknown
val bankId: String
)
@@ -57,8 +55,7 @@ data class MibCard(
val customerId: String,
val phoneNumber: String,
val cardHolderName: String,
val loginTag: String,
val profileId: String = ""
val loginTag: String
)
data class MibFinanceDeal(
@@ -1,87 +1,50 @@
package sh.sar.basedbank.api.mib
import android.os.Build
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import sh.sar.basedbank.util.CredentialStore
import java.util.concurrent.TimeUnit
data class MibPersonalProfile(
val fullName: String,
val username: String,
val email: String,
val mobile: String,
val idCard: String
val enrolled: String
)
class MibProfileClient(private val flow: MibLoginFlow) {
private val BASE_WV_URL = "https://faisamobilex-wv-v2.mib.com.mv"
class MibProfileClient {
private val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
/**
* Name comes from the A41 login response; email, mobile and National ID from the
* Favara alias suggestions (`/ajaxAlias/getAliasTypes`), which belong to the active
* profile — so the personal profile is selected first.
*/
fun fetchPersonalProfile(session: MibSession): MibPersonalProfile? {
val personal = flow.lastProfiles.firstOrNull { it.profileType == "0" }
if (personal != null) flow.switchProfile(session, personal)
val cookieHeader = "mbmodel=IOS-1.0; xxid=${session.xxid}; " +
"IBSID=${session.xxid}; mbnonce=${session.nonceGenerator}; time-tracker=597"
val request = Request.Builder()
.url("$BASE_WV_URL/ajaxAlias/getAliasTypes")
.post(FormBody.Builder().build())
.header("Cookie", "mbmodel=AND-1.0; xxid=${session.xxid}; IBSID=${session.xxid}; mbnonce=${session.nonceGenerator}")
.header(
"User-Agent",
"Mozilla/5.0 (Linux; Android ${Build.VERSION.RELEASE}; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/129.0.6668.70 Mobile Safari/537.36"
)
.header("X-Requested-With", "XMLHttpRequest")
.header("Accept", "*/*")
.header("Origin", BASE_WV_URL)
.header("Referer", "$BASE_WV_URL/Alias/Alias?dashurl=1")
.url("https://faisamobilex-wv.mib.com.mv/personalProfile")
.get()
.header("Cookie", cookieHeader)
.build()
val json = client.newCall(request).execute().use { response ->
val body = response.body?.string() ?: return null
try { JSONObject(body) } catch (_: Exception) { return null }
}
if (!json.optBoolean("success")) return null
// Alias type ids: 0 = mobile number, 1 = email, 3 = National ID
val aliases = json.optJSONArray("data")
fun alias(id: Int): String {
if (aliases == null) return ""
for (i in 0 until aliases.length()) {
val o = aliases.getJSONObject(i)
if (o.optInt("id", -1) == id) return o.optString("suggestedAlias").takeIf { it != "null" } ?: ""
return try {
val resp = client.newCall(request).execute()
val html = resp.body?.string() ?: return null
resp.close()
fun scrape(label: String): String {
val r = Regex("""<span[^>]*>\s*<b[^>]*>\s*$label\s*</b[^>]*>.*?<span[^>]*>([^<]+)</span>""",
setOf(RegexOption.DOT_MATCHES_ALL, RegexOption.IGNORE_CASE))
return r.find(html)?.groupValues?.get(1)?.trim() ?: ""
}
return ""
}
return MibPersonalProfile(
fullName = flow.lastFullName.ifBlank { personal?.name ?: "" },
email = alias(1).ifBlank { flow.lastEmail },
mobile = alias(0),
idCard = alias(3)
)
}
/** Fetches and caches the user's details for [loginId] unless a v2 fetch is already cached. */
fun cacheIfMissing(store: CredentialStore, loginId: String, session: MibSession) {
if (store.loadMibUserProfile(loginId)?.idCard != null) return
val p = fetchPersonalProfile(session) ?: return
store.saveMibUserProfile(loginId, CredentialStore.MibUserProfile(
fullName = p.fullName,
username = loginId,
email = p.email,
mobile = p.mobile,
enrolled = "",
idCard = p.idCard
))
val nameRegex = Regex("""<h5 class="mb-1 text-dark fw-semibold">\s*([^<]+)\s*</h5>""")
val fullName = nameRegex.find(html)?.groupValues?.get(1)?.trim() ?: return null
MibPersonalProfile(
fullName = fullName,
username = scrape("Username:"),
email = scrape("Email:"),
mobile = scrape("Mobile no:"),
enrolled = scrape("Enrolled:")
)
} catch (_: Exception) { null }
}
}
@@ -1,12 +1,42 @@
package sh.sar.basedbank.api.mib
import android.os.Build
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import java.util.concurrent.TimeUnit
class MibLookupException(message: String) : Exception(message)
class MibTransferClient(private val flow: MibLoginFlow) {
class MibTransferClient {
private val TAG = "MibTransferClient"
private val BASE_WV_URL = "https://faisamobilex-wv.mib.com.mv"
private val client = OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.build()
private fun cookieHeader(session: MibSession) =
"mbmodel=IOS-1.0; xxid=${session.xxid}; IBSID=${session.xxid}; " +
"mbnonce=${session.nonceGenerator}; time-tracker=597"
private fun Request.Builder.withWvHeaders(session: MibSession): Request.Builder = this
.header("Cookie", cookieHeader(session))
.header(
"User-Agent",
"Mozilla/5.0 (Linux; Android ${Build.VERSION.RELEASE}; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/129.0.6668.70 Mobile Safari/537.36"
)
.header("X-Requested-With", "XMLHttpRequest")
.header("Accept", "*/*")
.header("Origin", BASE_WV_URL)
.header("Referer", "$BASE_WV_URL/transfer/quick")
/**
* Execute a transfer. bankNo=2 → MIB internal (T50), bankNo=3 → local/BML via Favara (T51).
* currencyCode: "462"=MVR, "840"=USD.
* Execute a transfer. bankNo=2 → MIB internal (/transferInternal), bankNo=3 → local/BML (/transferLocal).
* currencyCode: "462"=MVR, "840"=USD. purpose uses "-" if blank.
*/
fun transfer(
session: MibSession,
@@ -19,79 +49,146 @@ class MibTransferClient(private val flow: MibLoginFlow) {
purpose: String,
otp: String
): MibTransferResult {
val json = flow.request(session, if (bankNo == 2) "T50" else "T51") {
put("benefName", benefName)
put("benefNo", "0")
put("fromAccountNo", fromAccount)
put("benefAccountNo", toAccount)
put("transferCy", currencyCode)
put("benefCurrencyCode", currencyCode)
put("amount", amount)
put("bankNo", bankNo.toString())
put("purpose", purpose)
put("otp", otp)
put("otpType", "3")
val endpoint = if (bankNo == 2) "transferInternal" else "transferLocal"
val body = FormBody.Builder()
.add("benefName", benefName)
.add("benefNo", "0")
.add("fromAccountNo", fromAccount)
.add("benefAccountNo", toAccount)
.add("transferCy", currencyCode)
.add("benefCurrencyCode", currencyCode)
.add("amount", amount)
.add("bankNo", bankNo.toString())
.add("purpose", purpose.ifBlank { "-" })
.add("otp", otp)
.add("otpType", "3")
.build()
val request = Request.Builder()
.url("$BASE_WV_URL/ajaxTransfer/$endpoint")
.post(body)
.withWvHeaders(session)
.build()
return client.newCall(request).execute().use { response ->
if (response.code == 419) throw SessionExpiredException()
val bodyStr = response.body?.string() ?: ""
val json = try { JSONObject(bodyStr) } catch (_: Exception) { null }
if (json == null || !json.optBoolean("success")) {
MibTransferResult(
success = false,
errorMessage = json?.optString("reasonText")?.ifBlank { null } ?: "Transfer failed"
)
} else {
val data = json.optJSONArray("data")?.optJSONObject(0)
MibTransferResult(
success = true,
trxId = data?.optString("trxId") ?: "",
date = data?.optString("date") ?: ""
)
}
}
if (!json.optBoolean("success")) {
return MibTransferResult(
success = false,
errorMessage = json.optString("reasonText").ifBlank { "Transfer failed" },
reasonCode = json.optString("reasonCode")
)
}
val data = json.optJSONArray("data")?.optJSONObject(0)
return MibTransferResult(
success = true,
trxId = data?.optString("trxId") ?: "",
date = data?.optString("date") ?: ""
)
}
/**
* Resolves a destination via B40, which takes any supported input:
* Routes the lookup to the correct endpoint based on input format:
*
* - 13 digits starting with 7 → BML / local bank account
* - 17 digits starting with 9 → MIB account
* - 15 digits starting with 7 → IPS account lookup (BML / local bank)
* - 17 digits starting with 9 → MIB internal account name lookup
* - 7 digits starting with 7 or 9,
* A + 6 digits,
* or email address → Favara alias
*
* The format check only avoids sending inputs B40 can't resolve.
* or email address → Favara alias lookup
*/
fun lookup(session: MibSession, input: String): MibIpsAccountInfo {
// B40 only resolves Favara IDs with an uppercase "A" ("a239225" fails, "A239225" works)
val trimmed = input.trim().let { if (it.matches(Regex("^a\\d{6}$"))) it.uppercase() else it }
val supported = trimmed.matches(Regex("^7\\d{12}$")) ||
trimmed.matches(Regex("^9\\d{16}$")) ||
trimmed.matches(Regex("^[79]\\d{6}$")) ||
trimmed.matches(Regex("^[Aa]\\d{6}$")) ||
trimmed.contains("@")
if (!supported) throw MibLookupException("Unrecognized account number format")
val trimmed = input.trim()
return when {
trimmed.matches(Regex("^7\\d{12}$")) -> lookupIpsAccount(session, trimmed)
trimmed.matches(Regex("^9\\d{16}$")) -> lookupAccountName(session, trimmed)
trimmed.matches(Regex("^[79]\\d{6}$")) -> lookupAlias(session, trimmed)
trimmed.matches(Regex("^[Aa]\\d{6}$")) -> lookupAlias(session, trimmed)
trimmed.contains("@") -> lookupAlias(session, trimmed)
else -> throw MibLookupException("Unrecognized account number format")
}
}
val json = flow.request(session, "B40") { put("search", trimmed) }
val match = json.optJSONArray("data")?.optJSONObject(0)
if (!json.optBoolean("success") || match == null) {
throw MibLookupException(
json.optString("reasonText").trim().ifBlank { "Account not found" }
/** BML / local bank: 15-digit account starting with 7. */
private fun lookupIpsAccount(session: MibSession, accountNumber: String): MibIpsAccountInfo {
val body = FormBody.Builder().add("benefAccount", accountNumber).build()
val request = Request.Builder()
.url("$BASE_WV_URL/AjaxAlias/getIPSAccount")
.post(body)
.withWvHeaders(session)
.build()
return client.newCall(request).execute().use { response ->
val bodyStr = response.body?.string() ?: ""
val json = try { JSONObject(bodyStr) } catch (_: Exception) { null }
if (!response.isSuccessful || json == null || !json.optBoolean("success")) {
throw MibLookupException(
json?.optString("reasonText")?.trim()?.takeIf { it.isNotBlank() }
?: "Request failed (${response.code})"
)
}
MibIpsAccountInfo(
accountName = json.optString("accountName").trim(),
accountNumber = accountNumber,
bankId = json.optString("bankBic")
)
}
val accountNumber = match.optString("benefAccount")
// B40 reports MIB accounts either as "MIB" or by BIC; callers expect the BIC
val bankId = match.optString("bankCode").let { if (it == "MIB") "MADVMVMV" else it }
val currency = match.optString("transferCyDesc").takeIf { it == "MVR" || it == "USD" }
?: if (bankId == "MADVMVMV") "" else "MVR" // cross-bank lookups only resolve MVR accounts
return MibIpsAccountInfo(
accountName = match.optString("benefName").trim(),
accountNumber = accountNumber,
bankId = bankId,
currency = currency
)
}
companion object {
/** reasonCode for a wrong OTP, e.g. one from the previous window. */
const val REASON_INVALID_OTP = "213"
/** reasonCode for an OTP the server has already accepted once. */
const val REASON_OTP_ALREADY_USED = "707"
/** MIB internal: 17-digit account starting with 9. */
private fun lookupAccountName(session: MibSession, accountNumber: String): MibIpsAccountInfo {
val body = FormBody.Builder().add("accountNo", accountNumber).build()
val request = Request.Builder()
.url("$BASE_WV_URL/ajaxBeneficiary/getAccountName")
.post(body)
.withWvHeaders(session)
.build()
return client.newCall(request).execute().use { response ->
val bodyStr = response.body?.string() ?: ""
val json = try { JSONObject(bodyStr) } catch (_: Exception) { null }
if (!response.isSuccessful || json == null || !json.optBoolean("success")) {
throw MibLookupException(
json?.optString("reasonText")?.trim()?.takeIf { it.isNotBlank() }
?: "Request failed (${response.code})"
)
}
// accountName may be at root or inside a "data" object
val name = json.optString("accountName").takeIf { it.isNotBlank() }
?: json.optJSONObject("data")?.optString("accountName") ?: ""
MibIpsAccountInfo(
accountName = name.trim(),
accountNumber = accountNumber,
bankId = "MADVMVMV" // MIB
)
}
}
/** Favara alias: 7-digit shortcode (7/9 prefix), A-format ID, or email. */
private fun lookupAlias(session: MibSession, aliasName: String): MibIpsAccountInfo {
val body = FormBody.Builder().add("aliasName", aliasName).build()
val request = Request.Builder()
.url("$BASE_WV_URL/AjaxAlias/getAlias")
.post(body)
.withWvHeaders(session)
.build()
return client.newCall(request).execute().use { response ->
val bodyStr = response.body?.string() ?: ""
val json = try { JSONObject(bodyStr) } catch (_: Exception) { null }
if (!response.isSuccessful || json == null || !json.optBoolean("success")) {
throw MibLookupException(
json?.optString("reasonText")?.trim()?.takeIf { it.isNotBlank() }
?: "Request failed (${response.code})"
)
}
val data = json.getJSONObject("data")
val cdtrAcct = data.getJSONObject("CdtrAcct")
MibIpsAccountInfo(
accountName = data.optString("BfyNm").trim(),
accountNumber = cdtrAcct.optString("Acct"),
bankId = cdtrAcct.optString("FinInstnId")
)
}
}
}
@@ -1,90 +0,0 @@
package sh.sar.basedbank.api.ooredoo
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import sh.sar.basedbank.api.models.BankServerException
import java.math.BigDecimal
import java.math.RoundingMode
import java.util.Locale
import java.util.concurrent.TimeUnit
/**
* Ooredoo prepaid recharge (Raastas) and bill payment through the ooredoo.mv Quick Pay pages,
* paid by card on BML's merchant gateway. Ooredoo only creates the order; the money moves on the
* BML Merchant Services transaction it hands back, which is paid like any card-only BML merchant
* link. See `docs/ooredooapi/02-raastas.md` and `docs/ooredooapi/03-bill-pay.md`.
*
* Every call blocks, so run it on an IO thread.
*/
class OoredooPaymentClient {
private val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
/**
* Creates the recharge order for [number] (7 digits) and the BML transaction paying for it.
* [amount] is what the number is credited, in whole MVR; the card pays [charged], which is
* that plus GST. Returns the 24-hex BML transaction id. Throws with Ooredoo's wording when
* the order is refused.
*/
fun createRaastasTransaction(number: String, amount: Int, charged: BigDecimal): String =
createOrder(number, charged, amount.toString(), transType = "recharge", serviceType = "prepaid")
/**
* Creates the bill payment order for postpaid [number] (7 digits) and the BML transaction
* paying for it. [amount] is MVR, up to 2 decimal places; no GST. Returns the 24-hex BML
* transaction id. Throws with Ooredoo's wording when the order is refused.
*/
fun createBillPayTransaction(number: String, amount: BigDecimal): String =
createOrder(number, amount, money(amount), transType = "billpay", serviceType = "Mobile")
/** `POST PaymentGateway/bml` — one call makes the order and its BML transaction. */
private fun createOrder(
number: String, charged: BigDecimal, amountWithoutGst: String, transType: String, serviceType: String,
): String {
val msisdn = "960$number"
val body = JSONObject()
.put("msisdn", msisdn)
.put("purchaseAmount", money(charged))
.put("amountWithoutGst", amountWithoutGst)
.put("receiverMsisdn", msisdn)
.put("transType", transType)
.put("serviceType", serviceType)
.put("serviceTypeDisplayName", "Mobile")
val text = client.newCall(
Request.Builder().url("$BASE/ooredoo-prod/PaymentGateway/bml")
.post(body.toString().toRequestBody(JSON))
.header("User-Agent", UA)
.header("Accept", "application/json")
.header("Origin", BASE)
.build()
).execute().use { r ->
if (r.code in 500..599) throw BankServerException("Ooredoo")
r.body?.string().orEmpty()
}
val obj = try { JSONObject(text) } catch (_: Exception) {
throw Exception("Unexpected response from Ooredoo")
}
if (obj.optString("status") != "OK" || obj.optString("code") != "2000") {
throw Exception(obj.optString("msg").ifBlank { "Ooredoo refused the payment" })
}
val data = obj.optJSONObject("data") ?: throw Exception("Ooredoo didn't create the order")
return TXN_URL.find(data.optString("bmlUrl"))?.groupValues?.get(1)
?: throw Exception("BML didn't create the transaction")
}
private fun money(amount: BigDecimal) =
String.format(Locale.US, "%.2f", amount.setScale(2, RoundingMode.HALF_UP))
companion object {
private const val BASE = "https://www.ooredoo.mv"
private const val UA = "Mozilla/5.0 (X11; Linux x86_64; rv:150.0) Gecko/20100101 Firefox/150.0"
private val JSON = "application/json".toMediaType()
private val TXN_URL = Regex("""transaction\.merchants\.bankofmaldives\.com\.mv/([0-9a-fA-F]{24})""")
}
}
@@ -1,185 +0,0 @@
package sh.sar.basedbank.nfc
import android.content.Intent
import android.nfc.cardemulation.HostApduService
import android.os.Bundle
import android.util.Log
import sh.sar.basedbank.api.bml.BmlWalletToken
/**
* HCE service that emulates a BML contactless payment card.
*
* Implements the minimal EMV mag-stripe contactless flow:
* SELECT PPSE → SELECT AID → GET PROCESSING OPTIONS → READ RECORD
*
* Each BmlWalletToken is single-use and is set via [setToken] before tapping.
* After READ RECORD is sent the [onTransactionComplete] callback fires.
*/
class BmlHostCardEmulatorService : HostApduService() {
private var gpoSent = false
override fun processCommandApdu(commandApdu: ByteArray?, extras: Bundle?): ByteArray {
if (commandApdu == null) return SW_UNKNOWN_ERROR
val apdu = Apdu(commandApdu)
if (apdu.isError) return apdu.errorResponse()
return when (apdu.ins) {
INS_SELECT -> handleSelect(apdu)
INS_GPO -> handleGpo()
INS_READ -> handleReadRecord()
else -> SW_INS_NOT_SUPPORTED
}
}
override fun onDeactivated(reason: Int) {
if (!gpoSent) onTransactionComplete?.invoke(false)
gpoSent = false
}
// ── APDU handlers ──────────────────────────────────────────────────────────
private fun handleSelect(apdu: Apdu): ByteArray {
val data = apdu.data ?: return SW_UNKNOWN_ERROR
if (data.contentEquals(PPSE_BYTES)) {
val token = activeToken ?: run { launchPromptActivity(); return SW_UNKNOWN_ERROR }
return hexToBytes(buildSelectPpseResponse(token.appCode, applicationLabel(token.appCode), "01"))
}
val token = activeToken ?: return SW_UNKNOWN_ERROR
return if (data.contentEquals(hexToBytes(token.appCode))) {
hexToBytes(buildSelectAidResponse(token.appCode, applicationLabel(token.appCode)))
} else {
SW_UNKNOWN_ERROR
}
}
private fun launchPromptActivity() {
val intent = Intent(applicationContext, BmlTapToPayActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
startActivity(intent)
}
private fun handleGpo(): ByteArray {
gpoSent = true
// AIP=0080 (mag-stripe mode), AFL=08010100 (SFI=1, record 1-1, offline 0)
val miscData = "008008010100"
val body = tlv("80", miscData)
return hexToBytes(body + SW_OK_HEX)
}
private fun handleReadRecord(): ByteArray {
val token = activeToken ?: return SW_UNKNOWN_ERROR
val track2 = buildTrack2(token)
val body = tlv("70", tlv("57", track2))
val response = hexToBytes(body + SW_OK_HEX)
onTransactionComplete?.invoke(true)
return response
}
// ── TLV / APDU response builders ───────────────────────────────────────────
private fun buildSelectPpseResponse(aid: String, label: String, priority: String): String {
val priorityTlv = tlv("87", priority) // tag 87
val aidTlv = tlv("4F", aid) // tag 4F (ADF Name)
val appEntry = tlv("61", aidTlv + priorityTlv) // tag 61
val ppseTlv = tlv("84", PPSE_HEX) // tag 84 (DF Name)
val inner = tlv("BF0C", appEntry) // tag BF0C
val propTemplate = tlv("A5", inner) // tag A5
val fci = tlv("6F", ppseTlv + propTemplate) // tag 6F
return fci + SW_OK_HEX
}
private fun buildSelectAidResponse(aid: String, label: String): String {
val aidTlv = tlv("84", aid) // tag 84
val labelTlv = tlv("50", asciiToHex(label)) // tag 50
val pdolTlv = tlv("9F38", "9F6602") // PDOL: TTQ 2 bytes
val propTemplate = tlv("A5", labelTlv + pdolTlv) // tag A5
val fci = tlv("6F", aidTlv + propTemplate) // tag 6F
return fci + SW_OK_HEX
}
private fun buildTrack2(token: BmlWalletToken): String {
var t2 = "${token.token}D${token.expiry}${token.serviceCode}${token.data}"
if (t2.length % 2 != 0) t2 += "F"
return t2
}
// ── Helpers ─────────────────────────────────────────────────────────────────
/** Build BER-TLV: tag (hex string, 1 or 2 bytes) + DER length + data (hex string). */
private fun tlv(tagHex: String, dataHex: String): String {
val lenBytes = dataHex.length / 2
val lenHex = when {
lenBytes <= 0x7F -> lenBytes.toHexByte()
lenBytes <= 0xFF -> "81" + lenBytes.toHexByte()
else -> "82" + (lenBytes shr 8).toHexByte() + (lenBytes and 0xFF).toHexByte()
}
return tagHex + lenHex + dataHex
}
private fun Int.toHexByte(): String = toString(16).padStart(2, '0').uppercase()
private fun asciiToHex(s: String): String =
s.toByteArray(Charsets.US_ASCII).joinToString("") { "%02X".format(it) }
private fun hexToBytes(hex: String): ByteArray {
val s = hex.uppercase()
return ByteArray(s.length / 2) { i ->
s.substring(i * 2, i * 2 + 2).toInt(16).toByte()
}
}
// ── APDU parser ─────────────────────────────────────────────────────────────
private inner class Apdu(raw: ByteArray) {
val isError: Boolean
val ins: Int
val data: ByteArray?
init {
if (raw.size < 5) {
isError = true; ins = -1; data = null
} else {
isError = false
ins = raw[1].toInt() and 0xFF
val lc = if (raw.size > 4) raw[4].toInt() and 0xFF else 0
data = if (lc > 0 && raw.size >= 5 + lc) raw.copyOfRange(5, 5 + lc) else null
}
}
fun errorResponse() = SW_UNKNOWN_ERROR
}
companion object {
private const val TAG = "BmlHCE"
private const val INS_SELECT = 0xA4
private const val INS_GPO = 0xA8
private const val INS_READ = 0xB2
private val PPSE_HEX = "325041592E5359532E4444463031" // "2PAY.SYS.DDF01"
private val PPSE_BYTES = byteArrayOf(
0x32,0x50,0x41,0x59,0x2E,0x53,0x59,0x53,0x2E,0x44,0x44,0x46,0x30,0x31
)
private const val SW_OK_HEX = "9000"
private val SW_UNKNOWN_ERROR = byteArrayOf(0x6F.toByte(), 0x00.toByte())
private val SW_INS_NOT_SUPPORTED = byteArrayOf(0x6D.toByte(), 0x00.toByte())
@Volatile var activeToken: BmlWalletToken? = null
@Volatile var onTransactionComplete: ((success: Boolean) -> Unit)? = null
fun setToken(token: BmlWalletToken) { activeToken = token }
fun clearToken() { activeToken = null }
fun applicationLabel(aidHex: String): String = when {
aidHex.startsWith("A0000000031010", ignoreCase = true) -> "VISA"
aidHex.startsWith("A0000000041010", ignoreCase = true) -> "MASTERCARD"
aidHex.startsWith("A000000025", ignoreCase = true) -> "AMEX"
else -> "BML"
}
}
}
@@ -1,20 +0,0 @@
package sh.sar.basedbank.nfc
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import sh.sar.basedbank.MainActivity
/**
* Fallback entry point — redirects to MainActivity which routes to the in-app tap-to-pay screen.
*/
class BmlTapToPayActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
startActivity(Intent(this, MainActivity::class.java).apply {
action = "sh.sar.basedbank.TAP_TO_PAY"
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
})
finish()
}
}
@@ -1,186 +0,0 @@
package sh.sar.basedbank.nfc
import android.nfc.Tag
import android.nfc.tech.IsoDep
import java.io.ByteArrayOutputStream
/**
* Minimal contactless EMV reader: selects the payment app, runs GPO and reads the
* AFL records until it finds the PAN (tag 5A / Track 2 tag 57) and expiry (5F24 / Track 2).
*/
object EmvCardReader {
/** [expiry] is "MM/YY". */
data class CardData(val pan: String, val expiry: String?)
private class Collected {
var pan: String? = null
var expiry: String? = null
val complete get() = pan != null && expiry != null
fun result() = pan?.let { CardData(it, expiry) }
}
/** Returns the card data, or null if the PAN couldn't be read. Blocking — call off the main thread. */
fun read(tag: Tag): CardData? {
val iso = IsoDep.get(tag) ?: return null
val c = Collected()
iso.use {
it.connect()
it.timeout = 5000
val aids = selectPpse(it).ifEmpty { KNOWN_AIDS }
for (aid in aids) {
val fci = transceive(it, selectApdu(aid)) ?: continue
val pdol = findTag(fci, 0x9F38)
val gpo = transceive(it, gpoApdu(pdol)) ?: continue
collect(gpo, c)
if (c.complete) return c.result()
// Format 1 (tag 80): AIP (2 bytes) + AFL. Format 2 (tag 77): AFL in tag 94.
val afl = findTag(gpo, 0x94)
?: findTag(gpo, 0x80)?.let { b -> if (b.size > 2) b.copyOfRange(2, b.size) else null }
?: continue
for (i in 0 until afl.size / 4) {
val sfi = (afl[i * 4].toInt() and 0xFF) shr 3
val first = afl[i * 4 + 1].toInt() and 0xFF
val last = afl[i * 4 + 2].toInt() and 0xFF
for (rec in first..last) {
val data = transceive(it, readRecordApdu(sfi, rec)) ?: continue
collect(data, c)
if (c.complete) return c.result()
}
}
if (c.pan != null) return c.result()
}
}
return c.result()
}
private val KNOWN_AIDS = listOf(
"A0000000031010", // Visa
"A0000000041010", // Mastercard
"A0000000043060", // Maestro
"A000000025010801", // Amex
"A0000003330101", // UnionPay
).map { hex(it) }
private fun selectPpse(iso: IsoDep): List<ByteArray> {
val resp = transceive(iso, selectApdu("2PAY.SYS.DDF01".toByteArray())) ?: return emptyList()
return findAllTags(resp, 0x4F)
}
private fun collect(data: ByteArray, c: Collected) {
findTag(data, 0x5A)?.let { c.pan = c.pan ?: toHex(it).trimEnd('F') }
findTag(data, 0x57)?.let { raw ->
val t2 = toHex(raw)
c.pan = c.pan ?: t2.substringBefore('D')
// Track 2: PAN 'D' YYMM service-code ...
val yymm = t2.substringAfter('D', "").take(4)
if (c.expiry == null && yymm.length == 4) c.expiry = "${yymm.substring(2, 4)}/${yymm.substring(0, 2)}"
}
findTag(data, 0x5F24)?.let { raw ->
val yymmdd = toHex(raw)
if (yymmdd.length >= 4) c.expiry = "${yymmdd.substring(2, 4)}/${yymmdd.substring(0, 2)}"
}
}
private fun selectApdu(aid: ByteArray): ByteArray =
byteArrayOf(0x00, 0xA4.toByte(), 0x04, 0x00, aid.size.toByte()) + aid + byteArrayOf(0x00)
private fun readRecordApdu(sfi: Int, rec: Int): ByteArray =
byteArrayOf(0x00, 0xB2.toByte(), rec.toByte(), ((sfi shl 3) or 0x04).toByte(), 0x00)
/** Builds GPO with the PDOL filled in: sensible TTQ/country/currency/date, zeros otherwise. */
private fun gpoApdu(pdol: ByteArray?): ByteArray {
val out = ByteArrayOutputStream()
if (pdol != null) {
var i = 0
while (i < pdol.size) {
var tag = pdol[i].toInt() and 0xFF
i++
if (tag and 0x1F == 0x1F) {
do {
tag = (tag shl 8) or (pdol[i].toInt() and 0xFF)
} while (pdol[i++].toInt() and 0x80 != 0 && i < pdol.size)
}
if (i >= pdol.size) break
val len = pdol[i++].toInt() and 0xFF
val value = when (tag) {
0x9F66 -> hex("B620C000") // TTQ: contactless qVSDC, online capable
0x9F1A, 0x5F2A -> hex("0462") // Maldives / MVR
0x9A -> hex("260101")
0x9C -> hex("00")
0x9F37 -> hex("12345678")
else -> ByteArray(len)
}
out.write(value.copyOf(len))
}
}
val pdolData = out.toByteArray()
val body = byteArrayOf(0x83.toByte(), pdolData.size.toByte()) + pdolData
return byteArrayOf(0x80.toByte(), 0xA8.toByte(), 0x00, 0x00, body.size.toByte()) + body + byteArrayOf(0x00)
}
/** Sends an APDU, returning the response data on 9000 (following 61xx / 6Cxx), else null. */
private fun transceive(iso: IsoDep, apdu: ByteArray): ByteArray? {
var resp = iso.transceive(apdu)
if (resp.size < 2) return null
var sw1 = resp[resp.size - 2].toInt() and 0xFF
if (sw1 == 0x6C) {
val retry = apdu.copyOf()
retry[retry.size - 1] = resp[resp.size - 1]
resp = iso.transceive(retry)
sw1 = resp[resp.size - 2].toInt() and 0xFF
}
if (sw1 == 0x61) {
resp = iso.transceive(byteArrayOf(0x00, 0xC0.toByte(), 0x00, 0x00, resp[resp.size - 1]))
sw1 = resp[resp.size - 2].toInt() and 0xFF
}
val sw2 = resp[resp.size - 1].toInt() and 0xFF
return if (sw1 == 0x90 && sw2 == 0x00) resp.copyOf(resp.size - 2) else null
}
// ── BER-TLV ──────────────────────────────────────────────────────────────
private fun findTag(data: ByteArray, target: Int): ByteArray? = findAllTags(data, target).firstOrNull()
private fun findAllTags(data: ByteArray, target: Int): List<ByteArray> {
val found = mutableListOf<ByteArray>()
walk(data, 0, data.size, target, found)
return found
}
private fun walk(data: ByteArray, start: Int, end: Int, target: Int, found: MutableList<ByteArray>) {
var i = start
while (i < end) {
val b0 = data[i].toInt() and 0xFF
if (b0 == 0x00 || b0 == 0xFF) { i++; continue } // padding
val constructed = b0 and 0x20 != 0
var tag = b0
i++
if (b0 and 0x1F == 0x1F) {
while (i < end) {
val b = data[i++].toInt() and 0xFF
tag = (tag shl 8) or b
if (b and 0x80 == 0) break
}
}
if (i >= end) return
var len = data[i++].toInt() and 0xFF
if (len and 0x80 != 0) {
val n = len and 0x7F
len = 0
repeat(n) { if (i < end) len = (len shl 8) or (data[i++].toInt() and 0xFF) }
}
if (len < 0 || i + len > end) return
if (tag == target) found.add(data.copyOfRange(i, i + len))
if (constructed) walk(data, i, i + len, target, found)
i += len
}
}
private fun hex(s: String): ByteArray =
ByteArray(s.length / 2) { s.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
private fun toHex(b: ByteArray): String = b.joinToString("") { "%02X".format(it) }
}
@@ -1,174 +0,0 @@
package sh.sar.basedbank.service
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.os.IBinder
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import sh.sar.basedbank.BasedBankApp
import sh.sar.basedbank.R
import sh.sar.basedbank.api.bml.BmlNotificationsClient
import sh.sar.basedbank.api.mib.MibActivityHistoryClient
import sh.sar.basedbank.ui.home.AppNotification
import sh.sar.basedbank.util.NotificationsCache
import java.util.concurrent.atomic.AtomicInteger
class NotificationPollingService : Service() {
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
private val app get() = application as BasedBankApp
private val notifIdCounter = AtomicInteger(2000)
override fun onBind(intent: Intent?): IBinder? = null
override fun onCreate() {
super.onCreate()
createChannels()
startForeground(SERVICE_NOTIF_ID, buildServiceNotification())
startPolling()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int = START_STICKY
override fun onDestroy() {
scope.cancel()
super.onDestroy()
}
private fun startPolling() {
scope.launch {
while (isActive) {
runCatching { poll() }
delay(POLL_INTERVAL_MS)
}
}
}
private suspend fun poll() {
pollBml()
pollMib()
}
private suspend fun pollBml() {
val sessions = app.bmlSessions.toMap()
if (sessions.isEmpty()) return
val client = BmlNotificationsClient()
sessions.forEach { (loginId, session) ->
val result = try { client.fetchNotifications(session, loginId, page = 1) }
catch (_: Exception) { return@forEach }
if (result.items.isEmpty()) return@forEach
val cached = NotificationsCache.loadBml(this@NotificationPollingService, loginId)
if (cached.isEmpty()) {
NotificationsCache.saveBml(this@NotificationPollingService, loginId, result.items)
return@forEach
}
val cachedIds = cached.map { it.id }.toSet()
val newItems = result.items.filter { it.id !in cachedIds }
if (newItems.isNotEmpty()) {
NotificationsCache.saveBml(this@NotificationPollingService, loginId, result.items)
val channelId = ensureLoginChannel("BML", loginId)
newItems.forEach { postBankNotification(it, channelId) }
}
}
}
private suspend fun pollMib() {
val sessions = app.mibSessions.toMap()
if (sessions.isEmpty()) return
val client = MibActivityHistoryClient()
sessions.forEach { (loginId, session) ->
val result = try { client.fetchActivity(session, loginId, 1, 100) }
catch (_: Exception) { return@forEach }
val readIds = NotificationsCache.getMibReadIds(this@NotificationPollingService)
val cached = NotificationsCache.loadMib(this@NotificationPollingService, loginId, readIds)
if (cached.isEmpty()) {
NotificationsCache.saveMib(this@NotificationPollingService, loginId, result.items)
return@forEach
}
val cachedIds = cached.map { it.id }.toSet()
val newItems = result.items.filter { it.id !in cachedIds }
if (newItems.isNotEmpty()) {
val all = (cached + newItems).sortedByDescending { it.timestampMs }
NotificationsCache.saveMib(this@NotificationPollingService, loginId, all)
val channelId = ensureLoginChannel("MIB", loginId)
newItems.forEach { postBankNotification(it, channelId) }
}
}
}
private fun ensureLoginChannel(bank: String, loginId: String): String {
val channelId = "bank_${bank.lowercase()}_$loginId"
val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
if (nm.getNotificationChannel(channelId) == null) {
val profileName = when (bank) {
"BML" -> app.bmlProfilesMap[loginId]?.firstOrNull()?.name
"MIB" -> app.mibProfilesMap[loginId]?.firstOrNull()?.name
else -> null
} ?: loginId
nm.createNotificationChannel(
NotificationChannel(channelId, "$bank · $profileName", NotificationManager.IMPORTANCE_DEFAULT)
)
}
return channelId
}
private fun postBankNotification(notif: AppNotification, channelId: String) {
val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
val pi = PendingIntent.getActivity(
this, 0,
packageManager.getLaunchIntentForPackage(packageName),
PendingIntent.FLAG_IMMUTABLE
)
val n = Notification.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_bell)
.setContentTitle(notif.title)
.setContentText(notif.message)
.setContentIntent(pi)
.setAutoCancel(true)
.build()
nm.notify(notifIdCounter.getAndIncrement(), n)
}
private fun buildServiceNotification(): Notification {
val pi = PendingIntent.getActivity(
this, 0,
packageManager.getLaunchIntentForPackage(packageName),
PendingIntent.FLAG_IMMUTABLE
)
return Notification.Builder(this, CHANNEL_SERVICE)
.setSmallIcon(R.drawable.ic_bell)
.setContentTitle(getString(R.string.notif_service_title))
.setContentText(getString(R.string.notif_service_desc))
.setContentIntent(pi)
.setOngoing(true)
.build()
}
private fun createChannels() {
val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
nm.createNotificationChannel(
NotificationChannel(
CHANNEL_SERVICE,
getString(R.string.notif_channel_service),
NotificationManager.IMPORTANCE_MIN
).apply { setShowBadge(false) }
)
}
companion object {
private const val POLL_INTERVAL_MS = 30_000L
private const val SERVICE_NOTIF_ID = 1001
const val CHANNEL_SERVICE = "notif_polling_service"
}
}
@@ -27,10 +27,9 @@ class AccountHistoryAdapter(
private sealed class Item {
data class DateHeader(val label: String) : Item()
data class Trx(val transaction: BankTransaction, val showDate: Boolean = false) : Item()
data class Trx(val transaction: BankTransaction) : Item()
}
private val pendingItems = mutableListOf<Item>()
private val displayItems = mutableListOf<Item>()
private var lastInsertedDateKey = ""
private val imageCache = mutableMapOf<String, Bitmap>()
@@ -38,22 +37,15 @@ class AccountHistoryAdapter(
var onImageNeeded: ((counterpartyName: String) -> Unit)? = null
var onIconUrlNeeded: ((url: String) -> Unit)? = null
var onTransferClick: ((BankAccount) -> Unit)? = null
var onDefaultToggle: ((Boolean) -> Unit)? = null
private var hideAmounts: Boolean = false
var showDefaultToggle: Boolean = false
set(value) { if (field == value) return; field = value; notifyItemChanged(0) }
var isDefaultAccount: Boolean = false
set(value) { if (field == value) return; field = value; notifyItemChanged(0) }
fun setHideAmounts(hide: Boolean) {
if (hideAmounts == hide) return
hideAmounts = hide
notifyItemChanged(0) // refresh header card
for (i in pendingItems.indices) {
if (pendingItems[i] is Item.Trx) notifyItemChanged(i + 1)
}
// refresh all transaction rows
for (i in displayItems.indices) {
if (displayItems[i] is Item.Trx) notifyItemChanged(1 + pendingItems.size + i)
if (displayItems[i] is Item.Trx) notifyItemChanged(i + 1)
}
}
@@ -61,7 +53,7 @@ class AccountHistoryAdapter(
imageCache[counterpartyName] = bitmap
displayItems.forEachIndexed { i, item ->
if (item is Item.Trx && item.transaction.counterpartyName == counterpartyName)
notifyItemChanged(1 + pendingItems.size + i)
notifyItemChanged(i + 1) // +1 for account header at position 0
}
}
@@ -69,28 +61,10 @@ class AccountHistoryAdapter(
iconUrlCache[url] = bitmap
displayItems.forEachIndexed { i, item ->
if (item is Item.Trx && item.transaction.iconUrl == url)
notifyItemChanged(1 + pendingItems.size + i)
notifyItemChanged(i + 1) // +1 for account header at position 0
}
}
fun setPendingTransactions(transactions: List<BankTransaction>) {
setLeadingSections(listOf("Pending" to transactions))
}
/**
* Sets one or more labeled sections that render above the main statement list
* (e.g. card "Outstanding" + "Unbilled"). Empty sections are skipped.
*/
fun setLeadingSections(sections: List<Pair<String, List<BankTransaction>>>) {
pendingItems.clear()
for ((label, transactions) in sections) {
if (transactions.isEmpty()) continue
pendingItems.add(Item.DateHeader(label))
for (trx in transactions) pendingItems.add(Item.Trx(trx, showDate = true))
}
notifyDataSetChanged()
}
private var _showLoadingFooter = false
var showLoadingFooter: Boolean
get() = _showLoadingFooter
@@ -148,24 +122,18 @@ class AccountHistoryAdapter(
displayItems.add(Item.Trx(trx))
}
val added = displayItems.size - oldCount
if (added > 0) notifyItemRangeInserted(1 + pendingItems.size + oldCount, added)
if (added > 0) notifyItemRangeInserted(1 + oldCount, added) // +1 for account header
}
// Position 0 = account header card
// Positions 1..pendingItems.size = pending header + pending transactions
// Positions 1+pendingItems.size..1+pendingItems.size+displayItems.size = date headers + transactions
// Positions 1..displayItems.size = date headers + transactions
// Last position = loading footer when showLoadingFooter = true
override fun getItemCount() = 1 + pendingItems.size + displayItems.size + if (_showLoadingFooter) 1 else 0
private fun itemAt(position: Int): Item {
val idx = position - 1
return if (idx < pendingItems.size) pendingItems[idx] else displayItems[idx - pendingItems.size]
}
override fun getItemCount() = 1 + displayItems.size + if (_showLoadingFooter) 1 else 0
override fun getItemViewType(position: Int) = when {
position == 0 -> TYPE_HEADER
_showLoadingFooter && position == itemCount - 1 -> TYPE_LOADING
else -> when (itemAt(position)) {
else -> when (displayItems[position - 1]) {
is Item.DateHeader -> TYPE_DATE_HEADER
is Item.Trx -> TYPE_TRANSACTION
}
@@ -184,11 +152,8 @@ class AccountHistoryAdapter(
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is HeaderVH -> holder.bind(display)
is DateHeaderVH -> holder.bind((itemAt(position) as Item.DateHeader).label)
is TransactionVH -> {
val item = itemAt(position) as Item.Trx
holder.bind(item.transaction, item.showDate)
}
is DateHeaderVH -> holder.bind((displayItems[position - 1] as Item.DateHeader).label)
is TransactionVH -> holder.bind((displayItems[position - 1] as Item.Trx).transaction)
else -> Unit
}
}
@@ -209,20 +174,6 @@ class AccountHistoryAdapter(
b.llHeaderBlocked.visibility = View.GONE
}
b.btnHeaderTransfer.setOnClickListener { onTransferClick?.invoke(account) }
if (showDefaultToggle) {
b.dividerDefaultAccount.visibility = View.VISIBLE
b.llDefaultAccountRow.visibility = View.VISIBLE
b.switchDefaultAccount.setOnCheckedChangeListener(null)
b.switchDefaultAccount.isChecked = isDefaultAccount
b.switchDefaultAccount.setOnCheckedChangeListener { _, checked ->
isDefaultAccount = checked
onDefaultToggle?.invoke(checked)
}
} else {
b.dividerDefaultAccount.visibility = View.GONE
b.llDefaultAccountRow.visibility = View.GONE
}
}
}
@@ -233,7 +184,7 @@ class AccountHistoryAdapter(
inner class TransactionVH(private val b: ItemTransactionBinding) :
RecyclerView.ViewHolder(b.root) {
fun bind(trx: BankTransaction, showDate: Boolean = false) {
fun bind(trx: BankTransaction) {
val isCredit = trx.amount >= 0
val color = sourceColor(trx.source)
val name = trx.counterpartyName ?: trx.description
@@ -269,7 +220,7 @@ class AccountHistoryAdapter(
b.tvCounterparty.visibility = View.GONE
}
b.tvDate.text = if (showDate) formatDateOnly(trx.date) else formatTime(trx.date)
b.tvDate.text = formatTime(trx.date)
if (hideAmounts) {
b.tvAmount.text = "${trx.currency} ••••••"
@@ -316,7 +267,6 @@ class AccountHistoryAdapter(
private val MIB_FMT = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US)
private val BML_FMT = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.US)
private val DATE_HEADER_FMT = SimpleDateFormat("MMMM d, yyyy", Locale.getDefault())
private val DATE_ONLY_FMT = SimpleDateFormat("MMM d, yyyy", Locale.getDefault())
private val TIME_FMT = SimpleDateFormat("h:mm a", Locale.getDefault())
private val FULL_DATE_FMT = SimpleDateFormat("MMM d, yyyy · h:mm a", Locale.getDefault())
@@ -338,11 +288,6 @@ class AccountHistoryAdapter(
return DATE_HEADER_FMT.format(date)
}
fun formatDateOnly(raw: String): String {
val date = parseDate(raw) ?: return raw.take(10)
return DATE_ONLY_FMT.format(date)
}
fun formatTime(raw: String): String {
val date = parseDate(raw) ?: return ""
return TIME_FMT.format(date)
@@ -23,16 +23,12 @@ import kotlinx.coroutines.withContext
import sh.sar.basedbank.BasedBankApp
import sh.sar.basedbank.R
import sh.sar.basedbank.api.models.BankAccount
import sh.sar.basedbank.api.models.BankServerException
import sh.sar.basedbank.api.bml.BmlHistoryClient
import sh.sar.basedbank.api.mib.MibContactsClient
import sh.sar.basedbank.api.models.BankTransaction
import sh.sar.basedbank.api.mib.TransactionCache
import sh.sar.basedbank.databinding.FragmentAccountHistoryBinding
import sh.sar.basedbank.util.AccountHistoryParser
import sh.sar.basedbank.util.AccountListParser
import sh.sar.basedbank.util.ContactImageCache
import sh.sar.basedbank.util.CredentialStore
import sh.sar.basedbank.util.HistoryFetcher
import sh.sar.basedbank.util.MerchantIconCache
@@ -83,24 +79,6 @@ class AccountHistoryFragment : Fragment() {
}
adapter.setHideAmounts(viewModel.hideAmounts.value ?: false)
viewModel.hideAmounts.observe(viewLifecycleOwner) { adapter.setHideAmounts(it) }
// Show default account toggle only for non-card, non-M-Faisa accounts.
// M-Faisa pockets (including PayPal) cannot be set as the default transfer/QR account.
val isCard = AccountListParser.from(account)?.isCard ?: false
if (!isCard && account.bank != "MFAISA") {
val store = CredentialStore(requireContext())
adapter.showDefaultToggle = true
adapter.isDefaultAccount = store.getDefaultAccountNumber() == account.accountNumber
adapter.onDefaultToggle = { isChecked ->
if (isChecked) {
store.setDefaultAccountNumber(account.accountNumber)
} else {
if (store.getDefaultAccountNumber() == account.accountNumber) {
store.setDefaultAccountNumber(null)
}
}
}
}
binding.recyclerView.layoutManager = LinearLayoutManager(requireContext())
binding.recyclerView.adapter = adapter
@@ -140,7 +118,6 @@ class AccountHistoryFragment : Fragment() {
}
(activity as? HomeActivity)?.setRefreshing(true)
loadNextPage()
loadPendingTransactions()
binding.swipeRefresh.setOnRefreshListener {
if (isLoading) {
@@ -153,12 +130,7 @@ class AccountHistoryFragment : Fragment() {
override fun onResume() {
super.onResume()
if (::account.isInitialized) {
requireActivity().title = account.accountBriefName
if (adapter.showDefaultToggle) {
adapter.isDefaultAccount = CredentialStore(requireContext()).getDefaultAccountNumber() == account.accountNumber
}
}
if (::account.isInitialized) requireActivity().title = account.accountBriefName
}
private fun filterAndDisplay() {
@@ -177,17 +149,9 @@ class AccountHistoryFragment : Fragment() {
pendingIconUrls.clear()
firstPageDone = false
fetcher = HistoryFetcher(account)
// Restore cache immediately so data stays visible while refreshing
val cached = TransactionCache.load(requireContext(), account.accountNumber)
if (cached.isNotEmpty()) {
allTransactions.addAll(cached)
filterAndDisplay()
} else {
adapter.setTransactions(emptyList())
binding.emptyView.visibility = View.GONE
}
adapter.setTransactions(emptyList())
binding.emptyView.visibility = View.GONE
loadNextPage()
loadPendingTransactions()
}
private fun loadNextPage() {
@@ -201,20 +165,9 @@ class AccountHistoryFragment : Fragment() {
val app = requireActivity().application as BasedBankApp
lifecycleScope.launch {
val transactions = try {
fetcher.fetchNextPage(app, pageSize)
} catch (e: java.io.IOException) {
(activity as? HomeActivity)?.showConnectivityBanner(getString(R.string.connectivity_no_internet))
null
} catch (e: BankServerException) {
(activity as? HomeActivity)?.showConnectivityBanner(getString(R.string.connectivity_server_error, e.bankName))
null
} catch (_: Exception) {
null
}
val transactions = fetcher.fetchNextPage(app, pageSize)
isLoading = false
if (_binding == null) return@launch
if (!firstPageDone) {
firstPageDone = true
@@ -222,20 +175,6 @@ class AccountHistoryFragment : Fragment() {
binding.swipeRefresh.isRefreshing = false
}
if (transactions == null) {
adapter.showLoadingFooter = false
if (allTransactions.isEmpty()) binding.emptyView.visibility = View.VISIBLE
return@launch
}
(activity as? HomeActivity)?.hideConnectivityBanner()
fetcher.takeCardPendingSections()?.let { (outstanding, unbilled) ->
adapter.setLeadingSections(listOf(
"Outstanding" to outstanding,
"Unbilled" to unbilled
))
}
if (transactions.isNotEmpty()) {
val existingIds = allTransactions.map { it.id }.toHashSet()
val newOnes = transactions.filter { it.id !in existingIds }
@@ -261,26 +200,6 @@ class AccountHistoryFragment : Fragment() {
}
}
private fun loadPendingTransactions() {
if (account.bank != "BML" || account.profileType != "BML") return
val app = requireActivity().application as BasedBankApp
val session = app.bmlSessionFor(account) ?: return
viewLifecycleOwner.lifecycleScope.launch {
try {
val pending = withContext(Dispatchers.IO) {
BmlHistoryClient().fetchPendingHistory(
session = session,
accountId = account.internalId,
accountDisplayName = account.accountBriefName,
accountNumber = account.accountNumber
)
}
if (_binding == null) return@launch
adapter.setPendingTransactions(pending)
} catch (_: Exception) { }
}
}
private fun loadContactImage(name: String) {
if (!pendingImageNames.add(name)) return
val contact = viewModel.contacts.value?.firstOrNull { it.benefNickName == name } ?: return
@@ -294,7 +213,7 @@ class AccountHistoryFragment : Fragment() {
val sess = app.anyMibSession() ?: return
viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) {
try {
val base64 = app.anyMibFlow()?.let { MibContactsClient(it) }?.fetchProfileImageBase64(sess, hash) ?: return@launch
val base64 = MibContactsClient().fetchProfileImageBase64(sess, hash) ?: return@launch
val bytes = Base64.decode(base64, Base64.DEFAULT)
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return@launch
ContactImageCache.save(requireContext(), hash, bitmap)
@@ -3,13 +3,11 @@ package sh.sar.basedbank.ui.home
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.graphics.Bitmap
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import sh.sar.basedbank.R
import sh.sar.basedbank.api.models.BankAccount
import sh.sar.basedbank.databinding.ItemAccountBinding
import sh.sar.basedbank.databinding.ItemCardBinding
@@ -19,11 +17,7 @@ import sh.sar.basedbank.util.AccountListParser
class AccountsAdapter(
accounts: List<BankAccount>,
private val onAccountClick: (BankAccount) -> Unit = {},
/** Optional loader for MIB per-profile images: (hash, onLoaded) */
private val profileImageLoader: ((String, (Bitmap) -> Unit) -> Unit)? = null,
/** Optional loader for local (BML/Fahipay) profile images: (loginTag, profileId, onLoaded) */
private val localProfileImageLoader: ((String, String, (Bitmap) -> Unit) -> Unit)? = null
private val onAccountClick: (BankAccount) -> Unit = {}
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
var onTransferClick: ((BankAccount) -> Unit)? = null
@@ -75,12 +69,10 @@ class AccountsAdapter(
"BML" -> "Bank of Maldives"
"FAHIPAY" -> "Fahipay"
"MIB" -> "Maldives Islamic Bank"
"MFAISA" -> if (account.profileType == "MFAISA_PAYPAL") "PayPal · M-Faisa" else "M-Faisa"
else -> account.bank
}
val profileLabel = when (account.bank) {
"MIB" -> account.productCode.ifBlank { account.profileName }
"MFAISA" -> "" // bank-level grouping is already specific (M-Faisa / PayPal · M-Faisa)
else -> account.profileName
}
return if (profileLabel.isNotBlank()) "$profileLabel · $bankName" else bankName
@@ -120,52 +112,17 @@ class AccountsAdapter(
private inner class AccountViewHolder(private val binding: ItemAccountBinding) :
RecyclerView.ViewHolder(binding.root) {
private var boundHash: String? = null
fun bind(account: BankAccount, display: AccountListDisplay) {
binding.tvAccountName.text = display.name
binding.tvAccountNumber.text = display.number
binding.tvAccountType.text = display.typeLabel
binding.tvBalance.text = if (hideAmounts) maskAmount(display.balance) else display.balance
val blocked = display.blockedBalance
if (blocked != null) {
val shown = if (hideAmounts) maskAmount(blocked) else blocked
binding.tvBlocked.text = binding.root.context.getString(R.string.account_blocked_label, shown)
binding.tvBlocked.visibility = View.VISIBLE
} else {
binding.tvBlocked.visibility = View.GONE
}
binding.btnTransfer.setOnClickListener { onTransferClick?.invoke(account) }
binding.root.setOnClickListener { onAccountClick(account) }
binding.root.setOnLongClickListener {
copyToClipboard(it.context, display.number)
true
}
val staticLogo = when (account.bank) {
"BML" -> R.drawable.bml_logo_vector
"FAHIPAY" -> R.drawable.fahipay_logo
"MIB" -> R.drawable.mib_logo
"MFAISA" -> R.drawable.ooredoo_logo
else -> null
}
if (staticLogo != null) binding.ivBankLogo.setImageResource(staticLogo)
else binding.ivBankLogo.setImageDrawable(null)
val hash = account.profileImageHash
boundHash = hash
when {
account.bank == "MIB" && hash != null && profileImageLoader != null -> {
profileImageLoader.invoke(hash) { bitmap ->
if (boundHash == hash) binding.ivBankLogo.setImageBitmap(bitmap)
}
}
(account.bank == "BML" || account.bank == "FAHIPAY") && localProfileImageLoader != null -> {
localProfileImageLoader.invoke(account.loginTag, account.profileId) { bitmap ->
if (boundHash == hash) binding.ivBankLogo.setImageBitmap(bitmap)
}
}
}
}
}
@@ -1,9 +1,6 @@
package sh.sar.basedbank.ui.home
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Base64
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
@@ -11,15 +8,9 @@ import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import sh.sar.basedbank.BasedBankApp
import sh.sar.basedbank.R
import sh.sar.basedbank.databinding.FragmentAccountsBinding
import sh.sar.basedbank.util.ProfileImageStore
class AccountsFragment : Fragment() {
@@ -27,7 +18,6 @@ class AccountsFragment : Fragment() {
private val binding get() = _binding!!
private val viewModel: HomeViewModel by activityViewModels()
private lateinit var adapter: AccountsAdapter
private val profileImageCache = mutableMapOf<String, Bitmap>()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentAccountsBinding.inflate(inflater, container, false)
@@ -35,49 +25,9 @@ class AccountsFragment : Fragment() {
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val app = requireActivity().application as BasedBankApp
adapter = AccountsAdapter(
accounts = emptyList(),
onAccountClick = { account ->
(activity as? HomeActivity)?.showWithBackStack(AccountHistoryFragment.newInstance(account))
},
profileImageLoader = { hash, onLoaded ->
profileImageCache[hash]?.let { onLoaded(it); return@AccountsAdapter }
viewLifecycleOwner.lifecycleScope.launch {
val bitmap = withContext(Dispatchers.IO) {
try {
val session = app.anyMibSession() ?: return@withContext null
val b64 = app.anyMibFlow()?.fetchProfileImage(session, hash) ?: return@withContext null
val bytes = Base64.decode(b64, Base64.DEFAULT)
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
} catch (_: Exception) { null }
}
if (bitmap != null) {
profileImageCache[hash] = bitmap
onLoaded(bitmap)
}
}
},
localProfileImageLoader = { loginTag, profileId, onLoaded ->
val cacheKey = "$loginTag|$profileId"
profileImageCache[cacheKey]?.let { onLoaded(it); return@AccountsAdapter }
viewLifecycleOwner.lifecycleScope.launch {
val bitmap = withContext(Dispatchers.IO) {
val ctx = requireContext()
if (loginTag.startsWith("bml_") && profileId.isNotBlank()) {
ProfileImageStore.load(ctx, ProfileImageStore.bmlKey(profileId))
} else if (loginTag.startsWith("fahipay_")) {
val loginId = ProfileImageStore.loginIdFromTag(loginTag)
ProfileImageStore.load(ctx, ProfileImageStore.fahipayKey(loginId))
} else null
}
if (bitmap != null) {
profileImageCache[cacheKey] = bitmap
onLoaded(bitmap)
}
}
}
)
adapter = AccountsAdapter(emptyList()) { account ->
(activity as? HomeActivity)?.showWithBackStack(AccountHistoryFragment.newInstance(account))
}
adapter.onTransferClick = { account ->
(activity as? HomeActivity)?.navigateTo(R.id.nav_transfer, TransferFragment.newInstanceFrom(account))
}
@@ -93,10 +43,7 @@ class AccountsFragment : Fragment() {
insets
}
viewModel.accounts.observe(viewLifecycleOwner) {
adapter.updateAccounts(it)
binding.emptyView.visibility = if (it.isEmpty()) View.VISIBLE else View.GONE
}
viewModel.accounts.observe(viewLifecycleOwner) { adapter.updateAccounts(it) }
viewModel.hideAmounts.observe(viewLifecycleOwner) { adapter.setHideAmounts(it) }
binding.swipeRefresh.setOnRefreshListener {
@@ -18,13 +18,11 @@ import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.activityViewModels
import androidx.swiperefreshlayout.widget.CircularProgressDrawable
import androidx.lifecycle.lifecycleScope
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import sh.sar.basedbank.util.ContactDisplay
import sh.sar.basedbank.util.ContactImageCache
import sh.sar.basedbank.util.ContactsCache
import sh.sar.basedbank.util.CredentialStore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@@ -34,7 +32,6 @@ import sh.sar.basedbank.R
import sh.sar.basedbank.api.bml.BmlAccountValidation
import sh.sar.basedbank.api.bml.BmlContactsClient
import sh.sar.basedbank.api.bml.BmlValidateClient
import sh.sar.basedbank.api.models.BankContact
import sh.sar.basedbank.api.models.BankContactCategory
import sh.sar.basedbank.api.mib.MibContactsClient
import sh.sar.basedbank.api.mib.MibProfile
@@ -70,9 +67,6 @@ class AddContactSheetFragment : BottomSheetDialogFragment() {
private var selectedCategoryId: String = "0"
private var categories: List<BankContactCategory> = emptyList()
// Set when editing an existing MIB contact instead of adding a new one
private var editContact: BankContact? = null
private val imagePicker = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
uri ?: return@registerForActivityResult
encodeImage(uri)
@@ -95,94 +89,6 @@ class AddContactSheetFragment : BottomSheetDialogFragment() {
categories = cats.filter { it.id != "BML" }
if (selectedDest?.isBml == false) setupCategoryDropdown()
}
if (!applyEditArgs()) applyPrefillArgs()
}
/** Switches the sheet into edit mode when opened via [forEdit]. Returns true if it did. */
private fun applyEditArgs(): Boolean {
val args = arguments ?: return false
val benefNo = args.getString(ARG_EDIT_BENEF_NO) ?: return false
val profileId = args.getString(ARG_EDIT_PROFILE_ID) ?: return false
val contact = viewModel.contacts.value?.firstOrNull { it.benefNo == benefNo && it.profileId == profileId }
val dest = destinations.firstOrNull { !it.isBml && it.mibProfile?.profileId == profileId }
if (contact == null || dest == null) {
Toast.makeText(requireContext(), R.string.contact_save_failed, Toast.LENGTH_SHORT).show()
dismiss()
return true
}
editContact = contact
selectedCategoryId = contact.benefCategoryId
categories = viewModel.contactCategories.value?.filter { it.id != "BML" } ?: emptyList()
binding.tvTitle.setText(R.string.contact_edit_title)
selectedDest = dest
binding.actvDestination.setText(dest.label, false)
binding.tilDestination.isEnabled = false
binding.actvGroup.setText(
categories.firstOrNull { it.id == contact.benefCategoryId }?.categoryName
?: getString(R.string.contact_no_group), false
)
updateMibOnlyVisibility()
mibLookupAccount = contact.benefAccount
binding.tvResultName.text = contact.benefName
binding.tvResultBank.text = "${contact.benefBankName} · ${contact.benefAccount}"
val photo = contact.customerImgHash?.let { ContactImageCache.load(requireContext(), it) }
binding.ivResultAvatar.setImageBitmap(photo ?: makeInitialsBitmap(contact.benefName, contact.bankColor))
if (photo != null) binding.ivContactImage.setImageBitmap(photo)
binding.cardResult.visibility = View.VISIBLE
binding.tilAccount.visibility = View.GONE
binding.btnClearResult.visibility = View.GONE
binding.etAlias.setText(contact.benefNickName)
binding.etCurrency.setText(contact.transferCyDesc)
updateSaveState()
return true
}
private fun applyPrefillArgs() {
val args = arguments ?: return
val bmlProfileId = args.getString(ARG_BML_PROFILE_ID)
val accountNumber = args.getString(ARG_ACCOUNT_NUMBER)
val recipientName = args.getString(ARG_RECIPIENT_NAME)
val currency = args.getString(ARG_CURRENCY)
if (bmlProfileId != null) {
val match = destinations.firstOrNull { it.isBml && it.bmlLoginId == bmlProfileId }
if (match != null) {
selectedDest = match
binding.actvDestination.setText(match.label, false)
updateMibOnlyVisibility()
}
}
if (accountNumber != null) {
binding.etAccount.setText(accountNumber)
}
// Skip lookup only when we have a MIB-verified name+currency from the caller.
if (selectedDest != null && accountNumber != null &&
!recipientName.isNullOrBlank() && !currency.isNullOrBlank()
) {
val bankBic = when {
accountNumber.matches(Regex("^9\\d{16}$")) -> "MADVMVMV"
accountNumber.matches(Regex("^7\\d{12}$")) -> "MALBMVMV"
else -> ""
}
val trnType = if (accountNumber.matches(Regex("^9\\d{16}$"))) "DOT" else "IAT"
val validation = BmlAccountValidation(
trnType = trnType,
validationType = "prefilled",
account = accountNumber,
originalInput = accountNumber,
name = recipientName,
alias = null,
currency = currency,
agnt = bankBic.takeIf { it.isNotBlank() }
)
showLookupResult(validation, accountNumber)
}
}
private fun buildDestinations(): List<DestinationOption> {
@@ -249,18 +155,6 @@ class AddContactSheetFragment : BottomSheetDialogFragment() {
binding.layoutImage.visibility = if (isMib) View.VISIBLE else View.GONE
binding.tilGroup.visibility = if (isMib) View.VISIBLE else View.GONE
if (isMib) setupCategoryDropdown()
updateSaveState()
}
/**
* Save is enabled once an account is resolved. MIB rejects nicknames longer than
* [MIB_MAX_ALIAS] characters, so show that under the alias field and keep Save disabled.
*/
private fun updateSaveState() {
val alias = binding.etAlias.text?.toString()?.trim() ?: ""
val tooLong = selectedDest?.isBml == false && alias.length > MIB_MAX_ALIAS
binding.tilAlias.error = if (tooLong) getString(R.string.contact_alias_mib_max, MIB_MAX_ALIAS) else null
binding.btnSave.isEnabled = !tooLong && mibLookupAccount != null
}
private fun setupCategoryDropdown() {
@@ -294,12 +188,6 @@ class AddContactSheetFragment : BottomSheetDialogFragment() {
private fun setupAccountSearch() {
binding.tilAccount.setEndIconOnClickListener { performLookup() }
binding.etAccount.setOnEditorActionListener { _, actionId, _ ->
if (actionId == android.view.inputmethod.EditorInfo.IME_ACTION_SEARCH) {
performLookup()
true
} else false
}
}
private fun performLookup() {
@@ -367,9 +255,8 @@ class AddContactSheetFragment : BottomSheetDialogFragment() {
// 3) Fall back to MIB IPS lookup (for USD MIB accounts not reachable via BML)
val mibSess = app.anyMibSession() ?: return null
val mibFlow = app.anyMibFlow() ?: return null
return try {
val info = MibTransferClient(mibFlow).lookup(mibSess, input)
val info = MibTransferClient().lookup(mibSess, input)
BmlAccountValidation(
trnType = "DOT",
validationType = "MIB",
@@ -389,9 +276,8 @@ class AddContactSheetFragment : BottomSheetDialogFragment() {
val profile = dest.mibProfile ?: return null
val mibResult = try {
val flow = app.mibFlowFor(loginId)
flow.switchProfile(mibSess, profile)
val info = MibTransferClient(flow).lookup(mibSess, input)
app.mibFlowFor(loginId).switchProfile(mibSess, profile)
val info = MibTransferClient().lookup(mibSess, input)
BmlAccountValidation(
trnType = if (info.bankId == "MADVMVMV") "MIB_INTERNAL" else "MIB_LOCAL",
validationType = "MIB",
@@ -455,12 +341,12 @@ class AddContactSheetFragment : BottomSheetDialogFragment() {
// Auto-fill alias with existing alias or name
if (binding.etAlias.text.isNullOrBlank()) {
binding.etAlias.setText(sh.sar.basedbank.util.bmlapi.BmlDashboardParser.toTitleCase(validation.name))
binding.etAlias.setText(validation.name)
}
binding.etCurrency.setText(validation.currency)
binding.btnClearResult.setOnClickListener { clearLookupResult() }
updateSaveState()
binding.btnSave.isEnabled = true
}
private fun clearLookupResult() {
@@ -500,7 +386,6 @@ class AddContactSheetFragment : BottomSheetDialogFragment() {
private fun setupSaveButton() {
binding.btnSave.setOnClickListener { performSave() }
binding.etAlias.addTextChangedListener(afterTextChanged = { updateSaveState() })
}
private fun performSave() {
@@ -510,10 +395,6 @@ class AddContactSheetFragment : BottomSheetDialogFragment() {
binding.tilAlias.error = "Alias is required"
return
}
if (!dest.isBml && alias.length > MIB_MAX_ALIAS) {
updateSaveState()
return
}
binding.tilAlias.error = null
binding.btnSave.isEnabled = false
@@ -521,16 +402,11 @@ class AddContactSheetFragment : BottomSheetDialogFragment() {
viewLifecycleOwner.lifecycleScope.launch {
val success = withContext(Dispatchers.IO) {
when {
editContact != null -> updateMib(alias)
dest.isBml -> saveToBml(alias)
else -> saveToMib(alias)
}
if (dest.isBml) saveToBml(alias) else saveToMib(alias)
}
if (success) {
Toast.makeText(requireContext(), R.string.contact_saved, Toast.LENGTH_SHORT).show()
// Same reload as pull-to-refresh on the contacts page
(activity as? HomeActivity)?.loadAllContacts(showIndicator = true)
reloadSavedProfileContacts(dest)
dismiss()
} else {
binding.btnSave.isEnabled = true
@@ -567,13 +443,15 @@ class AddContactSheetFragment : BottomSheetDialogFragment() {
val transferCy = if (currency.equals("USD", ignoreCase = true)) "840" else "462"
val isMibInternal = account.matches(Regex("^9\\d{16}$"))
val benefType = if (isMibInternal) "I" else "L"
val bankNo = if (isMibInternal) 2 else 3
val name = bmlLookup?.name ?: ""
return try {
app.mibFlowFor(loginId).switchProfile(mibSess, profile)
MibContactsClient(app.mibFlowFor(loginId)).createContact(
MibContactsClient().createContact(
session = mibSess,
benefType = benefType,
bankNo = bankNo,
benefAccount = account,
benefName = name,
@@ -585,33 +463,6 @@ class AddContactSheetFragment : BottomSheetDialogFragment() {
} catch (_: Exception) { false }
}
private fun updateMib(alias: String): Boolean {
val contact = editContact ?: return false
val dest = selectedDest ?: return false
val loginId = dest.mibLoginId ?: return false
val mibSess = app.mibSessions[loginId] ?: return false
val profile = dest.mibProfile ?: return false
val currency = binding.etCurrency.text?.toString()?.trim() ?: "MVR"
val transferCy = if (currency.equals("USD", ignoreCase = true)) "840" else "462"
val bankNo = if (contact.benefAccount.matches(Regex("^9\\d{16}$"))) 2 else 3
return try {
val flow = app.mibFlowFor(loginId)
flow.switchProfile(mibSess, profile)
MibContactsClient(flow).updateContact(
session = mibSess,
benefNo = contact.benefNo,
bankNo = bankNo,
benefAccount = contact.benefAccount,
benefName = contact.benefName,
nickName = alias,
transferCy = transferCy,
categoryId = selectedCategoryId,
imageBase64 = selectedImageBase64
)
} catch (_: Exception) { false }
}
private fun makeInitialsBitmap(name: String, colorHex: String): Bitmap {
val sizePx = (resources.displayMetrics.density * 40).toInt()
val bgColor = try { Color.parseColor(colorHex) } catch (_: Exception) { Color.GRAY }
@@ -629,6 +480,35 @@ class AddContactSheetFragment : BottomSheetDialogFragment() {
return bm
}
private fun reloadSavedProfileContacts(dest: DestinationOption) {
// Use activity scope so the reload continues after sheet dismisses
requireActivity().lifecycleScope.launch(Dispatchers.IO) {
try {
if (dest.isBml) {
val loginId = dest.bmlLoginId ?: return@launch
val bmlSess = app.bmlSessions[loginId] ?: return@launch
val fresh = BmlContactsClient().fetchContacts(bmlSess, loginId)
val existing = viewModel.contacts.value ?: emptyList()
val merged = existing.filter { it.benefCategoryId != "BML" } + fresh
viewModel.contacts.postValue(merged)
if (loginId.isNotBlank()) ContactsCache.saveBml(requireContext(), loginId, fresh)
} else {
val profile = dest.mibProfile ?: return@launch
val mibLoginId = dest.mibLoginId ?: return@launch
val mibSess = app.mibSessions[mibLoginId] ?: return@launch
app.mibFlowFor(mibLoginId).switchProfile(mibSess, profile)
val fresh = MibContactsClient().fetchContacts(mibSess)
.map { it.copy(profileId = profile.profileId) }
val existing = viewModel.contacts.value ?: emptyList()
val merged = existing.filter { it.profileId != profile.profileId } + fresh
viewModel.contacts.postValue(merged)
val allMib = merged.filter { it.benefCategoryId != "BML" }
ContactsCache.save(requireContext(), allMib, viewModel.contactCategories.value ?: emptyList())
}
} catch (_: Exception) { }
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
@@ -637,37 +517,5 @@ class AddContactSheetFragment : BottomSheetDialogFragment() {
companion object {
// BML's internal UUID for MIB bank — used as the "swift" field when saving DOT contacts
private const val MIB_SWIFT_ON_BML = "F4E79935-3E73-E611-80DD-00155D020F0A"
// MIB rejects longer nicknames with "invalid nick name"
private const val MIB_MAX_ALIAS = 20
private const val ARG_BML_PROFILE_ID = "bml_profile_id"
private const val ARG_ACCOUNT_NUMBER = "account_number"
private const val ARG_RECIPIENT_NAME = "recipient_name"
private const val ARG_CURRENCY = "currency"
private const val ARG_EDIT_BENEF_NO = "edit_benef_no"
private const val ARG_EDIT_PROFILE_ID = "edit_profile_id"
/** Opens the sheet to edit an existing MIB contact (alias, group, photo). */
fun forEdit(contact: ContactDisplay) = AddContactSheetFragment().apply {
arguments = Bundle().apply {
putString(ARG_EDIT_BENEF_NO, contact.id)
putString(ARG_EDIT_PROFILE_ID, contact.profileId)
}
}
fun newInstance(
bmlProfileId: String? = null,
accountNumber: String? = null,
recipientName: String? = null,
currency: String? = null
) = AddContactSheetFragment().apply {
arguments = Bundle().apply {
if (bmlProfileId != null) putString(ARG_BML_PROFILE_ID, bmlProfileId)
if (accountNumber != null) putString(ARG_ACCOUNT_NUMBER, accountNumber)
if (recipientName != null) putString(ARG_RECIPIENT_NAME, recipientName)
if (currency != null) putString(ARG_CURRENCY, currency)
}
}
}
}
@@ -1,13 +0,0 @@
package sh.sar.basedbank.ui.home
data class AppNotification(
val id: String,
val bank: String, // "BML" or "MIB"
val loginId: String, // key in bmlSessions / mibSessions
val group: String, // "ALERTS" or "INFORMATION"
val title: String,
val message: String,
val timestampMs: Long,
val isRead: Boolean,
val detailFields: List<Pair<String, String>> = emptyList()
)
@@ -1,402 +0,0 @@
package sh.sar.basedbank.ui.home
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Filter
import android.widget.Filterable
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import sh.sar.basedbank.BasedBankApp
import sh.sar.basedbank.R
import sh.sar.basedbank.api.bml.BmlQrPayClient
import sh.sar.basedbank.api.bml.BmlQrPayInfo
import sh.sar.basedbank.api.models.BankAccount
import sh.sar.basedbank.databinding.FragmentBmlQrPayBinding
import sh.sar.basedbank.databinding.ItemAccountDropdownBinding
import sh.sar.basedbank.util.CredentialStore
import sh.sar.basedbank.util.RecentPick
import sh.sar.basedbank.util.RecentsCache
import sh.sar.basedbank.util.Totp
class BmlQrPayFragment : Fragment() {
private var _binding: FragmentBmlQrPayBinding? = null
private val binding get() = _binding!!
private val viewModel: HomeViewModel by activityViewModels()
private var merchantInfo: BmlQrPayInfo? = null
private var selectedAccount: BankAccount? = null
companion object {
private const val ARG_QR_URL = "qr_url"
private const val ARG_FROM_ACCOUNT = "from_account"
fun newInstance(qrUrl: String, fromAccountNumber: String? = null) = BmlQrPayFragment().apply {
arguments = Bundle().apply {
putString(ARG_QR_URL, qrUrl)
if (fromAccountNumber != null) putString(ARG_FROM_ACCOUNT, fromAccountNumber)
}
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
_binding = FragmentBmlQrPayBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
setupFromDropdown()
binding.etAmount.addTextChangedListener { updatePayButton() }
binding.btnClearFromInfo.setOnClickListener {
selectedAccount = null
binding.cardFromInfo.visibility = View.GONE
binding.tilFrom.visibility = View.VISIBLE
binding.actvFrom.setText("", false)
updatePayButton()
}
binding.btnPay.setOnClickListener { initiatePay() }
val qrUrl = arguments?.getString(ARG_QR_URL) ?: run {
requireActivity().onBackPressedDispatcher.onBackPressed(); return
}
lookupMerchant(qrUrl)
}
private fun setupFromDropdown() {
viewModel.accounts.observe(viewLifecycleOwner) { accounts ->
val bmlAccounts = accounts.filter {
it.bank == "BML" &&
it.profileType != "BML_LOAN" &&
it.profileType != "BML_CREDIT"
}
val adapter = BmlAccountAdapter(bmlAccounts)
binding.actvFrom.setAdapter(adapter)
binding.actvFrom.setOnItemClickListener { _, _, position, _ ->
val picked = adapter.getItem(position) as? BankAccount ?: return@setOnItemClickListener
selectedAccount = picked
showFromCard(picked)
updatePayButton()
}
// Pre-select card passed in from the card wallet/dashboard
val preselect = arguments?.getString(ARG_FROM_ACCOUNT)
if (preselect != null && selectedAccount == null) {
bmlAccounts.firstOrNull { it.accountNumber == preselect }?.let {
selectedAccount = it
showFromCard(it)
updatePayButton()
}
}
}
}
private fun showFromCard(account: BankAccount) {
binding.tvFromAccountName.text = account.accountBriefName
binding.tvFromAccountNumber.text = account.accountNumber
val currency = account.currencyName.ifBlank { "MVR" }
binding.tvFromBalance.text = "$currency ${account.availableBalance}"
binding.ivFromPhoto.setImageBitmap(makeInitialsBitmap(account.accountBriefName, "#0066A1"))
binding.tilFrom.visibility = View.GONE
binding.cardFromInfo.visibility = View.VISIBLE
// Update amount prefix to match account currency
binding.tilAmount.prefixText = if (account.currencyName == "USD") "USD " else "MVR "
}
private fun lookupMerchant(qrUrl: String) {
val app = requireActivity().application as BasedBankApp
val session = app.anyBmlSession() ?: run {
Toast.makeText(requireContext(), R.string.transfer_session_unavailable, Toast.LENGTH_SHORT).show()
requireActivity().onBackPressedDispatcher.onBackPressed()
return
}
binding.tvLookingUp.visibility = View.VISIBLE
binding.cardMerchant.visibility = View.GONE
viewLifecycleOwner.lifecycleScope.launch {
val info = withContext(Dispatchers.IO) {
try { BmlQrPayClient().lookupPayRequest(session, qrUrl) }
catch (_: Exception) { null }
}
if (_binding == null) return@launch
binding.tvLookingUp.visibility = View.GONE
if (info == null) {
Toast.makeText(requireContext(), R.string.bml_qr_lookup_failed, Toast.LENGTH_LONG).show()
requireActivity().onBackPressedDispatcher.onBackPressed()
return@launch
}
merchantInfo = info
if (info.amount == 0.0) {
val qrUrl = arguments?.getString(ARG_QR_URL)
if (qrUrl != null) {
RecentsCache.save(requireContext(), RecentPick(
accountNumber = "bmlqr:$qrUrl",
displayName = info.merchantName,
subtitle = info.merchantAddress.ifBlank { "BML Merchant" },
colorHex = "#0066A1",
imageHash = null,
isProfileImage = false
))
}
}
populateMerchant(info)
}
}
private fun populateMerchant(info: BmlQrPayInfo) {
binding.tvMerchantName.text = info.merchantName
binding.tvMerchantAddress.text = info.merchantAddress
binding.ivMerchantIcon.setImageBitmap(makeInitialsBitmap(info.merchantName, "#0066A1"))
binding.cardMerchant.visibility = View.VISIBLE
// Dynamic QR: pre-fill amount and lock the field
if (info.amount > 0.0) {
binding.etAmount.setText("%.2f".format(info.amount))
binding.tilAmount.isEnabled = false
}
updatePayButton()
}
private fun updatePayButton() {
val merchant = merchantInfo ?: run { binding.btnPay.isEnabled = false; return }
val account = selectedAccount ?: run { binding.btnPay.isEnabled = false; return }
val amount = binding.etAmount.text?.toString()?.trim()?.toDoubleOrNull() ?: 0.0
binding.btnPay.isEnabled = amount > 0.0
}
private fun initiatePay() {
val info = merchantInfo ?: return
val account = selectedAccount ?: run {
Toast.makeText(requireContext(), R.string.bml_qr_select_account, Toast.LENGTH_SHORT).show()
return
}
val amountStr = binding.etAmount.text?.toString()?.trim() ?: ""
val amount = amountStr.toDoubleOrNull()
if (amount == null || amount <= 0) {
binding.tilAmount.error = "Enter a valid amount"
return
}
binding.tilAmount.error = null
val debitAccount = account.internalId.ifBlank {
Toast.makeText(requireContext(), R.string.transfer_missing_internal_id, Toast.LENGTH_SHORT).show()
return
}
val currency = info.currency
MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.transfer)
.setMessage("Pay $currency ${"%.2f".format(amount)} to ${info.merchantName}?\n\nFrom: ${account.accountBriefName} · ${account.accountNumber}")
.setPositiveButton(R.string.transfer_confirm) { _, _ ->
executePay(account, debitAccount, info.requestId, amount, currency, info.merchantName)
}
.setNegativeButton(android.R.string.cancel, null)
.show()
}
private fun executePay(
account: BankAccount,
debitAccount: String,
requestId: String,
amount: Double,
currency: String,
merchantName: String
) {
val app = requireActivity().application as BasedBankApp
val loginId = account.loginTag.removePrefix("bml_")
val session = app.bmlSessionFor(account) ?: run {
Toast.makeText(requireContext(), R.string.transfer_session_unavailable, Toast.LENGTH_SHORT).show()
return
}
val otp = CredentialStore(requireContext()).loadBmlCredentials(loginId)?.otpSeed
?.let { Totp.generate(it) }
?: run {
Toast.makeText(requireContext(), "OTP unavailable", Toast.LENGTH_SHORT).show()
return
}
binding.btnPay.isEnabled = false
(activity as? HomeActivity)?.setRefreshing(true)
viewLifecycleOwner.lifecycleScope.launch {
val result = withContext(Dispatchers.IO) {
try {
val initiated = BmlQrPayClient().initiatePayment(session, debitAccount, requestId, amount, currency)
if (!initiated) return@withContext null
val confirmOtp = CredentialStore(requireContext()).loadBmlCredentials(loginId)?.otpSeed
?.let { Totp.generate(it) } ?: otp
BmlQrPayClient().confirmPayment(session, debitAccount, requestId, amount, currency, confirmOtp)
} catch (e: Exception) {
sh.sar.basedbank.api.bml.BmlQrPayResult(false, errorMessage = e.message ?: "Payment failed")
}
}
(activity as? HomeActivity)?.setRefreshing(false)
if (_binding == null) return@launch
if (result == null) {
binding.btnPay.isEnabled = true
Toast.makeText(requireContext(), "Failed to initiate payment", Toast.LENGTH_LONG).show()
return@launch
}
if (result.success) {
showSuccessDialog(
merchant = result.merchant.ifBlank { merchantName },
amount = result.amount.ifBlank { "%.2f".format(amount) },
currency = result.currency.ifBlank { currency }
)
} else {
binding.btnPay.isEnabled = true
Toast.makeText(requireContext(), result.errorMessage, Toast.LENGTH_LONG).show()
}
}
}
private fun showSuccessDialog(merchant: String, amount: String, currency: String) {
val ctx = requireContext()
val dp = resources.displayMetrics.density
val container = LinearLayout(ctx).apply {
orientation = LinearLayout.VERTICAL
gravity = Gravity.CENTER_HORIZONTAL
setPadding((24 * dp).toInt(), (24 * dp).toInt(), (24 * dp).toInt(), (8 * dp).toInt())
}
// Green checkmark icon
container.addView(ImageView(ctx).apply {
setImageResource(R.drawable.ic_check_circle)
setColorFilter(Color.parseColor("#4CAF50"))
layoutParams = LinearLayout.LayoutParams(
(64 * dp).toInt(), (64 * dp).toInt()
).apply { gravity = Gravity.CENTER_HORIZONTAL; bottomMargin = (16 * dp).toInt() }
})
// Amount
container.addView(TextView(ctx).apply {
text = "$currency $amount"
textSize = 28f
setTypeface(null, android.graphics.Typeface.BOLD)
setTextColor(com.google.android.material.color.MaterialColors.getColor(
requireView(), com.google.android.material.R.attr.colorOnSurface, Color.BLACK))
gravity = Gravity.CENTER
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
).apply { gravity = Gravity.CENTER_HORIZONTAL; bottomMargin = (8 * dp).toInt() }
})
// Merchant name
container.addView(TextView(ctx).apply {
text = merchant
textSize = 14f
setTextColor(com.google.android.material.color.MaterialColors.getColor(
requireView(), com.google.android.material.R.attr.colorOnSurfaceVariant, Color.GRAY))
gravity = Gravity.CENTER
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
).apply { gravity = Gravity.CENTER_HORIZONTAL }
})
MaterialAlertDialogBuilder(ctx)
.setTitle(R.string.bml_qr_payment_success)
.setView(container)
.setPositiveButton(android.R.string.ok) { _, _ ->
(activity as? HomeActivity)?.triggerRefresh()
requireActivity().onBackPressedDispatcher.onBackPressed()
}
.setCancelable(false)
.show()
}
private fun makeInitialsBitmap(name: String, colorHex: String): Bitmap {
val sizePx = (resources.displayMetrics.density * 40).toInt()
val bgColor = try { Color.parseColor(colorHex) } catch (_: Exception) { Color.GRAY }
val bm = Bitmap.createBitmap(sizePx, sizePx, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bm)
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
paint.color = bgColor
canvas.drawCircle(sizePx / 2f, sizePx / 2f, sizePx / 2f, paint)
paint.color = Color.WHITE
paint.textSize = sizePx * 0.42f
paint.textAlign = Paint.Align.CENTER
val letter = name.firstOrNull()?.uppercaseChar()?.toString() ?: "?"
val metrics = paint.fontMetrics
canvas.drawText(letter, sizePx / 2f, sizePx / 2f - (metrics.ascent + metrics.descent) / 2f, paint)
return bm
}
override fun onResume() {
super.onResume()
requireActivity().title = "BML QR Pay"
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private inner class BmlAccountAdapter(private val accounts: List<BankAccount>) :
BaseAdapter(), Filterable {
override fun getCount() = accounts.size
override fun getItem(position: Int) = accounts[position]
override fun getItemId(position: Int) = position.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup) =
getDropDownView(position, convertView, parent)
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
val acc = accounts[position]
val b = if (convertView?.tag is ItemAccountDropdownBinding) {
convertView.tag as ItemAccountDropdownBinding
} else {
ItemAccountDropdownBinding.inflate(LayoutInflater.from(context), parent, false)
.also { it.root.tag = it }
}
val ownerPrefix = if (acc.profileName.isNotBlank()) "${acc.profileName} · " else ""
b.tvDropdownAccountName.text = "$ownerPrefix${acc.accountBriefName}"
b.tvDropdownAccountNumber.text = acc.accountNumber
b.tvDropdownBalance.text = "${acc.currencyName} ${acc.availableBalance}"
b.root.alpha = 1f
return b.root
}
override fun getFilter() = object : Filter() {
override fun performFiltering(c: CharSequence?) =
FilterResults().apply { values = accounts; count = accounts.size }
override fun publishResults(c: CharSequence?, r: FilterResults?) = notifyDataSetChanged()
override fun convertResultToString(r: Any?) =
(r as? BankAccount)?.let {
val prefix = if (it.profileName.isNotBlank()) "${it.profileName} · " else ""
"$prefix${it.accountBriefName}"
} ?: ""
}
}
}
@@ -1,3 +1,139 @@
package sh.sar.basedbank.ui.home
// Merged into CardsFragment
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import sh.sar.basedbank.R
import sh.sar.basedbank.databinding.FragmentCardSettingsBinding
import sh.sar.basedbank.util.bmlapi.BmlCardParser
class CardSettingsFragment : Fragment() {
private var _binding: FragmentCardSettingsBinding? = null
private val binding get() = _binding!!
private val viewModel: HomeViewModel by activityViewModels()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentCardSettingsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val adapter = CardSettingsAdapter(emptyList(), requireContext())
binding.recyclerView.layoutManager = LinearLayoutManager(requireContext())
binding.recyclerView.adapter = adapter
val bottomPaddingBase = (16 * resources.displayMetrics.density).toInt()
ViewCompat.setOnApplyWindowInsetsListener(binding.recyclerView) { v, insets ->
val isBottomNav = requireContext().getSharedPreferences("prefs", Context.MODE_PRIVATE).getBoolean("bottom_nav", false)
val navBar = insets.getInsets(WindowInsetsCompat.Type.systemBars())
val extraBottom = if (isBottomNav) 0 else navBar.bottom
v.setPadding(v.paddingLeft, v.paddingTop, v.paddingRight, bottomPaddingBase + extraBottom)
insets
}
binding.swipeRefresh.setOnRefreshListener {
(activity as? HomeActivity)?.triggerRefresh()
}
val updateCardList = {
val mibItems = (viewModel.mibCards.value ?: emptyList()).map { CardItem.Mib(it) }
val bmlItems = (viewModel.accounts.value ?: emptyList())
.filter { it.profileType == "BML_PREPAID" || it.profileType == "BML_CREDIT" || it.profileType == "BML_DEBIT" }
.map { CardItem.Bml(it) }
val all = mibItems + bmlItems
adapter.update(all)
binding.loadingView.visibility = View.GONE
binding.swipeRefresh.isRefreshing = false
binding.emptyView.visibility = if (all.isEmpty()) View.VISIBLE else View.GONE
binding.recyclerView.visibility = if (all.isEmpty()) View.GONE else View.VISIBLE
}
viewModel.mibCards.observe(viewLifecycleOwner) { updateCardList() }
viewModel.accounts.observe(viewLifecycleOwner) { updateCardList() }
if (viewModel.mibCards.value == null) {
binding.loadingView.visibility = View.VISIBLE
(activity as? HomeActivity)?.triggerRefreshCards()
}
}
override fun onResume() {
super.onResume()
requireActivity().title = getString(R.string.nav_card_settings)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private inner class CardSettingsAdapter(
private var cards: List<CardItem>,
private val context: Context
) : RecyclerView.Adapter<CardSettingsAdapter.VH>() {
fun update(newCards: List<CardItem>) {
cards = newCards
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH =
VH(LayoutInflater.from(context).inflate(R.layout.item_card_settings_entry, parent, false))
override fun onBindViewHolder(holder: VH, position: Int) = holder.bind(cards[position])
override fun getItemCount() = cards.size
inner class VH(view: View) : RecyclerView.ViewHolder(view) {
private val ivCardImage: ImageView = view.findViewById(R.id.ivCardImage)
private val tvCardOwner: TextView = view.findViewById(R.id.tvCardOwner)
private val tvCardNumber: TextView = view.findViewById(R.id.tvCardNumber)
private val tvCardType: TextView = view.findViewById(R.id.tvCardType)
private val tvCardStatus: TextView = view.findViewById(R.id.tvCardStatus)
private val btnChangePin: View = view.findViewById(R.id.btnChangePin)
private val btnFreeze: View = view.findViewById(R.id.btnFreeze)
private val btnBlock: View = view.findViewById(R.id.btnBlock)
fun bind(item: CardItem) {
when (item) {
is CardItem.Mib -> {
tvCardOwner.text = item.card.cardHolderName
tvCardNumber.text = PayWithCardFragment.formatMasked(item.card.maskedCardNumber)
tvCardType.text = item.card.cardTypeDesc
val assetPath = PayWithCardFragment.cardImageAsset(item.card)
if (assetPath != null) PayWithCardFragment.loadCardImage(ivCardImage, assetPath)
else ivCardImage.setImageDrawable(null)
PayWithCardFragment.bindCardStatus(tvCardStatus, PayWithCardFragment.mibCardStatusLabel(item.card.cardStatus))
itemView.alpha = 1f
}
is CardItem.Bml -> {
tvCardOwner.text = item.account.accountBriefName
tvCardNumber.text = PayWithCardFragment.formatMasked(item.account.accountNumber)
tvCardType.text = item.account.accountTypeName
PayWithCardFragment.loadCardImage(ivCardImage, BmlCardParser.cardImageAsset(item.account))
val isActive = item.account.statusDesc.equals("Active", ignoreCase = true)
val bmlStatus = item.account.statusDesc.takeUnless { isActive }
PayWithCardFragment.bindCardStatus(tvCardStatus, bmlStatus)
itemView.alpha = if (isActive) 1f else 0.45f
}
}
val wip = View.OnClickListener {
Toast.makeText(context, R.string.work_in_progress, Toast.LENGTH_SHORT).show()
}
btnChangePin.setOnClickListener(wip)
btnFreeze.setOnClickListener(wip)
btnBlock.setOnClickListener(wip)
}
}
}
}
@@ -1,236 +0,0 @@
package sh.sar.basedbank.ui.home
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.os.SystemClock
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.OvershootInterpolator
import com.google.android.material.color.MaterialColors
import kotlin.math.PI
import kotlin.math.min
import kotlin.math.sin
/**
* "Tap card to verify" animation: a bank card swings onto the back of a phone, NFC waves
* ripple out from the contact point, then it lifts away and repeats. Has reading / success /
* error states so the fragment can reflect what the reader is doing.
*/
class CardVerifyAnimationView(context: Context) : View(context) {
enum class State { WAITING, READING, SUCCESS, ERROR }
private var state = State.WAITING
private var stateStart = SystemClock.uptimeMillis()
private var label: String = ""
/** Text shown under the animation while waiting (and restored after an error). */
var waitingLabel: String = ""
set(value) { field = value; if (state == State.WAITING) label = value; invalidate() }
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER }
private val rect = RectF()
private val path = Path()
private val easeInOut = AccelerateDecelerateInterpolator()
private val overshoot = OvershootInterpolator(2.2f)
// Drives redraws only; all motion is derived from elapsed time in the current state.
private val ticker = ValueAnimator.ofFloat(0f, 1f).apply {
duration = 1000
repeatCount = ValueAnimator.INFINITE
addUpdateListener { invalidate() }
}
private val revertToWaiting = Runnable { setState(State.WAITING) }
fun setState(newState: State, text: String? = null) {
removeCallbacks(revertToWaiting)
state = newState
stateStart = SystemClock.uptimeMillis()
label = text ?: if (newState == State.WAITING) waitingLabel else label
if (newState == State.ERROR) postDelayed(revertToWaiting, ERROR_HOLD_MS)
invalidate()
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
ticker.start()
}
override fun onDetachedFromWindow() {
ticker.cancel()
removeCallbacks(revertToWaiting)
super.onDetachedFromWindow()
}
override fun onDraw(canvas: Canvas) {
val w = width.toFloat(); val h = height.toFloat()
if (w <= 0f || h <= 0f) return
val dp = resources.displayMetrics.density
val colorOnSurface = MaterialColors.getColor(this, com.google.android.material.R.attr.colorOnSurface, 0xFF000000.toInt())
val colorPrimary = MaterialColors.getColor(this, com.google.android.material.R.attr.colorPrimary, 0xFF3F51B5.toInt())
val colorOnPrimary = MaterialColors.getColor(this, com.google.android.material.R.attr.colorOnPrimary, 0xFFFFFFFF.toInt())
val colorSurfaceVariant = MaterialColors.getColor(this, com.google.android.material.R.attr.colorSurfaceVariant, 0xFFDDDDDD.toInt())
val colorError = MaterialColors.getColor(this, com.google.android.material.R.attr.colorError, 0xFFB3261E.toInt())
// Artwork is laid out in a DESIGN_W x DESIGN_H dp box, scaled to fit the available area.
val textArea = 36 * dp
val scale = min(min(w / (DESIGN_W * dp), (h - textArea) / (DESIGN_H * dp)), 1.3f).coerceAtLeast(0.3f)
val u = dp * scale
val cx = w / 2f
val top = ((h - textArea) - DESIGN_H * u) / 2f
val elapsed = SystemClock.uptimeMillis() - stateStart
// ── Card motion: 0 = resting away from phone, 1 = held on phone ─────────
val contact = when (state) {
State.WAITING -> {
val p = (elapsed % CYCLE_MS) / CYCLE_MS.toFloat()
when {
p < 0.35f -> easeInOut.getInterpolation(p / 0.35f)
p < 0.70f -> 1f
p < 1.00f -> 1f - easeInOut.getInterpolation((p - 0.70f) / 0.30f)
else -> 0f
}
}
else -> 1f
}
val shake = if (state == State.ERROR && elapsed < 500)
sin(elapsed / 500f * 6 * PI).toFloat() * (1f - elapsed / 500f) * 8 * u else 0f
// Phone
val phoneW = 64 * u; val phoneH = 112 * u
val phoneL = cx - phoneW / 2f; val phoneT = top + 44 * u
paint.style = Paint.Style.FILL; paint.color = colorSurfaceVariant
rect.set(phoneL, phoneT, phoneL + phoneW, phoneT + phoneH)
canvas.drawRoundRect(rect, 10 * u, 10 * u, paint)
paint.style = Paint.Style.STROKE; paint.strokeWidth = 2.5f * u; paint.color = colorOnSurface
canvas.drawRoundRect(rect, 10 * u, 10 * u, paint)
// Camera bump (we're looking at the back of the phone)
paint.style = Paint.Style.FILL; paint.color = colorOnSurface; paint.alpha = 60
rect.set(phoneL + 8 * u, phoneT + 8 * u, phoneL + 26 * u, phoneT + 30 * u)
canvas.drawRoundRect(rect, 5 * u, 5 * u, paint)
paint.alpha = 255
// Contact point where the NFC antenna sits
val touchX = cx; val touchY = phoneT + phoneH * 0.42f
// ── NFC waves (behind the card) ────────────────────────────────────────
val waveStrength = when (state) {
State.WAITING -> ((contact - 0.85f) / 0.15f).coerceIn(0f, 1f)
State.READING -> 1f
else -> 0f
}
if (waveStrength > 0f) {
val period = if (state == State.READING) 700f else 1100f
val base = (elapsed % period.toLong()) / period
paint.style = Paint.Style.STROKE; paint.strokeWidth = 3 * u
for (i in 0..2) {
val p = (base + i / 3f) % 1f
val r = 58 * u + p * 46 * u
paint.color = colorPrimary
paint.alpha = ((1f - p) * 220 * waveStrength).toInt().coerceIn(0, 255)
rect.set(touchX - r, touchY - r * 0.72f, touchX + r, touchY + r * 0.72f)
canvas.drawOval(rect, paint)
}
paint.alpha = 255
}
// ── Card ───────────────────────────────────────────────────────────────
val cardW = 104 * u; val cardH = 66 * u
val restX = cx + 58 * u; val restY = top + 48 * u
val cardCx = restX + (touchX - restX) * contact + shake
val cardCy = restY + (touchY - restY) * contact
val rotation = 18f * (1f - contact)
val lift = 1f + 0.08f * (1f - contact)
canvas.save()
canvas.translate(cardCx, cardCy)
canvas.rotate(rotation)
canvas.scale(lift, lift)
// Same flat look as the phone: surface-variant body, on-surface outline, primary tint for the chip
val outline = if (state == State.ERROR) colorError else colorOnSurface
rect.set(-cardW / 2, -cardH / 2, cardW / 2, cardH / 2)
paint.style = Paint.Style.FILL; paint.color = colorSurfaceVariant
canvas.drawRoundRect(rect, 8 * u, 8 * u, paint)
paint.style = Paint.Style.STROKE; paint.strokeWidth = 2.5f * u; paint.color = outline
canvas.drawRoundRect(rect, 8 * u, 8 * u, paint)
// Chip
rect.set(-cardW / 2 + 12 * u, -9 * u, -cardW / 2 + 30 * u, 5 * u)
paint.style = Paint.Style.FILL; paint.color = colorPrimary; paint.alpha = 70
canvas.drawRoundRect(rect, 3 * u, 3 * u, paint)
paint.alpha = 255
paint.style = Paint.Style.STROKE; paint.strokeWidth = 1.5f * u; paint.color = outline
canvas.drawRoundRect(rect, 3 * u, 3 * u, paint)
canvas.drawLine(rect.left, rect.centerY(), rect.right, rect.centerY(), paint)
// Contactless symbol on the card
paint.strokeWidth = 1.8f * u; paint.strokeCap = Paint.Cap.ROUND
for (i in 0..2) {
val r = (5 + i * 4.5f) * u
rect.set(cardW / 2 - 28 * u - r, -14 * u - r, cardW / 2 - 28 * u + r, -14 * u + r)
canvas.drawArc(rect, -45f, 90f, false, paint)
}
// Number + name placeholders
paint.strokeWidth = 3f * u; paint.alpha = 150
for (g in 0..3) {
val x = -cardW / 2 + 12 * u + g * 21 * u
canvas.drawLine(x, 16 * u, x + 15 * u, 16 * u, paint)
}
paint.alpha = 100; paint.strokeWidth = 2.5f * u
canvas.drawLine(-cardW / 2 + 12 * u, 26 * u, -cardW / 2 + 48 * u, 26 * u, paint)
paint.alpha = 255; paint.strokeCap = Paint.Cap.BUTT
canvas.restore()
// ── Success badge ──────────────────────────────────────────────────────
if (state == State.SUCCESS) {
val t = (elapsed / 450f).coerceIn(0f, 1f)
val badgeR = 22 * u * overshoot.getInterpolation(t)
val bx = touchX + cardW / 2 - 6 * u; val by = touchY - cardH / 2 + 4 * u
paint.style = Paint.Style.FILL; paint.color = colorPrimary
canvas.drawCircle(bx, by, badgeR, paint)
val checkT = ((elapsed - 200) / 350f).coerceIn(0f, 1f)
if (checkT > 0f) {
paint.style = Paint.Style.STROKE; paint.strokeWidth = 3.5f * u
paint.strokeCap = Paint.Cap.ROUND; paint.color = colorOnPrimary
val x0 = bx - 9 * u; val y0 = by
val x1 = bx - 3 * u; val y1 = by + 7 * u
val x2 = bx + 10 * u; val y2 = by - 7 * u
path.reset(); path.moveTo(x0, y0)
if (checkT < 0.4f) {
val k = checkT / 0.4f
path.lineTo(x0 + (x1 - x0) * k, y0 + (y1 - y0) * k)
} else {
val k = (checkT - 0.4f) / 0.6f
path.lineTo(x1, y1); path.lineTo(x1 + (x2 - x1) * k, y1 + (y2 - y1) * k)
}
canvas.drawPath(path, paint)
paint.strokeCap = Paint.Cap.BUTT
}
}
// ── Label ──────────────────────────────────────────────────────────────
textPaint.textSize = 16 * dp
textPaint.color = if (state == State.ERROR) colorError else colorOnSurface
textPaint.alpha = when (state) {
State.WAITING -> (170 + 60 * sin(elapsed / 600.0).toFloat()).toInt().coerceIn(0, 255)
else -> 230
}
canvas.drawText(label, cx, h - textArea / 2f + textPaint.textSize / 3f, textPaint)
}
companion object {
private const val DESIGN_W = 240f
private const val DESIGN_H = 170f
private const val CYCLE_MS = 2600L
private const val ERROR_HOLD_MS = 1800L
}
}
@@ -1,561 +0,0 @@
package sh.sar.basedbank.ui.home
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.os.VibrationEffect
import android.os.Vibrator
import android.util.AttributeSet
import android.util.TypedValue
import android.view.*
import android.view.animation.DecelerateInterpolator
import android.view.animation.LinearInterpolator
import android.animation.AnimatorListenerAdapter
import android.animation.Animator
import android.widget.FrameLayout
import android.graphics.Typeface
import androidx.annotation.DrawableRes
import androidx.appcompat.content.res.AppCompatResources
import androidx.appcompat.widget.Toolbar
import androidx.core.graphics.drawable.DrawableCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import com.google.android.material.color.MaterialColors
import sh.sar.basedbank.R
import kotlin.math.*
class CircularNavFragment : Fragment() {
private var wheelView: CircularWheelView? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val ctx = requireContext()
val colorPrimary = MaterialColors.getColor(ctx, com.google.android.material.R.attr.colorPrimary, Color.RED)
val colorSurface = MaterialColors.getColor(ctx, com.google.android.material.R.attr.colorSurface, Color.WHITE)
val colorOnSurface = MaterialColors.getColor(ctx, com.google.android.material.R.attr.colorOnSurface, Color.DKGRAY)
fun dp(v: Float) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, v, ctx.resources.displayMetrics)
val root = android.widget.LinearLayout(ctx).apply {
orientation = android.widget.LinearLayout.VERTICAL
setBackgroundColor(colorSurface)
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
}
// Wheel area (weight 1, fills remaining space)
val wheelContainer = FrameLayout(ctx).apply {
layoutParams = android.widget.LinearLayout.LayoutParams(
android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f
)
}
val prefs = ctx.getSharedPreferences("prefs", Context.MODE_PRIVATE)
wheelView = CircularWheelView(ctx).apply {
layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
wheelAngle = prefs.getFloat("circular_wheel_angle", 0f)
val savedSlots = NavCustomization.getCircularSlots(prefs).map { id ->
val def = NavCustomization.ALL_SWAPPABLE.find { it.id == id }!!
CircularWheelView.WheelItem(def.id, def.iconRes, ctx.getString(def.titleRes))
}
items = listOf(
savedSlots[3], // 4 o'clock (strip slot 3)
CircularWheelView.WheelItem(R.id.nav_dashboard, R.drawable.ic_nav_dashboard, ctx.getString(R.string.nav_dashboard)), // 6 o'clock
CircularWheelView.WheelItem(R.id.nav_more, R.drawable.ic_nav_more, ctx.getString(R.string.nav_more)), // 8 o'clock
savedSlots[0], // 10 o'clock (strip slot 0 — first in strip)
savedSlots[1], // 12 o'clock (strip slot 1)
savedSlots[2], // 2 o'clock (strip slot 2)
)
accentColor = colorPrimary
surfaceColor = colorSurface
labelColor = colorOnSurface
onItemClick = { navId -> (activity as? HomeActivity)?.navigateTo(navId) }
onCenterClick = { /* unused: tap on unlocked center locks the wheel */ }
onWheelCenterLockedTap = { (activity as? HomeActivity)?.notifyWheelLockTap() }
}
wheelContainer.addView(wheelView)
// App icon centered at the bottom
val iconSz = dp(48f).toInt()
val footerIcon = android.widget.ImageView(ctx).apply {
setImageDrawable(ctx.packageManager.getApplicationIcon(ctx.packageName))
layoutParams = android.widget.LinearLayout.LayoutParams(iconSz, iconSz).also {
it.gravity = Gravity.CENTER_HORIZONTAL
it.topMargin = dp(12f).toInt()
it.bottomMargin = dp(16f).toInt()
}
}
root.addView(wheelContainer)
root.addView(footerIcon)
ViewCompat.setOnApplyWindowInsetsListener(root) { _, insets ->
val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
(footerIcon.layoutParams as android.widget.LinearLayout.LayoutParams).bottomMargin = dp(16f).toInt() + bars.bottom
footerIcon.requestLayout()
insets
}
return root
}
override fun onResume() {
super.onResume()
requireActivity().invalidateOptionsMenu()
val ctx = requireContext()
val toolbar = requireActivity().findViewById<com.google.android.material.appbar.MaterialToolbar>(R.id.toolbar)
requireActivity().title = ""
val textColor = MaterialColors.getColor(ctx, com.google.android.material.R.attr.colorOnSurface, android.graphics.Color.DKGRAY)
val container = android.widget.TextView(ctx).apply {
text = getString(R.string.app_name)
setTextColor(textColor)
textSize = 20f
typeface = Typeface.DEFAULT_BOLD
tag = "wheel_title"
}
toolbar.addView(container, Toolbar.LayoutParams(
Toolbar.LayoutParams.WRAP_CONTENT,
Toolbar.LayoutParams.WRAP_CONTENT,
Gravity.CENTER
))
}
override fun onPause() {
super.onPause()
wheelView?.let { wv ->
requireContext().getSharedPreferences("prefs", Context.MODE_PRIVATE)
.edit().putFloat("circular_wheel_angle", wv.wheelAngle).apply()
}
val toolbar = requireActivity().findViewById<com.google.android.material.appbar.MaterialToolbar>(R.id.toolbar)
toolbar.findViewWithTag<android.view.View>("wheel_title")?.let { toolbar.removeView(it) }
requireActivity().invalidateOptionsMenu()
}
fun unlockWheelLock() {
wheelView?.unlockWheel()
}
}
// ---------------------------------------------------------------------------
// Custom wheel view
// ---------------------------------------------------------------------------
class CircularWheelView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : View(context, attrs) {
data class WheelItem(
val navId: Int,
@DrawableRes val iconRes: Int,
val label: String
)
// ---- public properties ------------------------------------------------
var items: List<WheelItem> = emptyList()
set(value) {
field = value
iconBitmaps = arrayOfNulls(value.size)
if (cx > 0f) reloadBitmaps()
invalidate()
}
var accentColor: Int = Color.RED
set(value) { field = value; if (cx > 0f) reloadBitmaps(); invalidate() }
var surfaceColor: Int = Color.WHITE
set(value) { field = value; invalidate() }
var labelColor: Int = Color.DKGRAY
set(value) { field = value; invalidate() }
var isWheelLocked = false
set(value) { field = value; invalidate() }
var onItemClick: ((Int) -> Unit)? = null
var onCenterClick: (() -> Unit)? = null
var onWheelCenterLockedTap: (() -> Unit)? = null
// ---- geometry ---------------------------------------------------------
private var cx = 0f
private var cy = 0f
private var outerRadius = 0f
private var innerRadius = 0f
// ---- paint ------------------------------------------------------------
private val discPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val accentRingPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val accentRing2Paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val dividerPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
textAlign = Paint.Align.CENTER
typeface = Typeface.DEFAULT_BOLD
}
private val centerFillPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val centerRingPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val bitmapPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private var iconBitmaps: Array<Bitmap?> = emptyArray()
private var centerBitmap: Bitmap? = null
private var centerUnlockedBitmap: Bitmap? = null
private val grayFilter = ColorMatrixColorFilter(ColorMatrix().apply { setSaturation(0f) })
private var lockShakeAngle = 0f
private var shakeAnimator: ValueAnimator? = null
// ---- touch & fling ----------------------------------------------------
var wheelAngle = 0f
private var isDragging = false
private var snapAnimator: ValueAnimator? = null
// Incremental drag state
private var prevTouchAngle = 0f
private var touchDownX = 0f
private var touchDownY = 0f
// Velocity buffer: stores (cumulative wheel angle, timestamp) for last N samples
private val VEL_SAMPLES = 6
private val velAngles = FloatArray(VEL_SAMPLES)
private val velTimes = LongArray(VEL_SAMPLES)
private var velIdx = 0
private var velCount = 0
private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop.toFloat()
// ---- helpers ----------------------------------------------------------
private fun dp(v: Float) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, v, resources.displayMetrics)
// ---- sizing -----------------------------------------------------------
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
cx = w / 2f
cy = h / 2f
val size = minOf(w, h)
outerRadius = size / 2f * 0.80f
innerRadius = outerRadius * 0.26f
textPaint.textSize = size * 0.034f
dividerPaint.strokeWidth = dp(0.7f)
accentRingPaint.strokeWidth = dp(5f)
accentRing2Paint.strokeWidth = dp(3f)
centerRingPaint.strokeWidth = dp(4f)
reloadBitmaps()
}
private fun reloadBitmaps() {
val iconPx = (outerRadius * 0.24f).toInt().coerceAtLeast(1)
items.forEachIndexed { i, item ->
iconBitmaps[i] = tintedBitmap(item.iconRes, accentColor, iconPx)
}
val centerPx = (innerRadius * 0.64f).toInt().coerceAtLeast(1)
centerBitmap = tintedBitmap(R.drawable.ic_lock, accentColor, centerPx)
centerUnlockedBitmap = tintedBitmap(R.drawable.ic_lock_open, accentColor, centerPx)
}
private fun tintedBitmap(@DrawableRes resId: Int, tint: Int, sizePx: Int): Bitmap? {
if (sizePx <= 0) return null
return try {
val d = AppCompatResources.getDrawable(context, resId)!!.mutate()
DrawableCompat.setTint(DrawableCompat.wrap(d), tint)
val bmp = Bitmap.createBitmap(sizePx, sizePx, Bitmap.Config.ARGB_8888)
Canvas(bmp).also { d.setBounds(0, 0, sizePx, sizePx); d.draw(it) }
bmp
} catch (_: Exception) { null }
}
// ---- drawing ----------------------------------------------------------
override fun onDraw(canvas: Canvas) {
if (items.isEmpty()) return
val segCount = items.size
val segDeg = 360f / segCount
// Wheel disc
discPaint.color = surfaceColor
canvas.drawCircle(cx, cy, outerRadius, discPaint)
// Accent ring around wheel
accentRingPaint.color = accentColor
canvas.drawCircle(cx, cy, outerRadius + dp(20f), accentRingPaint)
// Rotatable layer
canvas.save()
canvas.rotate(wheelAngle, cx, cy)
// Divider lines between segments
dividerPaint.color = (labelColor and 0x00FFFFFF) or (100 shl 24)
for (i in 0 until segCount) {
val rad = Math.toRadians((i * segDeg).toDouble())
val cos = cos(rad).toFloat()
val sin = sin(rad).toFloat()
canvas.drawLine(
cx + cos * (innerRadius + dp(6f)), cy + sin * (innerRadius + dp(6f)),
cx + cos * (outerRadius - dp(12f)), cy + sin * (outerRadius - dp(12f)),
dividerPaint
)
}
// Segment content
for (i in 0 until segCount) {
val midDeg = i * segDeg + segDeg / 2f
drawSegment(canvas, i, midDeg)
}
canvas.restore()
// Center button — always upright
centerRingPaint.color = accentColor
canvas.drawCircle(cx, cy, innerRadius + dp(3f), centerRingPaint)
centerFillPaint.color = surfaceColor
canvas.drawCircle(cx, cy, innerRadius, centerFillPaint)
val activeCenterBitmap = if (isWheelLocked) centerBitmap else centerUnlockedBitmap
activeCenterBitmap?.let {
canvas.save()
// Shake pivots around the bottom-centre of the icon
if (lockShakeAngle != 0f) canvas.rotate(lockShakeAngle, cx, cy + it.height / 2f)
canvas.drawBitmap(it, cx - it.width / 2f, cy - it.height / 2f, bitmapPaint)
canvas.restore()
}
}
private fun drawSegment(canvas: Canvas, index: Int, midDeg: Float) {
val rad = Math.toRadians(midDeg.toDouble())
val cosA = cos(rad).toFloat()
val sinA = sin(rad).toFloat()
val iconX = cx + cosA * (outerRadius * 0.63f)
val iconY = cy + sinA * (outerRadius * 0.63f)
// Icon — radially oriented; top items are naturally upside-down
iconBitmaps.getOrNull(index)?.let { bmp ->
canvas.save()
canvas.translate(iconX, iconY)
canvas.rotate(midDeg - 90f)
if (isWheelLocked) {
bitmapPaint.colorFilter = grayFilter
bitmapPaint.alpha = 100
}
canvas.drawBitmap(bmp, -bmp.width / 2f, -bmp.height / 2f, bitmapPaint)
if (isWheelLocked) {
bitmapPaint.colorFilter = null
bitmapPaint.alpha = 255
}
canvas.restore()
}
// Curved label — same radial orientation as icons.
// In the local rotated frame the wheel arc is a circle of radius `labelRadius`
// with its centre directly "above" at (0, -labelRadius). A CCW arc through (0,0)
// flows rightward at that point, matching the natural reading direction at 6 o'clock.
val labelRadius = outerRadius * 0.84f
val textX = cx + cosA * labelRadius
val textY = cy + sinA * labelRadius
val label = items[index].label
textPaint.color = if (isWheelLocked) (labelColor and 0x00FFFFFF) or (80 shl 24) else labelColor
textPaint.textAlign = Paint.Align.LEFT
val halfAngleDeg = Math.toDegrees((textPaint.measureText(label) / 2.0) / labelRadius).toFloat()
val localArcRect = RectF(-labelRadius, -2f * labelRadius, labelRadius, 0f)
val arcPath = Path().apply { addArc(localArcRect, 90f + halfAngleDeg, -(halfAngleDeg * 2f)) }
canvas.save()
canvas.translate(textX, textY)
canvas.rotate(midDeg - 90f)
canvas.drawTextOnPath(label, arcPath, 0f, textPaint.textSize * 0.36f, textPaint)
canvas.restore()
}
// ---- touch ------------------------------------------------------------
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
snapAnimator?.cancel()
prevTouchAngle = angleAt(event.x, event.y)
touchDownX = event.x
touchDownY = event.y
isDragging = false
velIdx = 0
velCount = 0
recordVelSample()
return true
}
MotionEvent.ACTION_MOVE -> {
val curr = angleAt(event.x, event.y)
// Incremental delta — normalised to [-180, 180] to survive the ±180° wrap
var dA = curr - prevTouchAngle
if (dA > 180f) dA -= 360f
if (dA < -180f) dA += 360f
prevTouchAngle = curr
val moved = hypot(event.x - touchDownX, event.y - touchDownY)
if (moved > touchSlop || isDragging) {
isDragging = true
wheelAngle += dA
recordVelSample()
invalidate()
}
}
MotionEvent.ACTION_UP -> {
if (!isDragging) {
val dist = hypot(event.x - cx, event.y - cy)
when {
dist <= innerRadius -> {
if (isWheelLocked) {
onWheelCenterLockedTap?.invoke()
} else {
isWheelLocked = true
}
}
dist <= outerRadius -> {
if (isWheelLocked) {
val idx = segmentAt(event.x, event.y)
if (idx in items.indices) animateToSixOClock(idx) {
vibrateDevice()
shakeLock()
}
} else {
val idx = segmentAt(event.x, event.y)
if (idx in items.indices) animateToSixOClock(idx) { onItemClick?.invoke(items[idx].navId) }
}
}
}
} else {
val vel = computeVelocity()
if (abs(vel) > 0.05f) fling(vel) else snapToNearest()
}
}
MotionEvent.ACTION_CANCEL -> {
if (isDragging) {
val vel = computeVelocity()
if (abs(vel) > 0.05f) fling(vel) else snapToNearest()
}
}
}
return true
}
private fun recordVelSample() {
val slot = velIdx % VEL_SAMPLES
velAngles[slot] = wheelAngle
velTimes[slot] = System.currentTimeMillis()
velIdx++
if (velCount < VEL_SAMPLES) velCount++
}
/** Returns angular velocity in degrees per millisecond, using the oldest available sample. */
private fun computeVelocity(): Float {
if (velCount < 2) return 0f
val newest = (velIdx - 1 + VEL_SAMPLES) % VEL_SAMPLES
// Use the sample that is ~100 ms old for a stable estimate
val oldest = (velIdx - velCount + VEL_SAMPLES) % VEL_SAMPLES
val dt = velTimes[newest] - velTimes[oldest]
if (dt <= 0L) return 0f
return (velAngles[newest] - velAngles[oldest]) / dt
}
/**
* Kick off a physics-based fling: uniform deceleration from [initialVel] to zero,
* then snap to the nearest segment.
* Formula: total_rotation = v0² / (2 * DECEL), duration = v0 / DECEL
* With DecelerateInterpolator(1) the initial animation velocity matches v0.
*/
private fun fling(initialVel: Float) {
val DECEL = 0.0008f // deg / ms² — tune for feel
val duration = (abs(initialVel) / DECEL).toLong().coerceIn(200, 3500)
val sign = if (initialVel >= 0f) 1f else -1f
val totalRot = sign * initialVel * initialVel / (2f * DECEL)
val startAngle = wheelAngle
val endAngle = startAngle + totalRot
snapAnimator = ValueAnimator.ofFloat(startAngle, endAngle).apply {
this.duration = duration
interpolator = DecelerateInterpolator() // matches v0 at t=0
addUpdateListener { wheelAngle = it.animatedValue as Float; invalidate() }
addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(a: Animator) { snapToNearest() }
})
start()
}
}
private fun angleAt(x: Float, y: Float): Float =
Math.toDegrees(atan2((y - cy).toDouble(), (x - cx).toDouble())).toFloat()
private fun segmentAt(x: Float, y: Float): Int {
var a = angleAt(x, y) - wheelAngle
a = (a % 360f + 360f) % 360f
return (a / (360f / items.size)).toInt() % items.size
}
private fun animateToSixOClock(index: Int, onDone: () -> Unit) {
val segDeg = 360f / items.size.coerceAtLeast(1)
val midDeg = index * segDeg + segDeg / 2f
// delta needed so this segment's midpoint lands at 90° (6 o'clock in math coords)
var delta = (90f - midDeg) - wheelAngle
// normalise to shortest path [-180, 180]
delta = ((delta % 360f) + 360f) % 360f
if (delta > 180f) delta -= 360f
val endAngle = wheelAngle + delta
snapAnimator?.cancel()
snapAnimator = ValueAnimator.ofFloat(wheelAngle, endAngle).apply {
duration = 350
interpolator = DecelerateInterpolator()
addUpdateListener { wheelAngle = it.animatedValue as Float; invalidate() }
addListener(object : AnimatorListenerAdapter() {
private var cancelled = false
override fun onAnimationCancel(a: Animator) { cancelled = true }
override fun onAnimationEnd(a: Animator) { if (!cancelled) onDone() }
})
start()
}
}
private fun snapToNearest() {
val segDeg = 360f / items.size.coerceAtLeast(1)
val target = (wheelAngle / segDeg).roundToInt() * segDeg
snapAnimator = ValueAnimator.ofFloat(wheelAngle, target).apply {
duration = 300
interpolator = DecelerateInterpolator()
addUpdateListener { wheelAngle = it.animatedValue as Float; invalidate() }
start()
}
}
private fun vibrateDevice() {
val v = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
v.vibrate(VibrationEffect.createOneShot(60, VibrationEffect.DEFAULT_AMPLITUDE))
}
fun shakeLock() {
shakeAnimator?.cancel()
shakeAnimator = ValueAnimator.ofFloat(0f, -18f, 18f, -12f, 12f, -6f, 6f, 0f).apply {
duration = 500
interpolator = LinearInterpolator()
addUpdateListener { lockShakeAngle = it.animatedValue as Float; invalidate() }
addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(a: Animator) { lockShakeAngle = 0f; invalidate() }
})
start()
}
}
fun unlockWheel() {
isWheelLocked = false
lockShakeAngle = 0f
shakeAnimator?.cancel()
invalidate()
}
}

Some files were not shown because too many files have changed in this diff Show More