first implementation

This commit is contained in:
Meghdad committed 2026-06-23 00:21:51 +03:30
1 parent d278a4144d
commit 65444784dd
56 files changed
+3915 -283

No files matched your search

+10 -6
View File
@@ -1,21 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application
android:allowBackup="true"
android:name=".RemainingApplication"
android:allowBackup="false"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:supportsRtl="false"
android:theme="@style/Theme.Remaining">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.Remaining"
android:theme="@style/Theme.Remaining.Starting"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
@@ -25,4 +29,4 @@
</activity>
</application>
</manifest>
</manifest>
@@ -0,0 +1,29 @@
package net.rodakot.remaining
import android.content.Context
import net.rodakot.remaining.connectors.ConnectorRegistry
import net.rodakot.remaining.data.AccountRepository
import net.rodakot.remaining.data.AppDatabase
import net.rodakot.remaining.data.SettingsRepository
import net.rodakot.remaining.network.HttpClients
import net.rodakot.remaining.refresh.NotificationHelper
import net.rodakot.remaining.refresh.RefreshScheduler
import net.rodakot.remaining.security.SecretCipher
class AppContainer(context: Context) {
private val appContext = context.applicationContext
private val database = AppDatabase.getInstance(appContext)
private val httpClient = HttpClients.default()
val settingsRepository = SettingsRepository(appContext)
val notificationHelper = NotificationHelper(appContext)
val connectorRegistry = ConnectorRegistry(httpClient)
val accountRepository = AccountRepository(
dao = database.remainingDao(),
cipher = SecretCipher(),
registry = connectorRegistry,
settingsRepository = settingsRepository,
notifications = notificationHelper
)
val refreshScheduler = RefreshScheduler(appContext)
}
@@ -1,47 +1,63 @@
package net.rodakot.remaining
import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.activity.viewModels
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import net.rodakot.remaining.domain.ThemePreference
import net.rodakot.remaining.ui.RemainingApp
import net.rodakot.remaining.ui.RemainingViewModel
import net.rodakot.remaining.ui.theme.RemainingTheme
class MainActivity : ComponentActivity() {
private val viewModel: RemainingViewModel by viewModels {
RemainingViewModel.Factory((application as RemainingApplication).container)
}
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen()
super.onCreate(savedInstanceState)
enableEdgeToEdge()
requestNotificationPermissionIfNeeded()
setContent {
RemainingTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
Greeting(
name = "Android",
modifier = Modifier.padding(innerPadding)
)
}
val state by viewModel.uiState.collectAsState()
val darkTheme = when (state.settings.themePreference) {
ThemePreference.DARK -> true
ThemePreference.LIGHT -> false
ThemePreference.SYSTEM -> isSystemInDarkTheme()
}
RemainingTheme(darkTheme = darkTheme, dynamicColor = false) {
RemainingApp(state = state, viewModel = viewModel)
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
RemainingTheme {
Greeting("Android")
private fun requestNotificationPermissionIfNeeded() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return
val granted = ContextCompat.checkSelfPermission(
this,
Manifest.permission.POST_NOTIFICATIONS
) == PackageManager.PERMISSION_GRANTED
if (!granted) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.POST_NOTIFICATIONS),
REQUEST_NOTIFICATIONS
)
}
}
}
companion object {
private const val REQUEST_NOTIFICATIONS = 42
}
}
@@ -0,0 +1,25 @@
package net.rodakot.remaining
import android.app.Application
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
class RemainingApplication : Application() {
lateinit var container: AppContainer
private set
private val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
override fun onCreate() {
super.onCreate()
container = AppContainer(this)
container.notificationHelper.ensureChannel()
applicationScope.launch {
container.refreshScheduler.rescheduleAll(
container.accountRepository.getEnabledAccounts()
)
}
}
}
@@ -0,0 +1,20 @@
package net.rodakot.remaining.connectors
import net.rodakot.remaining.connectors.jahannama.JahanNamaConnector
import net.rodakot.remaining.connectors.mci.MciConnector
import net.rodakot.remaining.connectors.tci.TciConnector
import net.rodakot.remaining.domain.ServiceType
import okhttp3.OkHttpClient
class ConnectorRegistry(client: OkHttpClient) {
private val connectors: Map<ServiceType, ServiceConnector> = listOf(
MciConnector(client),
JahanNamaConnector(client),
TciConnector()
).associateBy { it.serviceType }
fun connectorFor(serviceType: ServiceType): ServiceConnector =
connectors.getValue(serviceType)
fun availableServices(): List<ServiceType> = ServiceType.entries
}
@@ -0,0 +1,24 @@
package net.rodakot.remaining.connectors
import net.rodakot.remaining.domain.CaptchaChallenge
import net.rodakot.remaining.domain.ConnectorResult
import net.rodakot.remaining.domain.ServiceType
import net.rodakot.remaining.domain.StoredAccount
import net.rodakot.remaining.domain.StoredSecret
interface ServiceConnector {
val serviceType: ServiceType
suspend fun refresh(
account: StoredAccount,
secret: StoredSecret,
captcha: String? = null
): ConnectorResult
suspend fun prepareCaptcha(
account: StoredAccount,
secret: StoredSecret
): CaptchaChallenge {
error("${serviceType.displayName} does not use captcha")
}
}
@@ -0,0 +1,122 @@
package net.rodakot.remaining.connectors.jahannama
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.rodakot.remaining.connectors.ServiceConnector
import net.rodakot.remaining.domain.AccountStatus
import net.rodakot.remaining.domain.ConnectorResult
import net.rodakot.remaining.domain.RefreshErrorCode
import net.rodakot.remaining.domain.RefreshException
import net.rodakot.remaining.domain.ServiceType
import net.rodakot.remaining.domain.StoredAccount
import net.rodakot.remaining.domain.StoredSecret
import okhttp3.FormBody
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
class JahanNamaConnector(
private val client: OkHttpClient
) : ServiceConnector {
override val serviceType: ServiceType = ServiceType.JAHAN_NAMA
override suspend fun refresh(
account: StoredAccount,
secret: StoredSecret,
captcha: String?
): ConnectorResult = withContext(Dispatchers.IO) {
val tokenSecret = ensureToken(account, secret)
getRemaining(tokenSecret.accessToken.orEmpty()).use { response ->
if (response.code == 401 || response.code == 403) {
val freshSecret = login(account, tokenSecret)
getRemaining(freshSecret.accessToken.orEmpty()).use { retry ->
if (!retry.isSuccessful) {
throw retry.toRefreshException("Jahan Nama remaining traffic request failed")
}
ConnectorResult(
snapshot = JahanNamaParser.parseRemainTraffic(retry.body.string()),
updatedSecret = freshSecret,
status = AccountStatus.ACTIVE
)
}
} else {
if (!response.isSuccessful) {
throw response.toRefreshException("Jahan Nama remaining traffic request failed")
}
ConnectorResult(
snapshot = JahanNamaParser.parseRemainTraffic(response.body.string()),
updatedSecret = tokenSecret,
status = AccountStatus.ACTIVE
)
}
}
}
private fun ensureToken(account: StoredAccount, secret: StoredSecret): StoredSecret {
if (!secret.accessToken.isNullOrBlank()) return secret
return login(account, secret)
}
private fun login(account: StoredAccount, secret: StoredSecret): StoredSecret {
val password = secret.password
?: throw RefreshException(RefreshErrorCode.AUTH, "Jahan Nama password is missing.")
val form = FormBody.Builder()
.add("Username", account.loginIdentifier)
.add("Password", password)
.add("DeviceTypeEnum", "4")
.add("IP", "")
.build()
val request = Request.Builder()
.url("$BASE_URL/api/login/AuthenticateWeb")
.post(form)
.commonHeaders()
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) {
throw response.toRefreshException("Jahan Nama authentication failed")
}
val token = JSONObject(response.body.string()).optString("Token")
if (token.isBlank()) {
throw RefreshException(
RefreshErrorCode.INVALID_RESPONSE,
"Jahan Nama authentication response did not include a token."
)
}
return secret.copy(accessToken = token)
}
}
private fun getRemaining(token: String) =
client.newCall(
Request.Builder()
.url(
"$BASE_URL/api/BaseInfo/GetUserRemain".toHttpUrl()
.newBuilder()
.addQueryParameter("Token", token)
.build()
)
.get()
.commonHeaders()
.build()
).execute()
private fun Request.Builder.commonHeaders(): Request.Builder =
header("Accept", "application/json")
.header("User-Agent", "Mozilla/5.0")
private fun okhttp3.Response.toRefreshException(prefix: String): RefreshException {
val errorCode = when (code) {
401, 403 -> RefreshErrorCode.AUTH
else -> RefreshErrorCode.NETWORK
}
return RefreshException(errorCode, "$prefix (${this.code}).")
}
companion object {
private const val BASE_URL = "https://qomservice.webotel.ir"
}
}
@@ -0,0 +1,37 @@
package net.rodakot.remaining.connectors.jahannama
import net.rodakot.remaining.domain.RefreshErrorCode
import net.rodakot.remaining.domain.RefreshException
import net.rodakot.remaining.domain.UsageSnapshotDraft
import net.rodakot.remaining.domain.asTrafficDisplay
import net.rodakot.remaining.domain.mbToBytes
import org.json.JSONObject
object JahanNamaParser {
fun parseRemainTraffic(body: String): UsageSnapshotDraft {
val json = JSONObject(body)
val raw = json.opt("RemainTraffic")
?: throw RefreshException(
RefreshErrorCode.INVALID_RESPONSE,
"Jahan Nama response did not include RemainTraffic."
)
val megabytes = when (raw) {
is Number -> raw.toDouble()
is String -> raw.toDoubleOrNull()
else -> null
} ?: throw RefreshException(
RefreshErrorCode.INVALID_RESPONSE,
"Jahan Nama RemainTraffic was not numeric."
)
val remainingBytes = mbToBytes(megabytes)
return UsageSnapshotDraft(
remainingBytes = remainingBytes,
totalBytes = null,
remainingDisplay = remainingBytes.asTrafficDisplay(),
totalDisplay = null,
expiresAtText = null,
rawSummary = body
)
}
}
@@ -0,0 +1,154 @@
package net.rodakot.remaining.connectors.mci
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.rodakot.remaining.connectors.ServiceConnector
import net.rodakot.remaining.domain.AccountStatus
import net.rodakot.remaining.domain.ConnectorResult
import net.rodakot.remaining.domain.RefreshErrorCode
import net.rodakot.remaining.domain.RefreshException
import net.rodakot.remaining.domain.ServiceType
import net.rodakot.remaining.domain.StoredAccount
import net.rodakot.remaining.domain.StoredSecret
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
class MciConnector(
private val client: OkHttpClient
) : ServiceConnector {
override val serviceType: ServiceType = ServiceType.MCI
override suspend fun refresh(
account: StoredAccount,
secret: StoredSecret,
captcha: String?
): ConnectorResult = withContext(Dispatchers.IO) {
val tokenSecret = ensureAccessToken(account, secret)
packageDetails(tokenSecret.accessToken.orEmpty()).use { detailsResponse ->
if (detailsResponse.code == 401 || detailsResponse.code == 403) {
val refreshed = refreshAccessToken(account, tokenSecret) ?: login(account, tokenSecret)
packageDetails(refreshed.accessToken.orEmpty()).use { retry ->
if (!retry.isSuccessful) {
throw retry.toRefreshException("MCI package details request failed")
}
ConnectorResult(
snapshot = MciParser.parsePackages(retry.body.string()),
updatedSecret = refreshed,
status = AccountStatus.ACTIVE
)
}
} else {
if (!detailsResponse.isSuccessful) {
throw detailsResponse.toRefreshException("MCI package details request failed")
}
ConnectorResult(
snapshot = MciParser.parsePackages(detailsResponse.body.string()),
updatedSecret = tokenSecret,
status = AccountStatus.ACTIVE
)
}
}
}
private fun ensureAccessToken(account: StoredAccount, secret: StoredSecret): StoredSecret {
if (!secret.accessToken.isNullOrBlank()) return secret
return login(account, secret)
}
private fun refreshAccessToken(account: StoredAccount, secret: StoredSecret): StoredSecret? {
val refreshToken = secret.refreshToken ?: return null
return authenticate(
account = account,
secret = secret,
credentialType = "REFRESH_TOKEN",
credential = refreshToken,
bearer = secret.accessToken
)
}
private fun login(account: StoredAccount, secret: StoredSecret): StoredSecret {
val password = secret.password
?: throw RefreshException(RefreshErrorCode.AUTH, "MCI password is missing.")
return authenticate(
account = account,
secret = secret,
credentialType = "PASSWORD",
credential = password,
bearer = null
) ?: throw RefreshException(RefreshErrorCode.AUTH, "MCI login failed.")
}
private fun authenticate(
account: StoredAccount,
secret: StoredSecret,
credentialType: String,
credential: String,
bearer: String?
): StoredSecret? {
val json = JSONObject()
.put("username", account.loginIdentifier)
.put("credential", credential)
.put("credential_type", credentialType)
.toString()
val requestBuilder = Request.Builder()
.url("$BASE_URL/api/idm/v1/auth")
.post(json.toRequestBody(JSON))
.mciHeaders()
if (!bearer.isNullOrBlank()) {
requestBuilder.header("Authorization", "Bearer $bearer")
}
client.newCall(requestBuilder.build()).execute().use { response ->
if (!response.isSuccessful) {
if (credentialType == "REFRESH_TOKEN") return null
throw response.toRefreshException("MCI authentication failed")
}
val body = JSONObject(response.body.string())
val accessToken = body.optString("access_token")
val refreshToken = body.optString("refresh_token")
if (accessToken.isBlank()) {
throw RefreshException(RefreshErrorCode.INVALID_RESPONSE, "MCI login response did not include an access token.")
}
return secret.copy(
accessToken = accessToken,
refreshToken = refreshToken.takeIf { it.isNotBlank() } ?: secret.refreshToken
)
}
}
private fun packageDetails(accessToken: String) =
client.newCall(
Request.Builder()
.url("$BASE_URL/api/unit/v1/packages/details")
.get()
.mciHeaders()
.header("Authorization", "Bearer $accessToken")
.build()
).execute()
private fun Request.Builder.mciHeaders(): Request.Builder =
header("User-Agent", "Mozilla/5.0")
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.header("Origin", BASE_URL)
.header("Referer", BASE_URL)
.header("platform", "WEB")
.header("version", "1.29.0")
private fun okhttp3.Response.toRefreshException(prefix: String): RefreshException {
val code = when (code) {
401, 403 -> RefreshErrorCode.AUTH
else -> RefreshErrorCode.NETWORK
}
return RefreshException(code, "$prefix (${this.code}).")
}
companion object {
private const val BASE_URL = "https://my.mci.ir"
private val JSON = "application/json; charset=utf-8".toMediaType()
}
}
@@ -0,0 +1,103 @@
package net.rodakot.remaining.connectors.mci
import net.rodakot.remaining.domain.UsagePackageDraft
import net.rodakot.remaining.domain.UsageSnapshotDraft
import net.rodakot.remaining.domain.asTrafficDisplay
import net.rodakot.remaining.domain.unitAmountToBytes
import org.json.JSONObject
import java.time.LocalDateTime
import java.time.ZoneId
object MciParser {
fun parsePackages(body: String): UsageSnapshotDraft {
val json = JSONObject(body)
val remainingValue = json.optDouble("totalUnusedBytes", Double.NaN)
val remainingUnit = json.optString("bytesUnusedUnit", json.optString("bytesUnit", ""))
val totalValue = json.optDouble("totalInitBytes", Double.NaN)
val totalUnit = json.optString("bytesInitUnit", json.optString("bytesUnit", ""))
val remainingBytes = if (remainingValue.isNaN()) null else unitAmountToBytes(remainingValue, remainingUnit)
val totalBytes = if (totalValue.isNaN()) null else unitAmountToBytes(totalValue, totalUnit)
val packages = buildList {
val items = json.optJSONArray("packageItems") ?: return@buildList
for (index in 0 until items.length()) {
val item = items.optJSONObject(index) ?: continue
val name = item.optString("offerName", "Internet package")
val itemRemaining = item.optDouble("totalUnusedValue", Double.NaN)
val itemTotal = item.optDouble("totalInitValue", Double.NaN)
val itemRemainingUnit = item.optString("unUsedUnitName", item.optString("totalUnitName", ""))
val itemTotalUnit = item.optString("totalUnitName", itemRemainingUnit)
val itemRemainingBytes = if (itemRemaining.isNaN()) {
parseItemDetailBytes(item, "unusedAmount")
} else {
unitAmountToBytes(itemRemaining, itemRemainingUnit)
}
val itemTotalBytes = if (itemTotal.isNaN()) {
parseItemDetailBytes(item, "initAmount")
} else {
unitAmountToBytes(itemTotal, itemTotalUnit)
}
add(
UsagePackageDraft(
name = name,
remainingBytes = itemRemainingBytes,
totalBytes = itemTotalBytes,
remainingDisplay = itemRemainingBytes?.asTrafficDisplay()
?: item.optString("remainingDays", "Unknown"),
expiresAtText = item.optNonBlank("formattedExpireTime")
?: item.optNonBlank("expireTime"),
expiresAtMillis = item.optNonBlank("expireTime")?.toEpochMillisOrNull(),
statusText = item.optNonBlank("packageStatusText")
?: item.optNonBlank("packageStatus"),
detail = item.optJSONArray("itemDetails")?.let { details ->
buildList {
for (detailIndex in 0 until details.length()) {
val detail = details.optJSONObject(detailIndex) ?: continue
detail.optString("shortName").takeIf { it.isNotBlank() }?.let(::add)
}
}.joinToString()
}
)
)
}
}
return UsageSnapshotDraft(
remainingBytes = remainingBytes,
totalBytes = totalBytes,
remainingDisplay = remainingBytes?.asTrafficDisplay() ?: "Unknown",
totalDisplay = totalBytes?.asTrafficDisplay(),
expiresAtText = packages.firstOrNull { it.expiresAtText != null }?.expiresAtText,
expiresAtMillis = packages.mapNotNull { it.expiresAtMillis }.minOrNull(),
packages = packages,
rawSummary = body
)
}
private fun parseItemDetailBytes(item: JSONObject, field: String): Long? {
val details = item.optJSONArray("itemDetails") ?: return null
var total = 0L
var found = false
for (index in 0 until details.length()) {
val value = details.optJSONObject(index)?.optLong(field, -1L) ?: -1L
if (value >= 0L) {
total += value
found = true
}
}
return total.takeIf { found }
}
private fun JSONObject.optNonBlank(key: String): String? =
optString(key).takeIf { it.isNotBlank() }
private fun String.toEpochMillisOrNull(): Long? =
runCatching {
LocalDateTime.parse(this)
.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli()
}.getOrNull()
}
@@ -0,0 +1,159 @@
package net.rodakot.remaining.connectors.tci
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.rodakot.remaining.connectors.ServiceConnector
import net.rodakot.remaining.domain.AccountStatus
import net.rodakot.remaining.domain.CaptchaChallenge
import net.rodakot.remaining.domain.ConnectorResult
import net.rodakot.remaining.domain.RefreshErrorCode
import net.rodakot.remaining.domain.RefreshException
import net.rodakot.remaining.domain.ServiceType
import net.rodakot.remaining.domain.StoredAccount
import net.rodakot.remaining.domain.StoredSecret
import net.rodakot.remaining.network.HttpClients
import net.rodakot.remaining.network.MutableCookieJar
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
class TciConnector : ServiceConnector {
override val serviceType: ServiceType = ServiceType.TCI
override suspend fun prepareCaptcha(
account: StoredAccount,
secret: StoredSecret
): CaptchaChallenge = withContext(Dispatchers.IO) {
val cookieJar = MutableCookieJar(TciCookieCodec.decode(secret.cookieJar))
val client = HttpClients.withCookieJar(cookieJar)
val panelHtml = client.newCall(browserGet("$BASE_URL/panel")).execute().use { response ->
if (!response.isSuccessful) {
throw response.toRefreshException("TCI panel request failed")
}
response.body.string()
}
if (TciHtmlParser.isAuthenticated(panelHtml)) {
throw RefreshException(RefreshErrorCode.UNKNOWN, "TCI session is already authenticated.")
}
val loginPage = TciHtmlParser.parseLoginPage(panelHtml, BASE_URL)
val imageBytes = client.newCall(browserGet(loginPage.captchaImageUrl)).execute().use { response ->
if (!response.isSuccessful) {
throw response.toRefreshException("TCI captcha download failed")
}
response.body.bytes()
}
if (imageBytes.isEmpty()) {
throw RefreshException(RefreshErrorCode.INVALID_RESPONSE, "TCI captcha image was empty.")
}
CaptchaChallenge(
imageBytes = imageBytes,
updatedSecret = secret.copy(
cookieJar = TciCookieCodec.encode(cookieJar.allCookies()),
sessionPayload = loginPage.loginActionUrl
)
)
}
override suspend fun refresh(
account: StoredAccount,
secret: StoredSecret,
captcha: String?
): ConnectorResult = withContext(Dispatchers.IO) {
val cookieJar = MutableCookieJar(TciCookieCodec.decode(secret.cookieJar))
val client = HttpClients.withCookieJar(cookieJar)
val effectiveSecret = if (!captcha.isNullOrBlank()) {
loginWithCaptcha(client, cookieJar, account, secret, captcha)
} else {
secret
}
val panelHtml = client.newCall(browserGet("$BASE_URL/panel")).execute().use { response ->
if (!response.isSuccessful) {
throw response.toRefreshException("TCI panel request failed")
}
response.body.string()
}
if (!TciHtmlParser.isAuthenticated(panelHtml)) {
throw RefreshException(
RefreshErrorCode.CAPTCHA_REQUIRED,
"TCI session expired. Complete captcha to sign in again."
)
}
ConnectorResult(
snapshot = TciHtmlParser.parseReservedTraffic(panelHtml),
updatedSecret = effectiveSecret.copy(
cookieJar = TciCookieCodec.encode(cookieJar.allCookies()),
sessionPayload = null
),
status = AccountStatus.ACTIVE
)
}
private fun loginWithCaptcha(
client: OkHttpClient,
cookieJar: MutableCookieJar,
account: StoredAccount,
secret: StoredSecret,
captcha: String
): StoredSecret {
val password = secret.password
?: throw RefreshException(RefreshErrorCode.AUTH, "TCI password is missing.")
val actionUrl = secret.sessionPayload
?: throw RefreshException(
RefreshErrorCode.CAPTCHA_REQUIRED,
"TCI captcha session is missing. Download a new captcha."
)
val form = FormBody.Builder()
.add("username", account.loginIdentifier)
.add("password", password)
.add("captcha", captcha)
.add("redirect", "")
.add("LoginFromWeb", "1")
.build()
client.newCall(
Request.Builder()
.url(actionUrl)
.post(form)
.header("User-Agent", "Mozilla/5.0")
.header("Accept", "text/html,application/xhtml+xml,application/xml")
.build()
).execute().use { response ->
if (!response.isSuccessful) {
throw response.toRefreshException("TCI login failed")
}
response.body.close()
}
return secret.copy(
cookieJar = TciCookieCodec.encode(cookieJar.allCookies()),
sessionPayload = null
)
}
private fun browserGet(url: String): Request =
Request.Builder()
.url(url)
.get()
.header("User-Agent", "Mozilla/5.0")
.header("Accept", "text/html,application/xhtml+xml,application/xml")
.build()
private fun okhttp3.Response.toRefreshException(prefix: String): RefreshException {
val errorCode = when (code) {
401, 403 -> RefreshErrorCode.SESSION_EXPIRED
else -> RefreshErrorCode.NETWORK
}
return RefreshException(errorCode, "$prefix (${this.code}).")
}
companion object {
private const val BASE_URL = "https://internet.tci.ir"
}
}
@@ -0,0 +1,45 @@
package net.rodakot.remaining.connectors.tci
import okhttp3.Cookie
import org.json.JSONArray
import org.json.JSONObject
object TciCookieCodec {
fun encode(cookies: List<Cookie>): String {
val array = JSONArray()
cookies.forEach { cookie ->
array.put(
JSONObject()
.put("name", cookie.name)
.put("value", cookie.value)
.put("domain", cookie.domain)
.put("path", cookie.path)
.put("expiresAt", cookie.expiresAt)
.put("secure", cookie.secure)
.put("httpOnly", cookie.httpOnly)
)
}
return array.toString()
}
fun decode(payload: String?): List<Cookie> {
if (payload.isNullOrBlank()) return emptyList()
val array = JSONArray(payload)
return buildList {
for (index in 0 until array.length()) {
val json = array.optJSONObject(index) ?: continue
runCatching {
val builder = Cookie.Builder()
.name(json.optString("name"))
.value(json.optString("value"))
.domain(json.optString("domain"))
.path(json.optString("path", "/"))
.expiresAt(json.optLong("expiresAt", Long.MAX_VALUE))
if (json.optBoolean("secure")) builder.secure()
if (json.optBoolean("httpOnly")) builder.httpOnly()
builder.build()
}.getOrNull()?.let(::add)
}
}
}
}
@@ -0,0 +1,100 @@
package net.rodakot.remaining.connectors.tci
import net.rodakot.remaining.domain.RefreshErrorCode
import net.rodakot.remaining.domain.RefreshException
import net.rodakot.remaining.domain.UsageSnapshotDraft
import net.rodakot.remaining.domain.asTrafficDisplay
import net.rodakot.remaining.domain.unitAmountToBytes
import org.jsoup.Jsoup
import java.util.Locale
data class TciLoginPage(
val loginActionUrl: String,
val captchaImageUrl: String
)
object TciHtmlParser {
private const val RESERVED_TRAFFIC_LABEL = "میزان ترافیک رزرو شما"
fun isAuthenticated(html: String): Boolean {
val lower = html.lowercase(Locale.US)
return lower.contains("logout") || html.contains("خروج")
}
fun parseLoginPage(html: String, baseUrl: String): TciLoginPage {
val document = Jsoup.parse(html, baseUrl)
val action = document.selectFirst("form[action]")?.absUrl("action")
?.takeIf { it.isNotBlank() }
?: throw RefreshException(
RefreshErrorCode.PARSER_CHANGED,
"TCI login form action was not found."
)
val captcha = document.selectFirst("#loginCaptchaImage")?.absUrl("src")
?.takeIf { it.isNotBlank() }
?: throw RefreshException(
RefreshErrorCode.PARSER_CHANGED,
"TCI captcha image was not found."
)
return TciLoginPage(action, captcha)
}
fun parseReservedTraffic(html: String): UsageSnapshotDraft {
val document = Jsoup.parse(html)
val candidateTexts = document.select("h5, h4, h3, div, span")
.filter { it.text().contains(RESERVED_TRAFFIC_LABEL) }
.flatMap { element ->
listOfNotNull(element.text(), element.parent()?.text())
}
.ifEmpty { listOf(document.text()) }
val match = candidateTexts
.asSequence()
.map { normalizeDigits(it) }
.mapNotNull { TRAFFIC_REGEX.find(it) }
.firstOrNull()
?: throw RefreshException(
RefreshErrorCode.PARSER_CHANGED,
"TCI reserved traffic value was not found."
)
val value = match.groupValues[1].toDoubleOrNull()
?: throw RefreshException(
RefreshErrorCode.INVALID_RESPONSE,
"TCI reserved traffic value was not numeric."
)
val unit = match.groupValues[2]
val remainingBytes = unitAmountToBytes(value, unit)
return UsageSnapshotDraft(
remainingBytes = remainingBytes,
totalBytes = null,
remainingDisplay = remainingBytes.asTrafficDisplay(),
totalDisplay = null,
expiresAtText = null,
rawSummary = normalizeDigits(match.value)
)
}
fun normalizeDigits(value: String): String =
buildString(value.length) {
value.forEach { char ->
append(
when (char) {
'۰', '٠' -> '0'
'۱', '١' -> '1'
'۲', '٢' -> '2'
'۳', '٣' -> '3'
'۴', '٤' -> '4'
'۵', '٥' -> '5'
'۶', '٦' -> '6'
'۷', '٧' -> '7'
'۸', '٨' -> '8'
'۹', '٩' -> '9'
'٫' -> '.'
else -> char
}
)
}
}
private val TRAFFIC_REGEX = Regex("""(\d+(?:\.\d+)?)\s*(گیگابایت|مگابایت|GB|MB)""", RegexOption.IGNORE_CASE)
}
@@ -0,0 +1,380 @@
package net.rodakot.remaining.data
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import net.rodakot.remaining.connectors.ConnectorRegistry
import net.rodakot.remaining.domain.AccountStatus
import net.rodakot.remaining.domain.CaptchaChallenge
import net.rodakot.remaining.domain.RefreshErrorCode
import net.rodakot.remaining.domain.RefreshException
import net.rodakot.remaining.domain.RefreshInterval
import net.rodakot.remaining.domain.ServiceType
import net.rodakot.remaining.domain.StoredAccount
import net.rodakot.remaining.domain.StoredSecret
import net.rodakot.remaining.domain.UsageSnapshotDraft
import net.rodakot.remaining.domain.asTrafficDisplay
import net.rodakot.remaining.refresh.NotificationHelper
import net.rodakot.remaining.security.SecretCipher
import java.io.IOException
data class CreateAccountRequest(
val serviceType: ServiceType,
val displayName: String,
val loginIdentifier: String,
val password: String,
val refreshIntervalMinutes: Long,
val alertsEnabled: Boolean = true,
val lowDataThresholdMb: Long = 1024,
val expiryThresholdDays: Int = 3
)
data class RefreshRunResult(
val success: Boolean,
val retryable: Boolean,
val message: String? = null
)
class AccountRepository(
private val dao: RemainingDao,
private val cipher: SecretCipher,
private val registry: ConnectorRegistry,
private val settingsRepository: SettingsRepository,
private val notifications: NotificationHelper
) {
fun observeAccountSummaries(): Flow<List<AccountSummary>> =
combine(
dao.observeAccounts(),
dao.observeLatestSnapshots()
) { accounts, snapshots ->
val snapshotByAccount = snapshots.associateBy { it.accountId }
accounts.map { account -> account.toSummary(snapshotByAccount[account.id]) }
}
fun observeAccount(accountId: String): Flow<AccountEntity?> = dao.observeAccount(accountId)
suspend fun getEnabledAccounts(): List<AccountEntity> = dao.getEnabledAccounts()
@OptIn(ExperimentalCoroutinesApi::class)
fun observeAccountDetail(accountId: String): Flow<AccountDetail?> {
val summaryFlow = combine(
dao.observeAccount(accountId),
dao.observeLatestSnapshot(accountId)
) { account, snapshot ->
account?.toSummary(snapshot)
}
val packagesFlow = dao.observeLatestSnapshot(accountId).flatMapLatest { snapshot ->
snapshot?.let { dao.observePackages(it.id) } ?: flowOf(emptyList())
}
return combine(summaryFlow, packagesFlow) { summary, packages ->
summary?.let { AccountDetail(it, packages) }
}
}
suspend fun createAccount(request: CreateAccountRequest): AccountEntity {
val now = System.currentTimeMillis()
val account = AccountEntity(
serviceType = request.serviceType.id,
displayName = request.displayName.ifBlank { request.loginIdentifier },
loginIdentifier = request.loginIdentifier,
refreshIntervalMinutes = request.refreshIntervalMinutes,
status = if (request.serviceType == ServiceType.TCI) {
AccountStatus.CAPTCHA_REQUIRED.name
} else {
AccountStatus.NEEDS_AUTH.name
},
alertsEnabled = request.alertsEnabled,
lowDataThresholdMb = request.lowDataThresholdMb,
expiryThresholdDays = request.expiryThresholdDays,
createdAt = now,
updatedAt = now,
nextRefreshAt = now + request.refreshIntervalMinutes * 60_000L
)
dao.upsertAccount(account)
dao.upsertSecret(
AccountSecretEntity(
accountId = account.id,
encryptedPassword = cipher.encrypt(request.password)
)
)
return account
}
suspend fun updateAccountSettings(
accountId: String,
interval: RefreshInterval,
alertsEnabled: Boolean,
lowDataThresholdMb: Long,
expiryThresholdDays: Int,
enabled: Boolean
) {
val current = dao.getAccount(accountId) ?: return
dao.updateAccountSettings(
accountId = accountId,
minutes = interval.minutes,
alertsEnabled = alertsEnabled,
lowDataThresholdMb = lowDataThresholdMb,
expiryThresholdDays = expiryThresholdDays,
enabled = enabled,
status = when {
!enabled -> AccountStatus.DISABLED.name
current.accountStatus == AccountStatus.DISABLED -> AccountStatus.NEEDS_AUTH.name
else -> current.status
},
updatedAt = System.currentTimeMillis()
)
}
suspend fun deleteAccount(accountId: String) {
dao.deleteAccount(accountId)
}
suspend fun prepareCaptcha(accountId: String): CaptchaChallenge {
val account = dao.getAccount(accountId) ?: throw RefreshException(
RefreshErrorCode.UNKNOWN,
"Account was not found."
)
val secret = dao.getSecret(accountId)?.toStoredSecret()
?: throw RefreshException(RefreshErrorCode.AUTH, "Account secret was not found.")
val connector = registry.connectorFor(account.service)
val challenge = connector.prepareCaptcha(account.toStoredAccount(), secret)
dao.upsertSecret(challenge.updatedSecret.toEntity(accountId))
dao.updateRefreshState(
accountId = accountId,
status = AccountStatus.CAPTCHA_REQUIRED.name,
updatedAt = System.currentTimeMillis(),
lastRefreshAt = account.lastRefreshAt,
lastSuccessAt = account.lastSuccessAt,
nextRefreshAt = account.nextRefreshAt,
lastErrorCode = RefreshErrorCode.CAPTCHA_REQUIRED.name,
lastErrorMessage = "Enter the captcha shown by ${account.service.displayName}."
)
return challenge
}
suspend fun refreshAccount(
accountId: String,
captcha: String? = null,
notify: Boolean = false
): RefreshRunResult {
val account = dao.getAccount(accountId)
?: return RefreshRunResult(false, retryable = false, message = "Account was not found.")
if (!account.enabled && captcha.isNullOrBlank()) {
return RefreshRunResult(false, retryable = false, message = "Account is disabled.")
}
val now = System.currentTimeMillis()
dao.updateRefreshState(
accountId = accountId,
status = AccountStatus.REFRESHING.name,
updatedAt = now,
lastRefreshAt = now,
lastSuccessAt = account.lastSuccessAt,
nextRefreshAt = account.nextRefreshAt,
lastErrorCode = null,
lastErrorMessage = null
)
return try {
val secret = dao.getSecret(accountId)?.toStoredSecret()
?: throw RefreshException(RefreshErrorCode.AUTH, "Account secret was not found.")
val connector = registry.connectorFor(account.service)
val result = connector.refresh(account.toStoredAccount(), secret, captcha)
dao.upsertSecret(result.updatedSecret.toEntity(accountId))
saveSnapshot(account, result.snapshot)
val successAt = System.currentTimeMillis()
dao.updateRefreshState(
accountId = accountId,
status = result.status.name,
updatedAt = successAt,
lastRefreshAt = successAt,
lastSuccessAt = successAt,
nextRefreshAt = successAt + account.refreshIntervalMinutes * 60_000L,
lastErrorCode = null,
lastErrorMessage = null
)
maybeNotifyLowData(account, result.snapshot, notify)
maybeNotifyExpiry(account, result.snapshot, notify)
RefreshRunResult(success = true, retryable = false)
} catch (throwable: Throwable) {
if (throwable is CancellationException) throw throwable
val error = throwable.asRefreshException()
val failedAt = System.currentTimeMillis()
val status = when (error.code) {
RefreshErrorCode.CAPTCHA_REQUIRED -> AccountStatus.CAPTCHA_REQUIRED
RefreshErrorCode.AUTH, RefreshErrorCode.SESSION_EXPIRED -> AccountStatus.NEEDS_AUTH
else -> AccountStatus.ERROR
}
dao.updateRefreshState(
accountId = accountId,
status = status.name,
updatedAt = failedAt,
lastRefreshAt = failedAt,
lastSuccessAt = account.lastSuccessAt,
nextRefreshAt = failedAt + account.refreshIntervalMinutes * 60_000L,
lastErrorCode = error.code.name,
lastErrorMessage = error.message
)
maybeNotifyFailure(account, error, notify)
RefreshRunResult(
success = false,
retryable = error.code == RefreshErrorCode.NETWORK,
message = error.message
)
}
}
private suspend fun saveSnapshot(account: AccountEntity, draft: UsageSnapshotDraft) {
val snapshot = UsageSnapshotEntity(
accountId = account.id,
serviceType = account.serviceType,
remainingBytes = draft.remainingBytes,
totalBytes = draft.totalBytes,
remainingDisplay = draft.remainingDisplay,
totalDisplay = draft.totalDisplay,
expiresAtText = draft.expiresAtText,
expiresAtMillis = draft.expiresAtMillis,
capturedAt = draft.capturedAt,
rawSummary = draft.rawSummary
)
val packages = draft.packages.map { pkg ->
UsagePackageEntity(
snapshotId = snapshot.id,
name = pkg.name,
remainingBytes = pkg.remainingBytes,
totalBytes = pkg.totalBytes,
remainingDisplay = pkg.remainingDisplay,
expiresAtText = pkg.expiresAtText,
expiresAtMillis = pkg.expiresAtMillis,
statusText = pkg.statusText,
detail = pkg.detail
)
}
dao.insertSnapshotWithPackages(snapshot, packages)
}
private fun maybeNotifyLowData(
account: AccountEntity,
snapshot: UsageSnapshotDraft,
notify: Boolean
) {
if (!notify || !shouldNotify(account) || snapshot.remainingBytes == null) return
val thresholdBytes = account.lowDataThresholdMb * 1024L * 1024L
if (snapshot.remainingBytes <= thresholdBytes) {
notifications.showAccountAlert(
account.id,
"${account.displayName} is low on data",
"${snapshot.remainingDisplay} remains for ${account.service.displayName}."
)
}
}
private fun maybeNotifyExpiry(
account: AccountEntity,
snapshot: UsageSnapshotDraft,
notify: Boolean
) {
if (!notify || !shouldNotify(account) || snapshot.expiresAtMillis == null) return
val thresholdMillis = account.expiryThresholdDays * 24L * 60L * 60L * 1000L
val remainingMillis = snapshot.expiresAtMillis - System.currentTimeMillis()
if (remainingMillis in 0..thresholdMillis) {
notifications.showAccountAlert(
account.id,
"${account.displayName} expires soon",
"${account.service.displayName} package expires ${snapshot.expiresAtText ?: "soon"}."
)
}
}
private fun maybeNotifyFailure(
account: AccountEntity,
error: RefreshException,
notify: Boolean
) {
if (!notify || !shouldNotify(account)) return
notifications.showAccountAlert(
account.id,
"${account.displayName}: ${error.code.displayName}",
error.message
)
}
private fun shouldNotify(account: AccountEntity): Boolean =
account.alertsEnabled && settingsRepository.settings.value.notificationsEnabled
private fun AccountEntity.toStoredAccount(): StoredAccount =
StoredAccount(
id = id,
serviceType = service,
displayName = displayName,
loginIdentifier = loginIdentifier,
refreshIntervalMinutes = refreshIntervalMinutes,
alertsEnabled = alertsEnabled,
lowDataThresholdMb = lowDataThresholdMb,
expiryThresholdDays = expiryThresholdDays,
enabled = enabled
)
private fun AccountEntity.toSummary(snapshot: UsageSnapshotEntity?): AccountSummary =
AccountSummary(
id = id,
serviceType = service,
displayName = displayName,
loginIdentifier = loginIdentifier,
status = accountStatus,
enabled = enabled,
alertsEnabled = alertsEnabled,
lowDataThresholdMb = lowDataThresholdMb,
expiryThresholdDays = expiryThresholdDays,
refreshInterval = RefreshInterval.fromMinutes(refreshIntervalMinutes),
remainingBytes = snapshot?.remainingBytes,
totalBytes = snapshot?.totalBytes,
remainingDisplay = snapshot?.remainingDisplay ?: "No data yet",
totalDisplay = snapshot?.totalDisplay,
expiresAtText = snapshot?.expiresAtText,
expiresAtMillis = snapshot?.expiresAtMillis,
lastRefreshAt = lastRefreshAt,
lastSuccessAt = lastSuccessAt,
nextRefreshAt = nextRefreshAt,
lastErrorCode = lastErrorCode,
lastErrorMessage = lastErrorMessage
)
private fun AccountSecretEntity.toStoredSecret(): StoredSecret =
StoredSecret(
password = cipher.decrypt(encryptedPassword),
accessToken = cipher.decrypt(encryptedAccessToken),
refreshToken = cipher.decrypt(encryptedRefreshToken),
cookieJar = cipher.decrypt(encryptedCookieJar),
sessionPayload = cipher.decrypt(encryptedSessionPayload)
)
private fun StoredSecret.toEntity(accountId: String): AccountSecretEntity =
AccountSecretEntity(
accountId = accountId,
encryptedPassword = cipher.encrypt(password),
encryptedAccessToken = cipher.encrypt(accessToken),
encryptedRefreshToken = cipher.encrypt(refreshToken),
encryptedCookieJar = cipher.encrypt(cookieJar),
encryptedSessionPayload = cipher.encrypt(sessionPayload)
)
private fun Throwable.asRefreshException(): RefreshException =
when (this) {
is RefreshException -> this
is IOException -> RefreshException(
RefreshErrorCode.NETWORK,
message ?: "Network request failed.",
this
)
else -> RefreshException(
RefreshErrorCode.UNKNOWN,
message ?: "Unexpected refresh failure.",
this
)
}
}
@@ -0,0 +1,37 @@
package net.rodakot.remaining.data
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(
entities = [
AccountEntity::class,
AccountSecretEntity::class,
UsageSnapshotEntity::class,
UsagePackageEntity::class
],
version = 1,
exportSchema = false
)
abstract class AppDatabase : RoomDatabase() {
abstract fun remainingDao(): RemainingDao
companion object {
@Volatile
private var instance: AppDatabase? = null
fun getInstance(context: Context): AppDatabase =
instance ?: synchronized(this) {
instance ?: Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"remaining.db"
)
.fallbackToDestructiveMigration(true)
.build()
.also { instance = it }
}
}
}
@@ -0,0 +1,34 @@
package net.rodakot.remaining.data
import net.rodakot.remaining.domain.AccountStatus
import net.rodakot.remaining.domain.RefreshInterval
import net.rodakot.remaining.domain.ServiceType
data class AccountSummary(
val id: String,
val serviceType: ServiceType,
val displayName: String,
val loginIdentifier: String,
val status: AccountStatus,
val enabled: Boolean,
val alertsEnabled: Boolean,
val lowDataThresholdMb: Long,
val expiryThresholdDays: Int,
val refreshInterval: RefreshInterval,
val remainingBytes: Long?,
val totalBytes: Long?,
val remainingDisplay: String,
val totalDisplay: String?,
val expiresAtText: String?,
val expiresAtMillis: Long?,
val lastRefreshAt: Long?,
val lastSuccessAt: Long?,
val nextRefreshAt: Long?,
val lastErrorCode: String?,
val lastErrorMessage: String?
)
data class AccountDetail(
val summary: AccountSummary,
val packages: List<UsagePackageEntity>
)
@@ -0,0 +1,112 @@
package net.rodakot.remaining.data
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import net.rodakot.remaining.domain.AccountStatus
import net.rodakot.remaining.domain.RefreshInterval
import net.rodakot.remaining.domain.ServiceType
import java.util.UUID
@Entity(
tableName = "accounts",
indices = [Index("serviceType"), Index("status")]
)
data class AccountEntity(
@PrimaryKey val id: String = UUID.randomUUID().toString(),
val serviceType: String,
val displayName: String,
val loginIdentifier: String,
val refreshIntervalMinutes: Long = RefreshInterval.HOURLY.minutes,
val status: String = AccountStatus.NEEDS_AUTH.name,
val enabled: Boolean = true,
val alertsEnabled: Boolean = true,
val lowDataThresholdMb: Long = 1024,
val expiryThresholdDays: Int = 3,
val createdAt: Long = System.currentTimeMillis(),
val updatedAt: Long = System.currentTimeMillis(),
val lastRefreshAt: Long? = null,
val lastSuccessAt: Long? = null,
val nextRefreshAt: Long? = null,
val lastErrorCode: String? = null,
val lastErrorMessage: String? = null
) {
val service: ServiceType
get() = ServiceType.fromId(serviceType)
val accountStatus: AccountStatus
get() = runCatching { AccountStatus.valueOf(status) }.getOrDefault(AccountStatus.ERROR)
}
@Entity(
tableName = "account_secrets",
foreignKeys = [
ForeignKey(
entity = AccountEntity::class,
parentColumns = ["id"],
childColumns = ["accountId"],
onDelete = ForeignKey.CASCADE
)
],
indices = [Index("accountId")]
)
data class AccountSecretEntity(
@PrimaryKey val accountId: String,
val encryptedPassword: String?,
val encryptedAccessToken: String? = null,
val encryptedRefreshToken: String? = null,
val encryptedCookieJar: String? = null,
val encryptedSessionPayload: String? = null
)
@Entity(
tableName = "usage_snapshots",
foreignKeys = [
ForeignKey(
entity = AccountEntity::class,
parentColumns = ["id"],
childColumns = ["accountId"],
onDelete = ForeignKey.CASCADE
)
],
indices = [Index("accountId"), Index("capturedAt")]
)
data class UsageSnapshotEntity(
@PrimaryKey val id: String = UUID.randomUUID().toString(),
val accountId: String,
val serviceType: String,
val remainingBytes: Long?,
val totalBytes: Long?,
val remainingDisplay: String,
val totalDisplay: String?,
val expiresAtText: String?,
val expiresAtMillis: Long?,
val capturedAt: Long,
val rawSummary: String?
)
@Entity(
tableName = "usage_packages",
foreignKeys = [
ForeignKey(
entity = UsageSnapshotEntity::class,
parentColumns = ["id"],
childColumns = ["snapshotId"],
onDelete = ForeignKey.CASCADE
)
],
indices = [Index("snapshotId")]
)
data class UsagePackageEntity(
@PrimaryKey val id: String = UUID.randomUUID().toString(),
val snapshotId: String,
val name: String,
val remainingBytes: Long?,
val totalBytes: Long?,
val remainingDisplay: String,
val expiresAtText: String?,
val expiresAtMillis: Long?,
val statusText: String?,
val detail: String?
)
@@ -0,0 +1,136 @@
package net.rodakot.remaining.data
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import kotlinx.coroutines.flow.Flow
@Dao
interface RemainingDao {
@Query("SELECT * FROM accounts ORDER BY serviceType, displayName")
fun observeAccounts(): Flow<List<AccountEntity>>
@Query("SELECT * FROM accounts WHERE id = :accountId")
fun observeAccount(accountId: String): Flow<AccountEntity?>
@Query("SELECT * FROM accounts WHERE id = :accountId LIMIT 1")
suspend fun getAccount(accountId: String): AccountEntity?
@Query("SELECT * FROM accounts WHERE enabled = 1")
suspend fun getEnabledAccounts(): List<AccountEntity>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertAccount(account: AccountEntity)
@Query("DELETE FROM accounts WHERE id = :accountId")
suspend fun deleteAccount(accountId: String)
@Query(
"""
UPDATE accounts
SET status = :status,
updatedAt = :updatedAt,
lastRefreshAt = :lastRefreshAt,
lastSuccessAt = :lastSuccessAt,
nextRefreshAt = :nextRefreshAt,
lastErrorCode = :lastErrorCode,
lastErrorMessage = :lastErrorMessage
WHERE id = :accountId
"""
)
suspend fun updateRefreshState(
accountId: String,
status: String,
updatedAt: Long,
lastRefreshAt: Long?,
lastSuccessAt: Long?,
nextRefreshAt: Long?,
lastErrorCode: String?,
lastErrorMessage: String?
)
@Query(
"""
UPDATE accounts
SET refreshIntervalMinutes = :minutes,
alertsEnabled = :alertsEnabled,
lowDataThresholdMb = :lowDataThresholdMb,
expiryThresholdDays = :expiryThresholdDays,
enabled = :enabled,
status = :status,
updatedAt = :updatedAt
WHERE id = :accountId
"""
)
suspend fun updateAccountSettings(
accountId: String,
minutes: Long,
alertsEnabled: Boolean,
lowDataThresholdMb: Long,
expiryThresholdDays: Int,
enabled: Boolean,
status: String,
updatedAt: Long
)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertSecret(secret: AccountSecretEntity)
@Query("SELECT * FROM account_secrets WHERE accountId = :accountId LIMIT 1")
suspend fun getSecret(accountId: String): AccountSecretEntity?
@Query(
"""
SELECT * FROM usage_snapshots
WHERE capturedAt = (
SELECT MAX(innerSnapshot.capturedAt)
FROM usage_snapshots AS innerSnapshot
WHERE innerSnapshot.accountId = usage_snapshots.accountId
)
ORDER BY capturedAt DESC
"""
)
fun observeLatestSnapshots(): Flow<List<UsageSnapshotEntity>>
@Query(
"""
SELECT * FROM usage_snapshots
WHERE accountId = :accountId
ORDER BY capturedAt DESC
LIMIT 1
"""
)
fun observeLatestSnapshot(accountId: String): Flow<UsageSnapshotEntity?>
@Query(
"""
SELECT * FROM usage_snapshots
WHERE accountId = :accountId
ORDER BY capturedAt DESC
LIMIT 1
"""
)
suspend fun getLatestSnapshot(accountId: String): UsageSnapshotEntity?
@Query("SELECT * FROM usage_packages WHERE snapshotId = :snapshotId")
fun observePackages(snapshotId: String): Flow<List<UsagePackageEntity>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertSnapshot(snapshot: UsageSnapshotEntity)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertPackages(packages: List<UsagePackageEntity>)
@Transaction
suspend fun insertSnapshotWithPackages(
snapshot: UsageSnapshotEntity,
packages: List<UsagePackageEntity>
) {
insertSnapshot(snapshot)
if (packages.isNotEmpty()) {
insertPackages(packages)
}
}
}
@@ -0,0 +1,49 @@
package net.rodakot.remaining.data
import android.content.Context
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import net.rodakot.remaining.domain.ThemePreference
data class AppSettings(
val themePreference: ThemePreference = ThemePreference.DARK,
val defaultRefreshMinutes: Long = 60,
val notificationsEnabled: Boolean = true
)
class SettingsRepository(context: Context) {
private val preferences = context.getSharedPreferences("remaining_settings", Context.MODE_PRIVATE)
private val mutableSettings = MutableStateFlow(load())
val settings: StateFlow<AppSettings> = mutableSettings
fun updateTheme(preference: ThemePreference) {
preferences.edit().putString(KEY_THEME, preference.name).apply()
mutableSettings.value = load()
}
fun updateNotificationsEnabled(enabled: Boolean) {
preferences.edit().putBoolean(KEY_NOTIFICATIONS, enabled).apply()
mutableSettings.value = load()
}
fun updateDefaultRefreshMinutes(minutes: Long) {
preferences.edit().putLong(KEY_DEFAULT_REFRESH, minutes).apply()
mutableSettings.value = load()
}
private fun load(): AppSettings =
AppSettings(
themePreference = runCatching {
ThemePreference.valueOf(preferences.getString(KEY_THEME, ThemePreference.DARK.name).orEmpty())
}.getOrDefault(ThemePreference.DARK),
defaultRefreshMinutes = preferences.getLong(KEY_DEFAULT_REFRESH, 60),
notificationsEnabled = preferences.getBoolean(KEY_NOTIFICATIONS, true)
)
companion object {
private const val KEY_THEME = "theme"
private const val KEY_DEFAULT_REFRESH = "default_refresh_minutes"
private const val KEY_NOTIFICATIONS = "notifications_enabled"
}
}
@@ -0,0 +1,141 @@
package net.rodakot.remaining.domain
import java.util.Locale
import kotlin.math.roundToLong
enum class ServiceType(
val id: String,
val displayName: String,
val shortName: String,
val accentArgb: Long
) {
MCI("mci", "MCI", "MCI", 0xFF00AECD),
JAHAN_NAMA("jahan_nama", "Jahan Nama / Webotel", "Webotel", 0xFF7C5CFF),
TCI("tci", "TCI Internet", "TCI", 0xFF00A86B);
companion object {
fun fromId(id: String): ServiceType = entries.firstOrNull { it.id == id } ?: MCI
}
}
enum class AccountStatus(val displayName: String) {
ACTIVE("Active"),
REFRESHING("Refreshing"),
CAPTCHA_REQUIRED("Captcha required"),
NEEDS_AUTH("Needs sign-in"),
ERROR("Error"),
DISABLED("Disabled")
}
enum class RefreshInterval(val minutes: Long, val displayName: String) {
FIFTEEN_MINUTES(15, "Every 15 minutes"),
THIRTY_MINUTES(30, "Every 30 minutes"),
HOURLY(60, "Hourly"),
SIX_HOURS(360, "Every 6 hours"),
TWELVE_HOURS(720, "Every 12 hours"),
DAILY(1440, "Daily");
companion object {
fun fromMinutes(minutes: Long): RefreshInterval =
entries.firstOrNull { it.minutes == minutes } ?: HOURLY
}
}
enum class ThemePreference(val displayName: String) {
DARK("Dark"),
LIGHT("Light"),
SYSTEM("System")
}
data class StoredAccount(
val id: String,
val serviceType: ServiceType,
val displayName: String,
val loginIdentifier: String,
val refreshIntervalMinutes: Long,
val alertsEnabled: Boolean,
val lowDataThresholdMb: Long,
val expiryThresholdDays: Int,
val enabled: Boolean
)
data class StoredSecret(
val password: String?,
val accessToken: String?,
val refreshToken: String?,
val cookieJar: String?,
val sessionPayload: String?
)
data class UsagePackageDraft(
val name: String,
val remainingBytes: Long?,
val totalBytes: Long?,
val remainingDisplay: String,
val expiresAtText: String?,
val expiresAtMillis: Long? = null,
val statusText: String?,
val detail: String?
)
data class UsageSnapshotDraft(
val remainingBytes: Long?,
val totalBytes: Long?,
val remainingDisplay: String,
val totalDisplay: String?,
val expiresAtText: String?,
val expiresAtMillis: Long? = null,
val capturedAt: Long = System.currentTimeMillis(),
val packages: List<UsagePackageDraft> = emptyList(),
val rawSummary: String? = null
)
data class ConnectorResult(
val snapshot: UsageSnapshotDraft,
val updatedSecret: StoredSecret,
val status: AccountStatus = AccountStatus.ACTIVE
)
data class CaptchaChallenge(
val imageBytes: ByteArray,
val updatedSecret: StoredSecret
)
enum class RefreshErrorCode(val displayName: String) {
NETWORK("Network error"),
AUTH("Authentication failed"),
CAPTCHA_REQUIRED("Captcha required"),
SESSION_EXPIRED("Session expired"),
PARSER_CHANGED("Service response changed"),
INVALID_RESPONSE("Unexpected response"),
UNKNOWN("Unknown error")
}
class RefreshException(
val code: RefreshErrorCode,
override val message: String,
override val cause: Throwable? = null
) : Exception(message, cause)
fun Long.asTrafficDisplay(): String {
val gb = 1024L * 1024L * 1024L
val mb = 1024L * 1024L
return if (this >= gb) {
String.format(Locale.US, "%.2f GB", this.toDouble() / gb)
} else {
String.format(Locale.US, "%.0f MB", this.toDouble() / mb)
}
}
fun mbToBytes(value: Double): Long = (value * 1024.0 * 1024.0).roundToLong()
fun unitAmountToBytes(value: Double, unit: String?): Long {
val normalized = unit.orEmpty().lowercase(Locale.US)
val multiplier = when {
normalized.contains("گیگ") || normalized.contains("gb") -> 1024.0 * 1024.0 * 1024.0
normalized.contains("مگ") || normalized.contains("mb") -> 1024.0 * 1024.0
normalized.contains("کیلو") || normalized.contains("kb") -> 1024.0
else -> 1.0
}
return (value * multiplier).roundToLong()
}
@@ -0,0 +1,51 @@
package net.rodakot.remaining.network
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import java.util.concurrent.TimeUnit
object HttpClients {
fun default(): OkHttpClient =
OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.followRedirects(true)
.followSslRedirects(true)
.build()
fun withCookieJar(cookieJar: MutableCookieJar): OkHttpClient =
default().newBuilder()
.cookieJar(cookieJar)
.build()
}
class MutableCookieJar(initialCookies: List<Cookie> = emptyList()) : CookieJar {
private val cookies = mutableListOf<Cookie>()
init {
cookies += initialCookies.filter { it.expiresAt > System.currentTimeMillis() }
}
@Synchronized
override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
this.cookies.removeAll { old ->
cookies.any { new ->
old.name == new.name && old.domain == new.domain && old.path == new.path
}
}
this.cookies += cookies.filter { it.expiresAt > System.currentTimeMillis() }
}
@Synchronized
override fun loadForRequest(url: HttpUrl): List<Cookie> {
val now = System.currentTimeMillis()
cookies.removeAll { it.expiresAt <= now }
return cookies.filter { it.matches(url) }
}
@Synchronized
fun allCookies(): List<Cookie> = cookies.toList()
}
@@ -0,0 +1,29 @@
package net.rodakot.remaining.refresh
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import net.rodakot.remaining.RemainingApplication
class AccountRefreshWorker(
appContext: Context,
params: WorkerParameters
) : CoroutineWorker(appContext, params) {
override suspend fun doWork(): Result {
val accountId = inputData.getString(KEY_ACCOUNT_ID) ?: return Result.failure()
val application = applicationContext as RemainingApplication
val result = application.container.accountRepository.refreshAccount(
accountId = accountId,
notify = true
)
return when {
result.success -> Result.success()
result.retryable -> Result.retry()
else -> Result.failure()
}
}
companion object {
const val KEY_ACCOUNT_ID = "account_id"
}
}
@@ -0,0 +1,55 @@
package net.rodakot.remaining.refresh
import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import net.rodakot.remaining.R
import kotlin.math.absoluteValue
class NotificationHelper(private val context: Context) {
fun ensureChannel() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val channel = NotificationChannel(
CHANNEL_ID,
"Account alerts",
NotificationManager.IMPORTANCE_DEFAULT
).apply {
description = "Refresh errors, captcha requests, and low remaining data alerts"
}
context.getSystemService(NotificationManager::class.java)
.createNotificationChannel(channel)
}
fun showAccountAlert(accountId: String, title: String, message: String) {
if (!canPostNotifications()) return
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(title)
.setContentText(message)
.setStyle(NotificationCompat.BigTextStyle().bigText(message))
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build()
NotificationManagerCompat.from(context)
.notify(accountId.hashCode().absoluteValue, notification)
}
private fun canPostNotifications(): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return true
return ContextCompat.checkSelfPermission(
context,
Manifest.permission.POST_NOTIFICATIONS
) == PackageManager.PERMISSION_GRANTED
}
companion object {
private const val CHANNEL_ID = "remaining_account_alerts"
}
}
@@ -0,0 +1,50 @@
package net.rodakot.remaining.refresh
import android.content.Context
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.workDataOf
import net.rodakot.remaining.data.AccountEntity
import java.util.concurrent.TimeUnit
class RefreshScheduler(context: Context) {
private val workManager = WorkManager.getInstance(context.applicationContext)
fun schedule(account: AccountEntity) {
if (!account.enabled) {
cancel(account.id)
return
}
val request = PeriodicWorkRequestBuilder<AccountRefreshWorker>(
account.refreshIntervalMinutes.coerceAtLeast(15),
TimeUnit.MINUTES
)
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
.setInputData(workDataOf(AccountRefreshWorker.KEY_ACCOUNT_ID to account.id))
.build()
workManager.enqueueUniquePeriodicWork(
workName(account.id),
ExistingPeriodicWorkPolicy.UPDATE,
request
)
}
fun cancel(accountId: String) {
workManager.cancelUniqueWork(workName(accountId))
}
suspend fun rescheduleAll(accounts: List<AccountEntity>) {
accounts.forEach(::schedule)
}
private fun workName(accountId: String): String = "refresh_account_$accountId"
}
@@ -0,0 +1,66 @@
package net.rodakot.remaining.security
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import java.nio.charset.StandardCharsets
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
class SecretCipher {
private val keyStore: KeyStore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
fun encrypt(value: String?): String? {
if (value.isNullOrEmpty()) return null
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.ENCRYPT_MODE, getOrCreateKey())
val ciphertext = cipher.doFinal(value.toByteArray(StandardCharsets.UTF_8))
return listOf(
VERSION,
cipher.iv.base64(),
ciphertext.base64()
).joinToString(separator = ":")
}
fun decrypt(value: String?): String? {
if (value.isNullOrEmpty()) return null
val parts = value.split(":")
require(parts.size == 3 && parts[0] == VERSION) { "Unsupported encrypted secret format" }
val iv = parts[1].base64Decode()
val ciphertext = parts[2].base64Decode()
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.DECRYPT_MODE, getOrCreateKey(), GCMParameterSpec(GCM_TAG_BITS, iv))
return String(cipher.doFinal(ciphertext), StandardCharsets.UTF_8)
}
private fun getOrCreateKey(): SecretKey {
(keyStore.getEntry(KEY_ALIAS, null) as? KeyStore.SecretKeyEntry)?.let { return it.secretKey }
val keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)
val spec = KeyGenParameterSpec.Builder(
KEY_ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setRandomizedEncryptionRequired(true)
.build()
keyGenerator.init(spec)
return keyGenerator.generateKey()
}
private fun ByteArray.base64(): String = Base64.encodeToString(this, Base64.NO_WRAP)
private fun String.base64Decode(): ByteArray = Base64.decode(this, Base64.NO_WRAP)
companion object {
private const val ANDROID_KEYSTORE = "AndroidKeyStore"
private const val KEY_ALIAS = "remaining_account_secrets"
private const val TRANSFORMATION = "AES/GCM/NoPadding"
private const val GCM_TAG_BITS = 128
private const val VERSION = "v1"
}
}
@@ -0,0 +1,160 @@
package net.rodakot.remaining.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import net.rodakot.remaining.domain.RefreshInterval
import net.rodakot.remaining.ui.components.CaptchaImage
import net.rodakot.remaining.ui.screens.AccountDetailScreen
import net.rodakot.remaining.ui.screens.AddAccountScreen
import net.rodakot.remaining.ui.screens.DashboardScreen
import net.rodakot.remaining.ui.screens.SettingsScreen
@Composable
fun RemainingApp(
state: RemainingUiState,
viewModel: RemainingViewModel
) {
CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Ltr) {
val navController = rememberNavController()
val snackbarHostState = remember { SnackbarHostState() }
LaunchedEffect(state.action.message) {
state.action.message?.let {
snackbarHostState.showSnackbar(it)
viewModel.clearMessage()
}
}
Scaffold(snackbarHost = { SnackbarHost(snackbarHostState) }) { outerPadding ->
NavHost(
navController = navController,
startDestination = Route.Dashboard,
modifier = Modifier.padding(outerPadding)
) {
composable(Route.Dashboard) {
DashboardScreen(
state = state,
onAddAccount = { navController.navigate(Route.AddAccount) },
onOpenAccount = { accountId -> navController.navigate(Route.detail(accountId)) },
onRefreshAccount = viewModel::refreshAccount,
onPrepareCaptcha = viewModel::prepareCaptcha,
onOpenSettings = { navController.navigate(Route.Settings) }
)
}
composable(Route.AddAccount) {
AddAccountScreen(
defaultRefreshMinutes = state.settings.defaultRefreshMinutes,
saving = state.action.globalBusy,
onBack = { navController.popBackStack() },
onCreateAccount = viewModel::createAccount
)
}
composable(
route = Route.Detail,
arguments = listOf(navArgument(Route.AccountId) { type = NavType.StringType })
) { backStackEntry ->
val accountId = backStackEntry.arguments?.getString(Route.AccountId).orEmpty()
val detail by viewModel.observeAccountDetail(accountId).collectAsState(initial = null)
AccountDetailScreen(
detail = detail,
busy = state.action.busyAccountIds.contains(accountId),
onBack = { navController.popBackStack() },
onRefresh = viewModel::refreshAccount,
onPrepareCaptcha = viewModel::prepareCaptcha,
onSaveSettings = viewModel::updateAccountSettings,
onDelete = viewModel::deleteAccount
)
}
composable(Route.Settings) {
SettingsScreen(
settings = state.settings,
onBack = { navController.popBackStack() },
onThemeChanged = viewModel::updateTheme,
onNotificationsChanged = viewModel::updateNotifications,
onDefaultRefreshChanged = { interval: RefreshInterval ->
viewModel.updateDefaultRefresh(interval)
}
)
}
}
}
state.action.captcha?.let { captcha ->
AlertDialog(
onDismissRequest = viewModel::dismissCaptcha,
title = { Text("TCI captcha") },
text = {
Column {
Text(
"Enter the captcha shown by TCI. This signs in the saved account session.",
color = MaterialTheme.colorScheme.onSurfaceVariant
)
CaptchaImage(
bytes = captcha.imageBytes,
modifier = Modifier
.padding(top = 14.dp)
.fillMaxWidth()
)
OutlinedTextField(
value = captcha.captchaText,
onValueChange = viewModel::updateCaptchaText,
label = { Text("Captcha") },
singleLine = true,
modifier = Modifier
.fillMaxWidth()
.padding(top = 12.dp)
)
}
},
confirmButton = {
Button(
onClick = viewModel::submitCaptcha,
enabled = captcha.captchaText.isNotBlank()
) {
Text("Submit")
}
},
dismissButton = {
OutlinedButton(onClick = viewModel::dismissCaptcha) {
Text("Cancel")
}
}
)
}
}
}
private object Route {
const val Dashboard = "dashboard"
const val AddAccount = "add_account"
const val Settings = "settings"
const val AccountId = "accountId"
const val Detail = "detail/{$AccountId}"
fun detail(accountId: String) = "detail/$accountId"
}
@@ -0,0 +1,204 @@
package net.rodakot.remaining.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import net.rodakot.remaining.AppContainer
import net.rodakot.remaining.data.AccountDetail
import net.rodakot.remaining.data.AccountSummary
import net.rodakot.remaining.data.AppSettings
import net.rodakot.remaining.data.CreateAccountRequest
import net.rodakot.remaining.domain.RefreshErrorCode
import net.rodakot.remaining.domain.RefreshException
import net.rodakot.remaining.domain.RefreshInterval
import net.rodakot.remaining.domain.ServiceType
import net.rodakot.remaining.domain.ThemePreference
data class CaptchaUiState(
val accountId: String,
val imageBytes: ByteArray,
val captchaText: String = ""
)
data class ActionUiState(
val busyAccountIds: Set<String> = emptySet(),
val globalBusy: Boolean = false,
val message: String? = null,
val captcha: CaptchaUiState? = null
)
data class RemainingUiState(
val accounts: List<AccountSummary> = emptyList(),
val settings: AppSettings = AppSettings(),
val action: ActionUiState = ActionUiState()
)
class RemainingViewModel(
private val container: AppContainer
) : ViewModel() {
private val actionState = MutableStateFlow(ActionUiState())
val uiState = combine(
container.accountRepository.observeAccountSummaries(),
container.settingsRepository.settings,
actionState
) { accounts, settings, action ->
RemainingUiState(accounts, settings, action)
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = RemainingUiState()
)
fun observeAccountDetail(accountId: String): Flow<AccountDetail?> =
container.accountRepository.observeAccountDetail(accountId)
fun createAccount(request: CreateAccountRequest) {
viewModelScope.launch {
setGlobalBusy(true)
runCatching {
val account = container.accountRepository.createAccount(request)
container.refreshScheduler.schedule(account)
if (request.serviceType != ServiceType.TCI) {
container.accountRepository.refreshAccount(account.id, notify = false)
}
"Account added."
}.onSuccess(::showMessage)
.onFailure { showMessage(it.userMessage()) }
setGlobalBusy(false)
}
}
fun refreshAccount(accountId: String) {
viewModelScope.launch {
setAccountBusy(accountId, true)
val result = container.accountRepository.refreshAccount(accountId, notify = false)
showMessage(result.message ?: if (result.success) "Account refreshed." else "Refresh failed.")
setAccountBusy(accountId, false)
}
}
fun prepareCaptcha(accountId: String) {
viewModelScope.launch {
setAccountBusy(accountId, true)
runCatching {
val challenge = container.accountRepository.prepareCaptcha(accountId)
actionState.value = actionState.value.copy(
captcha = CaptchaUiState(accountId, challenge.imageBytes),
message = null
)
}.onFailure { showMessage(it.userMessage()) }
setAccountBusy(accountId, false)
}
}
fun updateCaptchaText(text: String) {
val current = actionState.value.captcha ?: return
actionState.value = actionState.value.copy(captcha = current.copy(captchaText = text))
}
fun submitCaptcha() {
val captcha = actionState.value.captcha ?: return
viewModelScope.launch {
setAccountBusy(captcha.accountId, true)
val result = container.accountRepository.refreshAccount(
accountId = captcha.accountId,
captcha = captcha.captchaText.trim(),
notify = false
)
actionState.value = actionState.value.copy(captcha = null)
showMessage(result.message ?: if (result.success) "TCI account signed in." else "Captcha failed.")
setAccountBusy(captcha.accountId, false)
}
}
fun dismissCaptcha() {
actionState.value = actionState.value.copy(captcha = null)
}
fun updateAccountSettings(
account: AccountSummary,
interval: RefreshInterval,
alertsEnabled: Boolean,
lowDataThresholdMb: Long,
expiryThresholdDays: Int,
enabled: Boolean
) {
viewModelScope.launch {
container.accountRepository.updateAccountSettings(
accountId = account.id,
interval = interval,
alertsEnabled = alertsEnabled,
lowDataThresholdMb = lowDataThresholdMb,
expiryThresholdDays = expiryThresholdDays,
enabled = enabled
)
val updated = container.accountRepository.getEnabledAccounts()
.firstOrNull { it.id == account.id }
if (updated != null) {
container.refreshScheduler.schedule(updated)
} else {
container.refreshScheduler.cancel(account.id)
}
showMessage("Account settings updated.")
}
}
fun deleteAccount(accountId: String) {
viewModelScope.launch {
container.refreshScheduler.cancel(accountId)
container.accountRepository.deleteAccount(accountId)
showMessage("Account deleted.")
}
}
fun updateTheme(themePreference: ThemePreference) {
container.settingsRepository.updateTheme(themePreference)
}
fun updateNotifications(enabled: Boolean) {
container.settingsRepository.updateNotificationsEnabled(enabled)
}
fun updateDefaultRefresh(interval: RefreshInterval) {
container.settingsRepository.updateDefaultRefreshMinutes(interval.minutes)
}
fun clearMessage() {
actionState.value = actionState.value.copy(message = null)
}
private fun setGlobalBusy(busy: Boolean) {
actionState.value = actionState.value.copy(globalBusy = busy)
}
private fun setAccountBusy(accountId: String, busy: Boolean) {
val current = actionState.value.busyAccountIds
actionState.value = actionState.value.copy(
busyAccountIds = if (busy) current + accountId else current - accountId
)
}
private fun showMessage(message: String) {
actionState.value = actionState.value.copy(message = message)
}
private fun Throwable.userMessage(): String =
when (this) {
is RefreshException -> message
else -> message ?: RefreshErrorCode.UNKNOWN.displayName
}
class Factory(private val container: AppContainer) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return RemainingViewModel(container) as T
}
}
}
@@ -0,0 +1,134 @@
package net.rodakot.remaining.ui.components
import android.graphics.BitmapFactory
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import net.rodakot.remaining.domain.AccountStatus
import java.text.DateFormat
import java.util.Date
import java.util.Locale
@Composable
fun StatusChip(status: AccountStatus, modifier: Modifier = Modifier) {
val color = when (status) {
AccountStatus.ACTIVE -> Color(0xFF3DDC84)
AccountStatus.REFRESHING -> Color(0xFF64B5F6)
AccountStatus.CAPTCHA_REQUIRED -> Color(0xFFFFC857)
AccountStatus.NEEDS_AUTH -> Color(0xFFFF9F1C)
AccountStatus.ERROR -> Color(0xFFFF5A5F)
AccountStatus.DISABLED -> MaterialTheme.colorScheme.outline
}
Surface(
modifier = modifier,
color = color.copy(alpha = 0.16f),
contentColor = color,
shape = RoundedCornerShape(8.dp)
) {
Text(
text = status.displayName,
style = MaterialTheme.typography.labelMedium,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 5.dp)
)
}
}
@Composable
fun UsageBar(
remainingBytes: Long?,
totalBytes: Long?,
totalDisplay: String?,
modifier: Modifier = Modifier
) {
val progress = remember(remainingBytes, totalBytes) {
if (remainingBytes == null || totalBytes == null || totalBytes <= 0L) {
null
} else {
(remainingBytes.toFloat() / totalBytes.toFloat()).coerceIn(0f, 1f)
}
}
Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(6.dp)) {
LinearProgressIndicator(
progress = { progress ?: 0.62f },
modifier = Modifier
.fillMaxWidth()
.height(8.dp),
trackColor = MaterialTheme.colorScheme.surfaceVariant
)
Text(
text = totalDisplay?.let { "Total $it" } ?: "Total quota not reported",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall
)
}
}
@Composable
fun MetricPill(label: String, value: String, modifier: Modifier = Modifier) {
Box(
modifier = modifier
.background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(8.dp))
.padding(horizontal = 12.dp, vertical = 10.dp)
) {
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(label, color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.labelSmall)
Text(value, fontWeight = FontWeight.SemiBold, style = MaterialTheme.typography.titleSmall)
}
}
}
@Composable
fun CaptchaImage(bytes: ByteArray, modifier: Modifier = Modifier) {
val bitmap = remember(bytes) {
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
}
if (bitmap != null) {
Image(
bitmap = bitmap.asImageBitmap(),
contentDescription = "Captcha image",
modifier = modifier
.widthIn(min = 180.dp)
.background(Color.White, RoundedCornerShape(8.dp))
.padding(10.dp)
)
}
}
@Composable
fun InfoRow(label: String, value: String, modifier: Modifier = Modifier) {
Row(
modifier = modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(label, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(value, fontWeight = FontWeight.Medium)
}
}
fun Long?.formatTimestamp(): String =
this?.let {
DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.US)
.format(Date(it))
} ?: "Never"
@@ -0,0 +1,285 @@
package net.rodakot.remaining.ui.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import net.rodakot.remaining.data.AccountDetail
import net.rodakot.remaining.data.AccountSummary
import net.rodakot.remaining.data.UsagePackageEntity
import net.rodakot.remaining.domain.AccountStatus
import net.rodakot.remaining.domain.RefreshInterval
import net.rodakot.remaining.ui.components.InfoRow
import net.rodakot.remaining.ui.components.StatusChip
import net.rodakot.remaining.ui.components.UsageBar
import net.rodakot.remaining.ui.components.formatTimestamp
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AccountDetailScreen(
detail: AccountDetail?,
busy: Boolean,
onBack: () -> Unit,
onRefresh: (String) -> Unit,
onPrepareCaptcha: (String) -> Unit,
onSaveSettings: (AccountSummary, RefreshInterval, Boolean, Long, Int, Boolean) -> Unit,
onDelete: (String) -> Unit
) {
val account = detail?.summary
Scaffold(
topBar = {
TopAppBar(
title = { Text(account?.displayName ?: "Account") },
navigationIcon = {
IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
}
},
actions = {
if (account != null) {
IconButton(onClick = { onDelete(account.id); onBack() }) {
Icon(Icons.Default.Delete, contentDescription = "Delete account")
}
}
}
)
}
) { padding ->
if (account == null) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
.padding(24.dp),
verticalArrangement = Arrangement.Center
) {
Text("Account not found", style = MaterialTheme.typography.titleLarge)
}
} else {
AccountDetailContent(
modifier = Modifier.padding(padding),
detail = detail,
busy = busy,
onRefresh = { onRefresh(account.id) },
onPrepareCaptcha = { onPrepareCaptcha(account.id) },
onSaveSettings = onSaveSettings
)
}
}
}
@Composable
private fun AccountDetailContent(
modifier: Modifier,
detail: AccountDetail,
busy: Boolean,
onRefresh: () -> Unit,
onPrepareCaptcha: () -> Unit,
onSaveSettings: (AccountSummary, RefreshInterval, Boolean, Long, Int, Boolean) -> Unit
) {
val account = detail.summary
LazyColumn(
modifier = modifier.fillMaxSize(),
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
item {
Card(
shape = RoundedCornerShape(8.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer)
) {
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) {
Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) {
Column(modifier = Modifier.weight(1f)) {
Text(account.serviceType.displayName, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(account.remainingDisplay, style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
}
StatusChip(account.status)
}
UsageBar(account.remainingBytes, account.totalBytes, account.totalDisplay)
account.lastErrorMessage?.let {
Text(it, color = MaterialTheme.colorScheme.error)
}
InfoRow("Login", account.loginIdentifier)
InfoRow("Refresh interval", account.refreshInterval.displayName)
account.expiresAtText?.let { InfoRow("Package expiry", it) }
InfoRow("Last refresh", account.lastRefreshAt.formatTimestamp())
InfoRow("Last success", account.lastSuccessAt.formatTimestamp())
InfoRow("Next refresh", account.nextRefreshAt.formatTimestamp())
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Button(
onClick = onRefresh,
enabled = !busy && account.enabled,
modifier = Modifier.weight(1f)
) {
Icon(Icons.Default.Refresh, contentDescription = null)
Text(if (busy) "Refreshing" else "Refresh", modifier = Modifier.padding(start = 8.dp))
}
if (account.status == AccountStatus.CAPTCHA_REQUIRED) {
OutlinedButton(
onClick = onPrepareCaptcha,
enabled = !busy,
modifier = Modifier.weight(1f)
) {
Text("Captcha")
}
}
}
}
}
}
item {
AccountSettingsCard(account, onSaveSettings)
}
item {
Text("Packages", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
}
if (detail.packages.isEmpty()) {
item {
Text(
"No package details reported yet.",
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
} else {
items(detail.packages, key = { it.id }) { item ->
PackageRow(item)
}
}
}
}
@Composable
@OptIn(ExperimentalMaterial3Api::class)
private fun AccountSettingsCard(
account: AccountSummary,
onSaveSettings: (AccountSummary, RefreshInterval, Boolean, Long, Int, Boolean) -> Unit
) {
var interval by rememberSaveable(account.id) { mutableStateOf(account.refreshInterval) }
var alertsEnabled by rememberSaveable(account.id) { mutableStateOf(account.alertsEnabled) }
var enabled by rememberSaveable(account.id) { mutableStateOf(account.enabled) }
var thresholdMb by rememberSaveable(account.id) { mutableStateOf(account.lowDataThresholdMb.toString()) }
var expiryDays by rememberSaveable(account.id) { mutableStateOf(account.expiryThresholdDays.toString()) }
Card(
shape = RoundedCornerShape(8.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer)
) {
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) {
Text("Account settings", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) {
Column(Modifier.weight(1f)) {
Text("Enabled", fontWeight = FontWeight.Medium)
Text("Background refresh is paused when disabled.", color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodySmall)
}
Switch(checked = enabled, onCheckedChange = { enabled = it })
}
Text("Refresh interval", fontWeight = FontWeight.Medium)
RefreshInterval.entries.chunked(2).forEach { rowOptions ->
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
rowOptions.forEach { option ->
FilterChip(
selected = interval == option,
onClick = { interval = option },
label = { Text(option.displayName) },
modifier = Modifier.weight(1f),
shape = RoundedCornerShape(8.dp)
)
}
if (rowOptions.size == 1) {
Column(Modifier.weight(1f)) {}
}
}
}
Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) {
Text("Alerts", fontWeight = FontWeight.Medium)
Switch(checked = alertsEnabled, onCheckedChange = { alertsEnabled = it })
}
OutlinedTextField(
value = thresholdMb,
onValueChange = { thresholdMb = it.filter(Char::isDigit) },
label = { Text("Low data threshold (MB)") },
singleLine = true,
modifier = Modifier.fillMaxWidth()
)
OutlinedTextField(
value = expiryDays,
onValueChange = { expiryDays = it.filter(Char::isDigit) },
label = { Text("Expiry warning threshold (days)") },
singleLine = true,
modifier = Modifier.fillMaxWidth()
)
Button(
onClick = {
onSaveSettings(
account,
interval,
alertsEnabled,
thresholdMb.toLongOrNull()?.coerceAtLeast(1) ?: account.lowDataThresholdMb,
expiryDays.toIntOrNull()?.coerceAtLeast(1) ?: account.expiryThresholdDays,
enabled
)
},
modifier = Modifier.fillMaxWidth()
) {
Text("Save settings")
}
}
}
}
@Composable
private fun PackageRow(item: UsagePackageEntity) {
Card(
shape = RoundedCornerShape(8.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerLow)
) {
Column(Modifier.padding(14.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(item.name, fontWeight = FontWeight.SemiBold)
Text(item.remainingDisplay, style = MaterialTheme.typography.titleMedium)
item.expiresAtText?.let {
Text("Expires: $it", color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodySmall)
}
item.statusText?.let {
Text(it, color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodySmall)
}
item.detail?.takeIf { it.isNotBlank() }?.let {
Text(it, color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodySmall)
}
}
}
}
@@ -0,0 +1,230 @@
package net.rodakot.remaining.ui.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import net.rodakot.remaining.data.CreateAccountRequest
import net.rodakot.remaining.domain.RefreshInterval
import net.rodakot.remaining.domain.ServiceType
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddAccountScreen(
defaultRefreshMinutes: Long,
saving: Boolean,
onBack: () -> Unit,
onCreateAccount: (CreateAccountRequest) -> Unit
) {
var service by rememberSaveable { mutableStateOf(ServiceType.MCI) }
var displayName by rememberSaveable { mutableStateOf("") }
var username by rememberSaveable { mutableStateOf("") }
var password by rememberSaveable { mutableStateOf("") }
var passwordVisible by rememberSaveable { mutableStateOf(false) }
var interval by rememberSaveable {
mutableStateOf(RefreshInterval.fromMinutes(defaultRefreshMinutes))
}
var alertsEnabled by rememberSaveable { mutableStateOf(true) }
var thresholdMb by rememberSaveable { mutableStateOf("1024") }
var expiryDays by rememberSaveable { mutableStateOf("3") }
val canSave = username.isNotBlank() && password.isNotBlank() && !saving
Scaffold(
topBar = {
TopAppBar(
title = { Text("Add account") },
navigationIcon = {
IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
}
}
)
}
) { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
.verticalScroll(rememberScrollState())
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(18.dp)
) {
SectionTitle("Service")
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
ServiceType.entries.forEach { option ->
FilterChip(
selected = service == option,
onClick = { service = option },
label = { Text(option.shortName) },
shape = RoundedCornerShape(8.dp)
)
}
}
Text(
text = when (service) {
ServiceType.MCI -> "Use your My MCI phone number and password."
ServiceType.JAHAN_NAMA -> "Use your Webotel/Jahan Nama username and password."
ServiceType.TCI -> "TCI needs a manual captcha after the account is saved."
},
color = MaterialTheme.colorScheme.onSurfaceVariant
)
SectionTitle("Credentials")
OutlinedTextField(
value = displayName,
onValueChange = { displayName = it },
label = { Text("Display name") },
singleLine = true,
modifier = Modifier.fillMaxWidth()
)
OutlinedTextField(
value = username,
onValueChange = { username = it.trim() },
label = { Text(if (service == ServiceType.MCI) "Phone number" else "Username") },
singleLine = true,
modifier = Modifier.fillMaxWidth()
)
OutlinedTextField(
value = password,
onValueChange = { password = it },
label = { Text("Password") },
singleLine = true,
visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
trailingIcon = {
IconButton(onClick = { passwordVisible = !passwordVisible }) {
Icon(
imageVector = if (passwordVisible) Icons.Default.VisibilityOff else Icons.Default.Visibility,
contentDescription = if (passwordVisible) "Hide password" else "Show password"
)
}
},
modifier = Modifier.fillMaxWidth()
)
SectionTitle("Refresh")
PresetChips(
options = RefreshInterval.entries,
selected = interval,
label = { it.displayName },
onSelected = { interval = it }
)
SectionTitle("Alerts")
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Column(modifier = Modifier.weight(1f)) {
Text("Enable account alerts", fontWeight = FontWeight.Medium)
Text(
"Low data, failed refreshes, and captcha requests",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall
)
}
Switch(checked = alertsEnabled, onCheckedChange = { alertsEnabled = it })
}
OutlinedTextField(
value = thresholdMb,
onValueChange = { thresholdMb = it.filter(Char::isDigit) },
label = { Text("Low data threshold (MB)") },
singleLine = true,
modifier = Modifier.fillMaxWidth()
)
OutlinedTextField(
value = expiryDays,
onValueChange = { expiryDays = it.filter(Char::isDigit) },
label = { Text("Expiry warning threshold (days)") },
singleLine = true,
modifier = Modifier.fillMaxWidth()
)
Button(
onClick = {
onCreateAccount(
CreateAccountRequest(
serviceType = service,
displayName = displayName.trim(),
loginIdentifier = username.trim(),
password = password,
refreshIntervalMinutes = interval.minutes,
alertsEnabled = alertsEnabled,
lowDataThresholdMb = thresholdMb.toLongOrNull()?.coerceAtLeast(1) ?: 1024,
expiryThresholdDays = expiryDays.toIntOrNull()?.coerceAtLeast(1) ?: 3
)
)
onBack()
},
enabled = canSave,
contentPadding = PaddingValues(vertical = 14.dp),
modifier = Modifier.fillMaxWidth()
) {
Text(if (saving) "Saving" else "Save account")
}
}
}
}
@Composable
private fun SectionTitle(text: String) {
Text(text, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
}
@Composable
@OptIn(ExperimentalMaterial3Api::class)
private fun <T> PresetChips(
options: List<T>,
selected: T,
label: (T) -> String,
onSelected: (T) -> Unit
) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
options.chunked(2).forEach { rowOptions ->
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
rowOptions.forEach { option ->
FilterChip(
selected = selected == option,
onClick = { onSelected(option) },
label = { Text(label(option)) },
modifier = Modifier.weight(1f),
shape = RoundedCornerShape(8.dp)
)
}
if (rowOptions.size == 1) {
Column(modifier = Modifier.weight(1f)) {}
}
}
}
}
}
@@ -0,0 +1,257 @@
package net.rodakot.remaining.ui.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import net.rodakot.remaining.data.AccountSummary
import net.rodakot.remaining.domain.AccountStatus
import net.rodakot.remaining.domain.asTrafficDisplay
import net.rodakot.remaining.ui.RemainingUiState
import net.rodakot.remaining.ui.components.MetricPill
import net.rodakot.remaining.ui.components.StatusChip
import net.rodakot.remaining.ui.components.UsageBar
import net.rodakot.remaining.ui.components.formatTimestamp
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DashboardScreen(
state: RemainingUiState,
onAddAccount: () -> Unit,
onOpenAccount: (String) -> Unit,
onRefreshAccount: (String) -> Unit,
onPrepareCaptcha: (String) -> Unit,
onOpenSettings: () -> Unit
) {
Scaffold(
topBar = {
TopAppBar(
title = {
Column {
Text("Remaining", fontWeight = FontWeight.Bold)
Text(
"Usage across all accounts",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
},
actions = {
IconButton(onClick = onOpenSettings) {
Icon(Icons.Default.Settings, contentDescription = "Settings")
}
IconButton(onClick = onAddAccount) {
Icon(Icons.Default.Add, contentDescription = "Add account")
}
}
)
}
) { padding ->
if (state.accounts.isEmpty()) {
EmptyDashboard(
modifier = Modifier
.fillMaxSize()
.padding(padding),
onAddAccount = onAddAccount
)
} else {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(padding),
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
item {
OverviewCard(accounts = state.accounts)
}
items(state.accounts, key = { it.id }) { account ->
AccountCard(
account = account,
busy = state.action.busyAccountIds.contains(account.id),
onOpen = { onOpenAccount(account.id) },
onRefresh = { onRefreshAccount(account.id) },
onPrepareCaptcha = { onPrepareCaptcha(account.id) }
)
}
}
}
}
}
@Composable
private fun EmptyDashboard(modifier: Modifier = Modifier, onAddAccount: () -> Unit) {
Column(
modifier = modifier.padding(24.dp),
verticalArrangement = Arrangement.Center
) {
Text(
"Track every service account in one dashboard.",
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Bold
)
Text(
"Add MCI, Jahan Nama/Webotel, or TCI accounts, then choose how often each one refreshes.",
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 10.dp, bottom = 22.dp)
)
Button(onClick = onAddAccount) {
Icon(Icons.Default.Add, contentDescription = null)
Text("Add account", modifier = Modifier.padding(start = 8.dp))
}
}
}
@Composable
private fun OverviewCard(accounts: List<AccountSummary>) {
val totalRemaining = remember(accounts) {
accounts.mapNotNull { it.remainingBytes }.sum()
}
val issueCount = accounts.count {
it.status == AccountStatus.ERROR ||
it.status == AccountStatus.CAPTCHA_REQUIRED ||
it.status == AccountStatus.NEEDS_AUTH
}
val nextRefresh = accounts.mapNotNull { it.nextRefreshAt }.minOrNull()
Column(
modifier = Modifier
.fillMaxWidth()
.background(
Brush.linearGradient(
colors = listOf(
MaterialTheme.colorScheme.primaryContainer,
MaterialTheme.colorScheme.secondaryContainer
)
),
RoundedCornerShape(8.dp)
)
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
Text(
"Dashboard",
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onPrimaryContainer
)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
MetricPill("Remaining", totalRemaining.asTrafficDisplay(), Modifier.weight(1f))
MetricPill("Accounts", accounts.size.toString(), Modifier.weight(1f))
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
MetricPill("Needs action", issueCount.toString(), Modifier.weight(1f))
MetricPill("Next refresh", nextRefresh.formatTimestamp(), Modifier.weight(1f))
}
}
}
@Composable
private fun AccountCard(
account: AccountSummary,
busy: Boolean,
onOpen: () -> Unit,
onRefresh: () -> Unit,
onPrepareCaptcha: () -> Unit
) {
Card(
onClick = onOpen,
shape = RoundedCornerShape(8.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceContainer
)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) {
Column(modifier = Modifier.weight(1f)) {
Text(account.displayName, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
Text(
"${account.serviceType.displayName} • ${account.loginIdentifier}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
StatusChip(account.status)
}
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text("Remaining", color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(account.remainingDisplay, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold)
}
UsageBar(
remainingBytes = account.remainingBytes,
totalBytes = account.totalBytes,
totalDisplay = account.totalDisplay
)
account.lastErrorMessage?.let {
Text(
it,
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodySmall
)
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
FilledTonalButton(
onClick = onRefresh,
enabled = !busy && account.enabled,
modifier = Modifier.weight(1f)
) {
Icon(Icons.Default.Refresh, contentDescription = null)
Text(if (busy) "Refreshing" else "Refresh", modifier = Modifier.padding(start = 8.dp))
}
if (account.status == AccountStatus.CAPTCHA_REQUIRED) {
OutlinedButton(
onClick = onPrepareCaptcha,
enabled = !busy,
modifier = Modifier.weight(1f)
) {
Text("Captcha")
}
} else {
OutlinedButton(onClick = onOpen, modifier = Modifier.weight(1f)) {
Text("Details")
}
}
}
Text(
"Last success: ${account.lastSuccessAt.formatTimestamp()}",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall
)
}
}
}
@@ -0,0 +1,112 @@
package net.rodakot.remaining.ui.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import net.rodakot.remaining.data.AppSettings
import net.rodakot.remaining.domain.RefreshInterval
import net.rodakot.remaining.domain.ThemePreference
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(
settings: AppSettings,
onBack: () -> Unit,
onThemeChanged: (ThemePreference) -> Unit,
onNotificationsChanged: (Boolean) -> Unit,
onDefaultRefreshChanged: (RefreshInterval) -> Unit
) {
Scaffold(
topBar = {
TopAppBar(
title = { Text("Settings") },
navigationIcon = {
IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
}
}
)
}
) { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
.verticalScroll(rememberScrollState())
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(18.dp)
) {
Text("Appearance", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
ThemePreference.entries.forEach { option ->
FilterChip(
selected = settings.themePreference == option,
onClick = { onThemeChanged(option) },
label = { Text(option.displayName) },
modifier = Modifier.weight(1f),
shape = RoundedCornerShape(8.dp)
)
}
}
Text("Notifications", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) {
Column(Modifier.weight(1f)) {
Text("Global alerts", fontWeight = FontWeight.Medium)
Text(
"Controls refresh failures, captcha-needed alerts, and low-data alerts.",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall
)
}
Switch(
checked = settings.notificationsEnabled,
onCheckedChange = onNotificationsChanged
)
}
Text("New accounts", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
Text(
"Default refresh interval",
color = MaterialTheme.colorScheme.onSurfaceVariant
)
RefreshInterval.entries.chunked(2).forEach { rowOptions ->
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
rowOptions.forEach { option ->
FilterChip(
selected = settings.defaultRefreshMinutes == option.minutes,
onClick = { onDefaultRefreshChanged(option) },
label = { Text(option.displayName) },
modifier = Modifier.weight(1f),
shape = RoundedCornerShape(8.dp)
)
}
if (rowOptions.size == 1) {
Column(Modifier.weight(1f)) {}
}
}
}
}
}
}
@@ -2,10 +2,17 @@ package net.rodakot.remaining.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Blue80 = Color(0xFF8FD8FF)
val Green80 = Color(0xFF8FE7B0)
val Amber80 = Color(0xFFFFD66B)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
val Blue40 = Color(0xFF006B8F)
val Green40 = Color(0xFF006C46)
val Amber40 = Color(0xFF765A00)
val DarkBackground = Color(0xFF0D1117)
val DarkSurface = Color(0xFF151B23)
val DarkSurfaceVariant = Color(0xFF222B36)
val LightBackground = Color(0xFFF7F9FC)
val LightSurface = Color(0xFFFFFFFF)
val LightSurfaceVariant = Color(0xFFE8EEF5)
@@ -1,8 +1,6 @@
package net.rodakot.remaining.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
@@ -12,30 +10,26 @@ import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
primary = Blue80,
secondary = Green80,
tertiary = Amber80,
background = DarkBackground,
surface = DarkSurface,
surfaceVariant = DarkSurfaceVariant
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
primary = Blue40,
secondary = Green40,
tertiary = Amber40,
background = LightBackground,
surface = LightSurface,
surfaceVariant = LightSurfaceVariant
)
@Composable
fun RemainingTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
darkTheme: Boolean = true,
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
@@ -55,4 +49,4 @@ fun RemainingTheme(
typography = Typography,
content = content
)
}
}
@@ -8,27 +8,32 @@ import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
headlineMedium = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Bold,
fontSize = 28.sp,
lineHeight = 34.sp,
letterSpacing = 0.sp
),
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Bold,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
titleMedium = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.SemiBold,
fontSize = 16.sp,
lineHeight = 22.sp,
letterSpacing = 0.sp
),
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
)
)
@@ -1,170 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M0,0h108v108h-108z">
<aapt:attr name="android:fillColor">
<gradient
android:endX="108"
android:endY="108"
android:startX="0"
android:startY="0"
android:type="linear">
<item
android:color="#0D1117"
android:offset="0" />
<item
android:color="#123B52"
android:offset="0.58" />
<item
android:color="#006C46"
android:offset="1" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#3DDC84"
android:pathData="M0,0h108v108h-108z" />
android:fillColor="#263DDC84"
android:pathData="M79,4C96,8 110,24 113,42C117,63 101,84 80,87C59,90 39,75 36,54C33,33 48,11 69,6C72,5 76,4 79,4Z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
android:fillColor="#1F8FD8FF"
android:pathData="M14,70C28,60 47,63 58,76C69,89 89,93 105,82L105,108L14,108Z" />
</vector>
@@ -1,30 +1,48 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
<aapt:attr name="android:fillColor">
<gradient
android:endX="85.84757"
android:endY="92.4963"
android:startX="42.9492"
android:startY="49.59793"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#26000000"
android:pathData="M30,72C25,67 22,61 22,54C22,36 36,22 54,22C72,22 86,36 86,54C86,72 72,86 54,86C47,86 41,84 36,80L30,88C36,92 45,95 54,95C77,95 95,77 95,54C95,31 77,13 54,13C31,13 13,31 13,54C13,64 17,74 23,81Z" />
<path
android:fillColor="#00000000"
android:pathData="M54,24C37.4,24 24,37.4 24,54C24,70.6 37.4,84 54,84C70.6,84 84,70.6 84,54C84,37.4 70.6,24 54,24Z"
android:strokeColor="#3AFFFFFF"
android:strokeWidth="6" />
<path
android:fillColor="#00000000"
android:pathData="M54,24C70.6,24 84,37.4 84,54C84,62.5 80.4,70.2 74.7,75.7"
android:strokeColor="#8FD8FF"
android:strokeLineCap="round"
android:strokeWidth="7" />
<path
android:fillColor="#00000000"
android:pathData="M35,66L35,57"
android:strokeColor="#FFFFFF"
android:strokeLineCap="round"
android:strokeWidth="7" />
<path
android:fillColor="#00000000"
android:pathData="M48,66L48,47"
android:strokeColor="#8FD8FF"
android:strokeLineCap="round"
android:strokeWidth="7" />
<path
android:fillColor="#00000000"
android:pathData="M61,66L61,39"
android:strokeColor="#3DDC84"
android:strokeLineCap="round"
android:strokeWidth="7" />
<path
android:fillColor="#00000000"
android:pathData="M39,74L67,74"
android:strokeColor="#D8F7FF"
android:strokeLineCap="round"
android:strokeWidth="5" />
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>
android:pathData="M77,31L80,37L86,40L80,43L77,49L74,43L68,40L74,37Z" />
</vector>
@@ -0,0 +1,45 @@
<?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="#151B23"
android:pathData="M54,10C29.7,10 10,29.7 10,54C10,78.3 29.7,98 54,98C78.3,98 98,78.3 98,54C98,29.7 78.3,10 54,10Z" />
<path
android:fillColor="#00000000"
android:pathData="M54,24C37.4,24 24,37.4 24,54C24,70.6 37.4,84 54,84C70.6,84 84,70.6 84,54C84,37.4 70.6,24 54,24Z"
android:strokeColor="#33445A"
android:strokeWidth="6" />
<path
android:fillColor="#00000000"
android:pathData="M54,24C70.6,24 84,37.4 84,54C84,62.5 80.4,70.2 74.7,75.7"
android:strokeColor="#8FD8FF"
android:strokeLineCap="round"
android:strokeWidth="7" />
<path
android:fillColor="#00000000"
android:pathData="M35,66L35,57"
android:strokeColor="#FFFFFF"
android:strokeLineCap="round"
android:strokeWidth="7" />
<path
android:fillColor="#00000000"
android:pathData="M48,66L48,47"
android:strokeColor="#8FD8FF"
android:strokeLineCap="round"
android:strokeWidth="7" />
<path
android:fillColor="#00000000"
android:pathData="M61,66L61,39"
android:strokeColor="#3DDC84"
android:strokeLineCap="round"
android:strokeWidth="7" />
<path
android:fillColor="#00000000"
android:pathData="M39,74L67,74"
android:strokeColor="#D8F7FF"
android:strokeLineCap="round"
android:strokeWidth="5" />
</vector>
+5 -6
View File
@@ -1,10 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="remaining_splash_background">#0D1117</color>
<color name="remaining_splash_icon_background">#151B23</color>
<color name="remaining_primary">#8FD8FF</color>
<color name="remaining_success">#3DDC84</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
</resources>
</resources>
+2 -2
View File
@@ -1,3 +1,3 @@
<resources>
<string name="app_name">remaining</string>
</resources>
<string name="app_name">Remaining</string>
</resources>
+16 -2
View File
@@ -1,5 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Remaining" parent="android:Theme.Material.Light.NoActionBar" />
</resources>
<style name="Theme.Remaining" parent="android:style/Theme.Material.NoActionBar">
<item name="android:windowBackground">@color/remaining_splash_background</item>
<item name="android:navigationBarColor">@color/remaining_splash_background</item>
<item name="android:statusBarColor">@color/remaining_splash_background</item>
<item name="android:windowLightNavigationBar">false</item>
<item name="android:windowLightStatusBar">false</item>
</style>
<style name="Theme.Remaining.Starting" parent="Theme.SplashScreen">
<item name="windowSplashScreenBackground">@color/remaining_splash_background</item>
<item name="windowSplashScreenAnimatedIcon">@drawable/ic_splash_mark</item>
<item name="windowSplashScreenIconBackgroundColor">@color/remaining_splash_icon_background</item>
<item name="windowSplashScreenAnimationDuration">250</item>
<item name="postSplashScreenTheme">@style/Theme.Remaining</item>
</style>
</resources>
@@ -0,0 +1,80 @@
package net.rodakot.remaining.connectors
import net.rodakot.remaining.connectors.jahannama.JahanNamaParser
import net.rodakot.remaining.connectors.mci.MciParser
import net.rodakot.remaining.connectors.tci.TciHtmlParser
import net.rodakot.remaining.domain.asTrafficDisplay
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class ParserTest {
@Test
fun jahanNamaAcceptsNumericRemainTraffic() {
val snapshot = JahanNamaParser.parseRemainTraffic("""{"RemainTraffic":1536}""")
assertEquals("1.50 GB", snapshot.remainingDisplay)
}
@Test
fun jahanNamaAcceptsStringRemainTraffic() {
val snapshot = JahanNamaParser.parseRemainTraffic("""{"RemainTraffic":"512"}""")
assertEquals("512 MB", snapshot.remainingDisplay)
}
@Test
fun mciParsesTopLevelTrafficAndPackages() {
val snapshot = MciParser.parsePackages(
"""
{
"packageItems": [
{
"formattedExpireTime": "15:55 - 1405/05/04",
"totalInitValue": 100.0,
"totalUnusedValue": 12.5,
"totalUnitName": "گیگ",
"unUsedUnitName": "گیگ",
"packageStatusText": "Active",
"offerName": "120 day internet package"
}
],
"totalInitBytes": 100.0,
"totalUnusedBytes": 12.5,
"bytesInitUnit": "گیگ",
"bytesUnusedUnit": "گیگ"
}
""".trimIndent()
)
assertEquals("12.50 GB", snapshot.remainingDisplay)
assertEquals(1, snapshot.packages.size)
assertEquals("120 day internet package", snapshot.packages.first().name)
}
@Test
fun tciDetectsAuthenticatedHtml() {
assertTrue(TciHtmlParser.isAuthenticated("""<a href="/logout">logout</a>"""))
assertTrue(TciHtmlParser.isAuthenticated("""<a>خروج</a>"""))
}
@Test
fun tciParsesPersianReservedTraffic() {
val snapshot = TciHtmlParser.parseReservedTraffic(
"""
<html>
<body>
<h5>میزان ترافیک رزرو شما ۱۲٫۵ گیگابایت</h5>
</body>
</html>
""".trimIndent()
)
assertEquals("12.50 GB", snapshot.remainingDisplay)
}
@Test
fun trafficFormattingUsesMegabytesBelowOneGigabyte() {
assertEquals("512 MB", (512L * 1024L * 1024L).asTrafficDisplay())
}
}