diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/AndroidProjectSystem.xml b/.idea/AndroidProjectSystem.xml new file mode 100644 index 0000000..4a53bee --- /dev/null +++ b/.idea/AndroidProjectSystem.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..7643783 --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,123 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..79ee123 --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..b86273d --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/deploymentTargetSelector.xml b/.idea/deploymentTargetSelector.xml new file mode 100644 index 0000000..ca16a99 --- /dev/null +++ b/.idea/deploymentTargetSelector.xml @@ -0,0 +1,11 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/deviceManager.xml b/.idea/deviceManager.xml new file mode 100644 index 0000000..91f9558 --- /dev/null +++ b/.idea/deviceManager.xml @@ -0,0 +1,13 @@ + + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..cdbc250 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,17 @@ + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..a4f09e2 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,10 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml new file mode 100644 index 0000000..16660f1 --- /dev/null +++ b/.idea/runConfigurations.xml @@ -0,0 +1,17 @@ + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/build.gradle.kts b/app/build.gradle.kts index a994cf9..33548e8 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -1,20 +1,19 @@ plugins { alias(libs.plugins.android.application) + alias(libs.plugins.legacy.kapt) alias(libs.plugins.kotlin.compose) } android { namespace = "net.rodakot.remaining" compileSdk { - version = release(36) { - minorApiLevel = 1 - } + version = release(37) } defaultConfig { applicationId = "net.rodakot.remaining" minSdk = 29 - targetSdk = 36 + targetSdk = 37 versionCode = 1 versionName = "1.0" @@ -29,8 +28,8 @@ android { } } compileOptions { - sourceCompatibility = JavaVersion.VERSION_11 - targetCompatibility = JavaVersion.VERSION_11 + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 } buildFeatures { compose = true @@ -41,11 +40,22 @@ dependencies { implementation(platform(libs.androidx.compose.bom)) implementation(libs.androidx.activity.compose) implementation(libs.androidx.compose.material3) + implementation(libs.androidx.compose.material.icons.extended) implementation(libs.androidx.compose.ui) implementation(libs.androidx.compose.ui.graphics) implementation(libs.androidx.compose.ui.tooling.preview) implementation(libs.androidx.core.ktx) + implementation(libs.androidx.core.splashscreen) implementation(libs.androidx.lifecycle.runtime.ktx) + implementation(libs.androidx.lifecycle.viewmodel.compose) + implementation(libs.androidx.navigation.compose) + implementation(libs.androidx.room.ktx) + implementation(libs.androidx.room.runtime) + implementation(libs.androidx.work.runtime.ktx) + implementation(libs.jsoup) + implementation(libs.okhttp) + implementation(libs.org.json) + kapt(libs.androidx.room.compiler) testImplementation(libs.junit) androidTestImplementation(platform(libs.androidx.compose.bom)) androidTestImplementation(libs.androidx.compose.ui.test.junit4) @@ -53,4 +63,4 @@ dependencies { androidTestImplementation(libs.androidx.junit) debugImplementation(libs.androidx.compose.ui.test.manifest) debugImplementation(libs.androidx.compose.ui.tooling) -} \ No newline at end of file +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 63af67f..5cd3e00 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,21 +1,25 @@ - + + + + + @@ -25,4 +29,4 @@ - \ No newline at end of file + diff --git a/app/src/main/java/net/rodakot/remaining/AppContainer.kt b/app/src/main/java/net/rodakot/remaining/AppContainer.kt new file mode 100644 index 0000000..b6c5db4 --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/AppContainer.kt @@ -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) +} diff --git a/app/src/main/java/net/rodakot/remaining/MainActivity.kt b/app/src/main/java/net/rodakot/remaining/MainActivity.kt index c43477c..ad6abb9 100644 --- a/app/src/main/java/net/rodakot/remaining/MainActivity.kt +++ b/app/src/main/java/net/rodakot/remaining/MainActivity.kt @@ -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 + ) + } } -} \ No newline at end of file + + companion object { + private const val REQUEST_NOTIFICATIONS = 42 + } +} diff --git a/app/src/main/java/net/rodakot/remaining/RemainingApplication.kt b/app/src/main/java/net/rodakot/remaining/RemainingApplication.kt new file mode 100644 index 0000000..ed480d5 --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/RemainingApplication.kt @@ -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() + ) + } + } +} diff --git a/app/src/main/java/net/rodakot/remaining/connectors/ConnectorRegistry.kt b/app/src/main/java/net/rodakot/remaining/connectors/ConnectorRegistry.kt new file mode 100644 index 0000000..b3f17c3 --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/connectors/ConnectorRegistry.kt @@ -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 = listOf( + MciConnector(client), + JahanNamaConnector(client), + TciConnector() + ).associateBy { it.serviceType } + + fun connectorFor(serviceType: ServiceType): ServiceConnector = + connectors.getValue(serviceType) + + fun availableServices(): List = ServiceType.entries +} diff --git a/app/src/main/java/net/rodakot/remaining/connectors/ServiceConnector.kt b/app/src/main/java/net/rodakot/remaining/connectors/ServiceConnector.kt new file mode 100644 index 0000000..688b32c --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/connectors/ServiceConnector.kt @@ -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") + } +} diff --git a/app/src/main/java/net/rodakot/remaining/connectors/jahannama/JahanNamaConnector.kt b/app/src/main/java/net/rodakot/remaining/connectors/jahannama/JahanNamaConnector.kt new file mode 100644 index 0000000..3b52d3b --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/connectors/jahannama/JahanNamaConnector.kt @@ -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" + } +} diff --git a/app/src/main/java/net/rodakot/remaining/connectors/jahannama/JahanNamaParser.kt b/app/src/main/java/net/rodakot/remaining/connectors/jahannama/JahanNamaParser.kt new file mode 100644 index 0000000..d8878be --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/connectors/jahannama/JahanNamaParser.kt @@ -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 + ) + } +} diff --git a/app/src/main/java/net/rodakot/remaining/connectors/mci/MciConnector.kt b/app/src/main/java/net/rodakot/remaining/connectors/mci/MciConnector.kt new file mode 100644 index 0000000..c96d78d --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/connectors/mci/MciConnector.kt @@ -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() + } +} diff --git a/app/src/main/java/net/rodakot/remaining/connectors/mci/MciParser.kt b/app/src/main/java/net/rodakot/remaining/connectors/mci/MciParser.kt new file mode 100644 index 0000000..7b5f8d4 --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/connectors/mci/MciParser.kt @@ -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() +} diff --git a/app/src/main/java/net/rodakot/remaining/connectors/tci/TciConnector.kt b/app/src/main/java/net/rodakot/remaining/connectors/tci/TciConnector.kt new file mode 100644 index 0000000..73c36c6 --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/connectors/tci/TciConnector.kt @@ -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" + } +} diff --git a/app/src/main/java/net/rodakot/remaining/connectors/tci/TciCookieCodec.kt b/app/src/main/java/net/rodakot/remaining/connectors/tci/TciCookieCodec.kt new file mode 100644 index 0000000..02fd481 --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/connectors/tci/TciCookieCodec.kt @@ -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): 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 { + 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) + } + } + } +} diff --git a/app/src/main/java/net/rodakot/remaining/connectors/tci/TciHtmlParser.kt b/app/src/main/java/net/rodakot/remaining/connectors/tci/TciHtmlParser.kt new file mode 100644 index 0000000..6446c3a --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/connectors/tci/TciHtmlParser.kt @@ -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) +} diff --git a/app/src/main/java/net/rodakot/remaining/data/AccountRepository.kt b/app/src/main/java/net/rodakot/remaining/data/AccountRepository.kt new file mode 100644 index 0000000..24c7be3 --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/data/AccountRepository.kt @@ -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> = + 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 = dao.observeAccount(accountId) + + suspend fun getEnabledAccounts(): List = dao.getEnabledAccounts() + + @OptIn(ExperimentalCoroutinesApi::class) + fun observeAccountDetail(accountId: String): Flow { + 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 + ) + } +} diff --git a/app/src/main/java/net/rodakot/remaining/data/AppDatabase.kt b/app/src/main/java/net/rodakot/remaining/data/AppDatabase.kt new file mode 100644 index 0000000..92b1319 --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/data/AppDatabase.kt @@ -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 } + } + } +} diff --git a/app/src/main/java/net/rodakot/remaining/data/DashboardModels.kt b/app/src/main/java/net/rodakot/remaining/data/DashboardModels.kt new file mode 100644 index 0000000..8524962 --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/data/DashboardModels.kt @@ -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 +) diff --git a/app/src/main/java/net/rodakot/remaining/data/Entities.kt b/app/src/main/java/net/rodakot/remaining/data/Entities.kt new file mode 100644 index 0000000..8af20db --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/data/Entities.kt @@ -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? +) diff --git a/app/src/main/java/net/rodakot/remaining/data/RemainingDao.kt b/app/src/main/java/net/rodakot/remaining/data/RemainingDao.kt new file mode 100644 index 0000000..ce27bd1 --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/data/RemainingDao.kt @@ -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> + + @Query("SELECT * FROM accounts WHERE id = :accountId") + fun observeAccount(accountId: String): Flow + + @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 + + @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> + + @Query( + """ + SELECT * FROM usage_snapshots + WHERE accountId = :accountId + ORDER BY capturedAt DESC + LIMIT 1 + """ + ) + fun observeLatestSnapshot(accountId: String): Flow + + @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> + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun insertSnapshot(snapshot: UsageSnapshotEntity) + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun insertPackages(packages: List) + + @Transaction + suspend fun insertSnapshotWithPackages( + snapshot: UsageSnapshotEntity, + packages: List + ) { + insertSnapshot(snapshot) + if (packages.isNotEmpty()) { + insertPackages(packages) + } + } +} diff --git a/app/src/main/java/net/rodakot/remaining/data/SettingsRepository.kt b/app/src/main/java/net/rodakot/remaining/data/SettingsRepository.kt new file mode 100644 index 0000000..be66d49 --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/data/SettingsRepository.kt @@ -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 = 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" + } +} diff --git a/app/src/main/java/net/rodakot/remaining/domain/Models.kt b/app/src/main/java/net/rodakot/remaining/domain/Models.kt new file mode 100644 index 0000000..87c1a65 --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/domain/Models.kt @@ -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 = 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() +} diff --git a/app/src/main/java/net/rodakot/remaining/network/HttpClients.kt b/app/src/main/java/net/rodakot/remaining/network/HttpClients.kt new file mode 100644 index 0000000..e3c01cb --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/network/HttpClients.kt @@ -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 = emptyList()) : CookieJar { + private val cookies = mutableListOf() + + init { + cookies += initialCookies.filter { it.expiresAt > System.currentTimeMillis() } + } + + @Synchronized + override fun saveFromResponse(url: HttpUrl, cookies: List) { + 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 { + val now = System.currentTimeMillis() + cookies.removeAll { it.expiresAt <= now } + return cookies.filter { it.matches(url) } + } + + @Synchronized + fun allCookies(): List = cookies.toList() +} diff --git a/app/src/main/java/net/rodakot/remaining/refresh/AccountRefreshWorker.kt b/app/src/main/java/net/rodakot/remaining/refresh/AccountRefreshWorker.kt new file mode 100644 index 0000000..f4353ce --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/refresh/AccountRefreshWorker.kt @@ -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" + } +} diff --git a/app/src/main/java/net/rodakot/remaining/refresh/NotificationHelper.kt b/app/src/main/java/net/rodakot/remaining/refresh/NotificationHelper.kt new file mode 100644 index 0000000..e87e821 --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/refresh/NotificationHelper.kt @@ -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" + } +} diff --git a/app/src/main/java/net/rodakot/remaining/refresh/RefreshScheduler.kt b/app/src/main/java/net/rodakot/remaining/refresh/RefreshScheduler.kt new file mode 100644 index 0000000..44be0cf --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/refresh/RefreshScheduler.kt @@ -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( + 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) { + accounts.forEach(::schedule) + } + + private fun workName(accountId: String): String = "refresh_account_$accountId" +} diff --git a/app/src/main/java/net/rodakot/remaining/security/SecretCipher.kt b/app/src/main/java/net/rodakot/remaining/security/SecretCipher.kt new file mode 100644 index 0000000..9f11ce9 --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/security/SecretCipher.kt @@ -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" + } +} diff --git a/app/src/main/java/net/rodakot/remaining/ui/RemainingApp.kt b/app/src/main/java/net/rodakot/remaining/ui/RemainingApp.kt new file mode 100644 index 0000000..4fefede --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/ui/RemainingApp.kt @@ -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" +} diff --git a/app/src/main/java/net/rodakot/remaining/ui/RemainingViewModel.kt b/app/src/main/java/net/rodakot/remaining/ui/RemainingViewModel.kt new file mode 100644 index 0000000..2b4f2d2 --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/ui/RemainingViewModel.kt @@ -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 = emptySet(), + val globalBusy: Boolean = false, + val message: String? = null, + val captcha: CaptchaUiState? = null +) + +data class RemainingUiState( + val accounts: List = 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 = + 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 create(modelClass: Class): T { + return RemainingViewModel(container) as T + } + } +} diff --git a/app/src/main/java/net/rodakot/remaining/ui/components/UiHelpers.kt b/app/src/main/java/net/rodakot/remaining/ui/components/UiHelpers.kt new file mode 100644 index 0000000..dd62060 --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/ui/components/UiHelpers.kt @@ -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" diff --git a/app/src/main/java/net/rodakot/remaining/ui/screens/AccountDetailScreen.kt b/app/src/main/java/net/rodakot/remaining/ui/screens/AccountDetailScreen.kt new file mode 100644 index 0000000..1b3642c --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/ui/screens/AccountDetailScreen.kt @@ -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) + } + } + } +} diff --git a/app/src/main/java/net/rodakot/remaining/ui/screens/AddAccountScreen.kt b/app/src/main/java/net/rodakot/remaining/ui/screens/AddAccountScreen.kt new file mode 100644 index 0000000..20fa368 --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/ui/screens/AddAccountScreen.kt @@ -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 PresetChips( + options: List, + 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)) {} + } + } + } + } +} diff --git a/app/src/main/java/net/rodakot/remaining/ui/screens/DashboardScreen.kt b/app/src/main/java/net/rodakot/remaining/ui/screens/DashboardScreen.kt new file mode 100644 index 0000000..6f410ad --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/ui/screens/DashboardScreen.kt @@ -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) { + 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 + ) + } + } +} diff --git a/app/src/main/java/net/rodakot/remaining/ui/screens/SettingsScreen.kt b/app/src/main/java/net/rodakot/remaining/ui/screens/SettingsScreen.kt new file mode 100644 index 0000000..40726ee --- /dev/null +++ b/app/src/main/java/net/rodakot/remaining/ui/screens/SettingsScreen.kt @@ -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)) {} + } + } + } + } + } +} diff --git a/app/src/main/java/net/rodakot/remaining/ui/theme/Color.kt b/app/src/main/java/net/rodakot/remaining/ui/theme/Color.kt index 1e99cb6..adf3beb 100644 --- a/app/src/main/java/net/rodakot/remaining/ui/theme/Color.kt +++ b/app/src/main/java/net/rodakot/remaining/ui/theme/Color.kt @@ -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) \ No newline at end of file +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) diff --git a/app/src/main/java/net/rodakot/remaining/ui/theme/Theme.kt b/app/src/main/java/net/rodakot/remaining/ui/theme/Theme.kt index 7cadde1..56b4adc 100644 --- a/app/src/main/java/net/rodakot/remaining/ui/theme/Theme.kt +++ b/app/src/main/java/net/rodakot/remaining/ui/theme/Theme.kt @@ -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 ) -} \ No newline at end of file +} diff --git a/app/src/main/java/net/rodakot/remaining/ui/theme/Type.kt b/app/src/main/java/net/rodakot/remaining/ui/theme/Type.kt index d42cc6f..4a72485 100644 --- a/app/src/main/java/net/rodakot/remaining/ui/theme/Type.kt +++ b/app/src/main/java/net/rodakot/remaining/ui/theme/Type.kt @@ -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 ) - */ -) \ No newline at end of file +) diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml index 07d5da9..71e5f9d 100644 --- a/app/src/main/res/drawable/ic_launcher_background.xml +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -1,170 +1,34 @@ + + + + + + + + + + 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" /> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + android:fillColor="#1F8FD8FF" + android:pathData="M14,70C28,60 47,63 58,76C69,89 89,93 105,82L105,108L14,108Z" /> diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml index 2b068d1..8ff1443 100644 --- a/app/src/main/res/drawable/ic_launcher_foreground.xml +++ b/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -1,30 +1,48 @@ + - - - - - - - - + + + + + + + - \ No newline at end of file + android:pathData="M77,31L80,37L86,40L80,43L77,49L74,43L68,40L74,37Z" /> + diff --git a/app/src/main/res/drawable/ic_splash_mark.xml b/app/src/main/res/drawable/ic_splash_mark.xml new file mode 100644 index 0000000..b760eab --- /dev/null +++ b/app/src/main/res/drawable/ic_splash_mark.xml @@ -0,0 +1,45 @@ + + + + + + + + + + diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml index f8c6127..0c96770 100644 --- a/app/src/main/res/values/colors.xml +++ b/app/src/main/res/values/colors.xml @@ -1,10 +1,9 @@ - #FFBB86FC - #FF6200EE - #FF3700B3 - #FF03DAC5 - #FF018786 + #0D1117 + #151B23 + #8FD8FF + #3DDC84 #FF000000 #FFFFFFFF - \ No newline at end of file + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ef317b0..04a9420 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,3 +1,3 @@ - remaining - \ No newline at end of file + Remaining + diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml index e05618e..791636d 100644 --- a/app/src/main/res/values/themes.xml +++ b/app/src/main/res/values/themes.xml @@ -1,5 +1,19 @@ - + + + diff --git a/app/src/test/java/net/rodakot/remaining/connectors/ParserTest.kt b/app/src/test/java/net/rodakot/remaining/connectors/ParserTest.kt new file mode 100644 index 0000000..13c4b4b --- /dev/null +++ b/app/src/test/java/net/rodakot/remaining/connectors/ParserTest.kt @@ -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("""logout""")) + assertTrue(TciHtmlParser.isAuthenticated("""خروج""")) + } + + @Test + fun tciParsesPersianReservedTraffic() { + val snapshot = TciHtmlParser.parseReservedTraffic( + """ + + +
میزان ترافیک رزرو شما ۱۲٫۵ گیگابایت
+ + + """.trimIndent() + ) + + assertEquals("12.50 GB", snapshot.remainingDisplay) + } + + @Test + fun trafficFormattingUsesMegabytesBelowOneGigabyte() { + assertEquals("512 MB", (512L * 1024L * 1024L).asTrafficDisplay()) + } +} diff --git a/build.gradle.kts b/build.gradle.kts index 18318be..7ca872f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,5 +1,6 @@ // Top-level build file where you can add configuration options common to all sub-projects/modules. plugins { alias(libs.plugins.android.application) apply false + alias(libs.plugins.legacy.kapt) apply false alias(libs.plugins.kotlin.compose) apply false -} \ No newline at end of file +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 324b701..7353007 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,16 +1,24 @@ [versions] agp = "9.2.1" coreKtx = "1.19.0" +coreSplashscreen = "1.2.0" junit = "4.13.2" junitVersion = "1.3.0" espressoCore = "3.7.0" lifecycleRuntimeKtx = "2.11.0" activityCompose = "1.13.0" -kotlin = "2.2.10" -composeBom = "2026.02.01" +kotlin = "2.3.21" +composeBom = "2026.06.00" +navigationCompose = "2.9.8" +room = "2.8.4" +work = "2.11.2" +okhttp = "5.4.0" +jsoup = "1.22.2" +orgJson = "20260522" [libraries] androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } +androidx-core-splashscreen = { group = "androidx.core", name = "core-splashscreen", version.ref = "coreSplashscreen" } junit = { group = "junit", name = "junit", version.ref = "junit" } androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" } androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" } @@ -24,8 +32,18 @@ androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "u androidx-compose-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" } androidx-compose-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" } androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" } +androidx-compose-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended" } +androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycleRuntimeKtx" } +androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" } +androidx-room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" } +androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" } +androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" } +androidx-work-runtime-ktx = { group = "androidx.work", name = "work-runtime-ktx", version.ref = "work" } +okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" } +jsoup = { group = "org.jsoup", name = "jsoup", version.ref = "jsoup" } +org-json = { group = "org.json", name = "json", version.ref = "orgJson" } [plugins] android-application = { id = "com.android.application", version.ref = "agp" } +legacy-kapt = { id = "com.android.legacy-kapt", version.ref = "agp" } kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } -