diff --git a/.idea/caches/deviceStreaming.xml b/.idea/caches/deviceStreaming.xml new file mode 100644 index 0000000..6a3e9f5 --- /dev/null +++ b/.idea/caches/deviceStreaming.xml @@ -0,0 +1,1550 @@ + + + + + + \ 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/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..aa724b7 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,15 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/android/.idea/.gitignore b/android/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/android/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/android/.idea/.name b/android/.idea/.name new file mode 100644 index 0000000..00796b0 --- /dev/null +++ b/android/.idea/.name @@ -0,0 +1 @@ +Chatapp \ No newline at end of file diff --git a/android/.idea/AndroidProjectSystem.xml b/android/.idea/AndroidProjectSystem.xml new file mode 100644 index 0000000..4a53bee --- /dev/null +++ b/android/.idea/AndroidProjectSystem.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/android/.idea/appInsightsSettings.xml b/android/.idea/appInsightsSettings.xml new file mode 100644 index 0000000..7f73dc8 --- /dev/null +++ b/android/.idea/appInsightsSettings.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/android/.idea/codeStyles/Project.xml b/android/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..7643783 --- /dev/null +++ b/android/.idea/codeStyles/Project.xml @@ -0,0 +1,123 @@ + + + + + + + + + + \ No newline at end of file diff --git a/android/.idea/codeStyles/codeStyleConfig.xml b/android/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..79ee123 --- /dev/null +++ b/android/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/android/.idea/compiler.xml b/android/.idea/compiler.xml new file mode 100644 index 0000000..b86273d --- /dev/null +++ b/android/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/android/.idea/deploymentTargetSelector.xml b/android/.idea/deploymentTargetSelector.xml new file mode 100644 index 0000000..fc8303f --- /dev/null +++ b/android/.idea/deploymentTargetSelector.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/android/.idea/deviceManager.xml b/android/.idea/deviceManager.xml new file mode 100644 index 0000000..91f9558 --- /dev/null +++ b/android/.idea/deviceManager.xml @@ -0,0 +1,13 @@ + + + + + + \ No newline at end of file diff --git a/android/.idea/gradle.xml b/android/.idea/gradle.xml new file mode 100644 index 0000000..02c4aa5 --- /dev/null +++ b/android/.idea/gradle.xml @@ -0,0 +1,18 @@ + + + + + + + \ No newline at end of file diff --git a/android/.idea/inspectionProfiles/Project_Default.xml b/android/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..7061a0d --- /dev/null +++ b/android/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,61 @@ + + + + \ No newline at end of file diff --git a/android/.idea/misc.xml b/android/.idea/misc.xml new file mode 100644 index 0000000..b2c751a --- /dev/null +++ b/android/.idea/misc.xml @@ -0,0 +1,9 @@ + + + + + + + + \ No newline at end of file diff --git a/android/.idea/runConfigurations.xml b/android/.idea/runConfigurations.xml new file mode 100644 index 0000000..16660f1 --- /dev/null +++ b/android/.idea/runConfigurations.xml @@ -0,0 +1,17 @@ + + + + + + \ No newline at end of file diff --git a/android/.idea/studiobot.xml b/android/.idea/studiobot.xml new file mode 100644 index 0000000..539e3b8 --- /dev/null +++ b/android/.idea/studiobot.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/android/.idea/vcs.xml b/android/.idea/vcs.xml new file mode 100644 index 0000000..6c0b863 --- /dev/null +++ b/android/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/android/app/.gitignore b/android/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/android/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..46ac932 --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,76 @@ +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.compose) + alias(libs.plugins.kotlin.serialization) +} + +android { + namespace = "dev.zxq5.chatapp.android" + compileSdk = 35 + + defaultConfig { + applicationId = "dev.zxq5.chatapp.android" + minSdk = 26 + targetSdk = 35 + versionCode = 1 + versionName = "1.0" + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + buildFeatures { + compose = true + } +} + +dependencies { + // Ktor client + implementation(libs.ktor.client.android) + implementation(libs.ktor.client.content.negotiation) + implementation(libs.ktor.serialization.kotlinx.json) + implementation(libs.ktor.client.auth) // Auth plugin + // Kotlinx Serialization + implementation(libs.kotlinx.serialization.json) + + // Coroutines + implementation(libs.kotlinx.coroutines.android) + + // ViewModel + implementation(libs.androidx.lifecycle.viewmodel.compose) + + // Encrypted storage for session cookie/token + implementation(libs.androidx.security.crypto) + + + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.lifecycle.runtime.ktx) + implementation(libs.androidx.activity.compose) + implementation(platform(libs.androidx.compose.bom)) + implementation(libs.androidx.compose.ui) + implementation(libs.androidx.compose.ui.graphics) + implementation(libs.androidx.compose.ui.tooling.preview) + implementation(libs.androidx.compose.material3) + implementation(libs.androidx.compose.foundation.layout) + implementation(libs.androidx.compose.material.icons.extended) + + testImplementation(libs.junit) + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.espresso.core) + androidTestImplementation(platform(libs.androidx.compose.bom)) + androidTestImplementation(libs.androidx.compose.ui.test.junit4) + debugImplementation(libs.androidx.compose.ui.tooling) + debugImplementation(libs.androidx.compose.ui.test.manifest) +} \ No newline at end of file diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/android/app/src/androidTest/java/dev/zxq5/chatapp/android/ExampleInstrumentedTest.kt b/android/app/src/androidTest/java/dev/zxq5/chatapp/android/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..9e02c75 --- /dev/null +++ b/android/app/src/androidTest/java/dev/zxq5/chatapp/android/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package dev.zxq5.chatapp.android + +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("dev.zxq5.chatapp.android", appContext.packageName) + } +} \ No newline at end of file diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..92adfa2 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/ChatApplication.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/ChatApplication.kt new file mode 100644 index 0000000..907df9a --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/ChatApplication.kt @@ -0,0 +1,11 @@ +package dev.zxq5.chatapp.android + +import android.app.Application +import dev.zxq5.chatapp.android.api.ApiClient + +class ChatApplication : Application() { + override fun onCreate() { + super.onCreate() + ApiClient.init(this) + } +} diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/MainActivity.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/MainActivity.kt new file mode 100644 index 0000000..d8d1512 --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/MainActivity.kt @@ -0,0 +1,50 @@ +package dev.zxq5.chatapp.android + +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.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.lifecycle.viewmodel.compose.viewModel +import dev.zxq5.chatapp.android.model.ChatViewModel +import dev.zxq5.chatapp.android.model.LoginState +import dev.zxq5.chatapp.android.model.MainScreen +import dev.zxq5.chatapp.android.ui.components.AuthScreen +import dev.zxq5.chatapp.android.ui.components.ChatScreen +import dev.zxq5.chatapp.android.ui.components.SettingsScreen +import dev.zxq5.chatapp.android.ui.theme.ChatappTheme + +class MainActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + setContent { + ChatappTheme { + val viewModel: ChatViewModel = viewModel() + val loginState by viewModel.loginState.collectAsState() + val currentScreen by viewModel.currentScreen.collectAsState() + + Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding -> + androidx.compose.foundation.layout.Box(modifier = Modifier.padding(innerPadding)) { + if (loginState is LoginState.Success) { + when (currentScreen) { + MainScreen.CHAT -> ChatScreen(viewModel = viewModel) + MainScreen.SETTINGS -> SettingsScreen(viewModel = viewModel) + } + } else { + AuthScreen( + viewModel = viewModel, + onSuccess = { } + ) + } + } + } + } + } + } +} diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/api/ApiClient.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/api/ApiClient.kt new file mode 100644 index 0000000..7c9e333 --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/api/ApiClient.kt @@ -0,0 +1,361 @@ +package dev.zxq5.chatapp.android.api + +import android.content.Context +import android.util.Log +import dev.zxq5.chatapp.android.core.data.TokenStore.getScopeFromToken +import dev.zxq5.chatapp.android.model.LoginRequest +import dev.zxq5.chatapp.android.model.LoginResponse +import dev.zxq5.chatapp.android.model.Message +import dev.zxq5.chatapp.android.model.SendMessage +import dev.zxq5.chatapp.android.model.SignupRequest +import io.ktor.client.HttpClient +import io.ktor.client.call.body +import io.ktor.client.engine.android.Android +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.client.request.get +import io.ktor.client.request.post +import io.ktor.client.request.delete +import io.ktor.client.request.prepareGet +import io.ktor.client.request.setBody +import io.ktor.client.statement.bodyAsChannel +import io.ktor.http.ContentType +import io.ktor.http.contentType +import io.ktor.http.isSuccess +import io.ktor.serialization.kotlinx.json.json +import io.ktor.utils.io.readUTF8Line +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flow +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +import io.ktor.client.plugins.auth.Auth +import io.ktor.client.plugins.auth.providers.BearerTokens +import io.ktor.client.plugins.auth.providers.bearer +import io.ktor.http.encodedPath +import dev.zxq5.chatapp.android.core.BASE_URL +import dev.zxq5.chatapp.android.core.data.TokenStore +import dev.zxq5.chatapp.android.core.data.TokenStore.getUserIdFromToken +import dev.zxq5.chatapp.android.core.error.ApiResult +import kotlinx.serialization.KSerializer +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder + +@Serializable +data class QrResponse(val qr_code: String) + +@Serializable +data class TOTPSixDigitCode(val code: String) + +@Serializable(with = TotpStatusSerializer::class) +enum class TotpStatus { + ENABLED, DISABLED; + + val isEnabled: Boolean get() = this == ENABLED +} + +object TotpStatusSerializer : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("TotpStatus", PrimitiveKind.STRING) + override fun serialize(encoder: Encoder, value: TotpStatus) = encoder.encodeString(value.name.lowercase()) + override fun deserialize(decoder: Decoder): TotpStatus = + TotpStatus.valueOf(decoder.decodeString().uppercase()) +} + +@Serializable +data class TotpStatusResponse(val status: TotpStatus) + +@Serializable +data class PasswordChangeRequest(val old_password: String, val new_password: String) + +@Serializable +data class DisplayNameRequest(val display_name: String?) + +object ApiClient { + private lateinit var appContext: Context + + fun init(context: Context) { + appContext = context.applicationContext + } + + fun hasToken(): Boolean { + return TokenStore.get(appContext) != null + } + + fun getTokenScope(): String? { + val token = TokenStore.get(appContext) ?: return null + val scope = getScopeFromToken(token) + Log.d("Chat", "Current token scope: $scope") + return scope + } + + fun getStoredUserId(): Int? { + return TokenStore.getUserId(appContext) + } + + fun is2faEnabledLocal(): Boolean { + return TokenStore.is2faEnabled(appContext) + } + + fun set2faEnabledLocal(enabled: Boolean) { + TokenStore.save2faEnabled(appContext, enabled) + } + + private var _http: HttpClient? = null + val http: HttpClient + get() = synchronized(this) { + _http ?: createClient().also { _http = it } + } + + private fun createClient(): HttpClient { + return HttpClient(Android) { + install(ContentNegotiation) { + json(Json { ignoreUnknownKeys = true }) + } + install(Auth) { + bearer { + loadTokens { + val token = TokenStore.get(appContext) ?: return@loadTokens null + Log.d("Chat", "Auth plugin loading token: ${getScopeFromToken(token)}") + BearerTokens(token, "") + } + sendWithoutRequest { request -> + val path = request.url.encodedPath + !path.endsWith("/login") && !path.endsWith("/signup") + } + } + } + } + } + + private fun resetClient() { + Log.d("Chat", "Resetting HttpClient to refresh tokens") + _http?.close() + _http = null + } + + suspend fun login(username: String, password: String): ApiResult { + return try { + val response = http.post("${BASE_URL}/api/login") { + contentType(ContentType.Application.Json) + setBody(LoginRequest(username, password)) + } + if (response.status.isSuccess()) { + val body = response.body() + Log.d("Chat", "Login token scope: ${getScopeFromToken(body.token)}") + TokenStore.save(appContext, body.token) + resetClient() + ApiResult.Success(body) + } else { + ApiResult.HttpError( + status = response.status.value, + message = when (response.status.value) { + 401 -> "Invalid username or password" + 403 -> "Account suspended" + 429 -> "Too many attempts, please wait" + else -> "Login failed (${response.status.value})" + } + ) + } + } catch (e: Exception) { + Log.e("Chat", "Login network error", e) + ApiResult.NetworkError(e.localizedMessage ?: "Network error") + } + } + + suspend fun signup(username: String, email: String, password: String, token: String): ApiResult { + return try { + val response = http.post("${BASE_URL}/api/signup") { + contentType(ContentType.Application.Json) + setBody(SignupRequest(username = username, email = email, password = password, access_token = token)) + } + if (response.status.isSuccess()) { + val body = response.body() + TokenStore.save(appContext, body.token) + resetClient() + ApiResult.Success(body) + } else { + ApiResult.HttpError( + status = response.status.value, + message = when (response.status.value) { + 401 -> "Invalid access token" + else -> "Signup failed (${response.status.value})" + } + ) + } + } catch (e: Exception) { + Log.e("Chat", "Signup error", e) + ApiResult.NetworkError(e.localizedMessage ?: "Network error") + } + } + + fun logout() { + TokenStore.clear(appContext) + resetClient() + } + + suspend fun sendMessage(channelId: Int, text: String) { + val userId = TokenStore.getUserId(appContext) ?: return + http.post("${BASE_URL}/api/chat/$channelId") { + contentType(ContentType.Application.Json) + setBody(SendMessage( + user_id = userId, + text = text, + timestamp = System.currentTimeMillis() + )) + } + } + + fun messageStream(channelId: Int): Flow = flow { + http.prepareGet("${BASE_URL}/api/events/$channelId").execute { response -> + val channel = response.bodyAsChannel() + while (!channel.isClosedForRead) { + val line = channel.readUTF8Line(256) ?: break + if (line.startsWith("data:")) { + val json = line.removePrefix("data:").trim() + runCatching { Json.decodeFromString(json) } + .onSuccess { emit(it) } + } + } + } + } + + suspend fun getTotpQr(): QrResponse? { + return try { + http.get("${BASE_URL}/api/totp.jpg").body() + } catch (e: Exception) { + Log.e("Chat", "Error fetching TOTP QR", e) + null + } + } + + suspend fun confirmTotp(code: String): Boolean { + return try { + val response = http.post("${BASE_URL}/api/totp") { + contentType(ContentType.Application.Json) + setBody(TOTPSixDigitCode(code)) + } + if (response.status.isSuccess()) { + // If confirming TOTP returns a new token (e.g. from partial to full), we should save it + // Assuming confirm might return a LoginResponse if it upgrades the session + runCatching { + val body = response.body() + TokenStore.save(appContext, body.token) + resetClient() + } + set2faEnabledLocal(true) + true + } else { + false + } + } catch (e: Exception) { + Log.e("Chat", "Error confirming TOTP", e) + false + } + } + + suspend fun verifyTotpLogin(code: String): ApiResult { + return try { + val response = http.post("${BASE_URL}/api/totp/verify") { + contentType(ContentType.Application.Json) + setBody(TOTPSixDigitCode(code)) + } + if (response.status.isSuccess()) { + val body = response.body() + + val tok = body.token; + Log.d("Chat", "UID ${getUserIdFromToken(tok)}"); + Log.d("Chat", "Token ${getScopeFromToken(tok)}"); + + TokenStore.save(appContext, body.token) + resetClient() + ApiResult.Success(body) + } else { + val errorText = try { response.body() } catch (e: Exception) { "Unknown error" } + Log.e("Chat", "TOTP verify failed: ${response.status.value} - $errorText") + ApiResult.HttpError( + status = response.status.value, + message = when (response.status.value) { + 401 -> "Incorrect code, please try again" + 403 -> "Session expired, please log in again" + 429 -> "Too many attempts, please wait" + else -> "Verification failed (${response.status.value})" + } + ) + } + } catch (e: Exception) { + Log.e("Chat", "TOTP verify network error", e) + ApiResult.NetworkError(e.localizedMessage ?: "Network error") + } + } + + suspend fun getTotpStatus(): Boolean { + return try { + val response = http.get("${BASE_URL}/api/totp/status") + if (response.status.isSuccess()) { + val status = response.body() + val enabled = status.isEnabled + set2faEnabledLocal(enabled) + enabled + } else { + is2faEnabledLocal() + } + } catch (e: Exception) { + Log.e("Chat", "Error getting TOTP status", e) + is2faEnabledLocal() + } + } + + suspend fun disableTotp(): ApiResult { + return try { + val response = http.delete("${BASE_URL}/api/totp") + if (response.status.isSuccess()) { + val body = response.body() + TokenStore.save(appContext, body.token) + set2faEnabledLocal(false) + resetClient() + ApiResult.Success(body) + } else { + ApiResult.HttpError(response.status.value, "Failed to disable TOTP") + } + } catch (e: Exception) { + Log.e("Chat", "Error disabling TOTP", e) + ApiResult.NetworkError(e.localizedMessage ?: "Network error") + } + } + + suspend fun changePassword(old: String, new: String): ApiResult { + return try { + val response = http.post("${BASE_URL}/api/settings/password") { + contentType(ContentType.Application.Json) + setBody(PasswordChangeRequest(old, new)) + } + if (response.status.isSuccess()) { + ApiResult.Success(Unit) + } else { + ApiResult.HttpError( + response.status.value, + if (response.status.value == 401) "Old password is wrong" else "Password change failed" + ) + } + } catch (e: Exception) { + Log.e("Chat", "Error changing password", e) + ApiResult.NetworkError(e.localizedMessage ?: "Network error") + } + } + + suspend fun updateDisplayName(name: String?): Boolean { + return try { + val response = http.post("${BASE_URL}/api/settings/display_name") { + contentType(ContentType.Application.Json) + setBody(DisplayNameRequest(name)) + } + response.status.isSuccess() + } catch (e: Exception) { + Log.e("Chat", "Error updating display name", e) + false + } + } +} + diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/core/constants.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/core/constants.kt new file mode 100644 index 0000000..c67d567 --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/core/constants.kt @@ -0,0 +1,3 @@ +package dev.zxq5.chatapp.android.core + +const val BASE_URL = "http://zxq5-x1:8000" \ No newline at end of file diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/core/data/TokenStore.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/core/data/TokenStore.kt new file mode 100644 index 0000000..f25e33c --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/core/data/TokenStore.kt @@ -0,0 +1,78 @@ +package dev.zxq5.chatapp.android.core.data + +import android.content.Context +import android.content.SharedPreferences +import android.util.Base64 +import androidx.core.content.edit +import androidx.security.crypto.EncryptedSharedPreferences +import androidx.security.crypto.MasterKey +import org.json.JSONObject + +// In your ApiClient or a dedicated TokenStore +object TokenStore { + private const val KEY = "auth_token" + private const val TWOFA_KEY = "twofa_enabled" + + private fun prefs(context: Context): SharedPreferences { + return EncryptedSharedPreferences.create( + context, + "secure_prefs", + MasterKey.Builder(context) + .setKeyScheme(MasterKey.KeyScheme.AES256_GCM) + .build(), + EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, + EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM + ) + } + + fun save(context: Context, token: String) = + prefs(context).edit { putString(KEY, token) } + + fun get(context: Context): String? = + prefs(context).getString(KEY, null) + + fun save2faEnabled(context: Context, enabled: Boolean) = + prefs(context).edit { putBoolean(TWOFA_KEY, enabled) } + + fun is2faEnabled(context: Context): Boolean = + prefs(context).getBoolean(TWOFA_KEY, false) + + fun clear(context: Context) = + prefs(context).edit { remove(KEY).remove(TWOFA_KEY) } + + fun getUserId(context: Context): Int? { + val token = get(context) ?: return null + return getUserIdFromToken(token) + } + + fun getUserIdFromToken(token: String): Int? { + return try { + val payload = token.split(".")[1] + // base64url needs padding restored + val padded = payload + "==".take((4 - payload.length % 4) % 4) + val jsonString = String(Base64.decode(padded, Base64.URL_SAFE)) + val json = JSONObject(jsonString) + + // Handle both standard 'sub' and custom 'user_id' + when { + json.has("sub") -> json.getInt("sub") + json.has("user_id") -> json.getInt("user_id") + else -> null + } + } catch (e: Exception) { + null + } + } + + fun getScopeFromToken(token: String): String? { + return try { + val payload = token.split(".")[1] + val padded = payload + "==".take((4 - payload.length % 4) % 4) + val jsonString = String(Base64.decode(padded, Base64.URL_SAFE)) + val json = JSONObject(jsonString) + if (json.has("scope")) json.getString("scope") else null + } catch (e: Exception) { + null + } + } +} \ No newline at end of file diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/core/error/ApiResult.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/core/error/ApiResult.kt new file mode 100644 index 0000000..3c90458 --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/core/error/ApiResult.kt @@ -0,0 +1,7 @@ +package dev.zxq5.chatapp.android.core.error + +sealed class ApiResult { + data class Success(val data: T) : ApiResult() + data class HttpError(val status: Int, val message: String) : ApiResult() + data class NetworkError(val message: String) : ApiResult() +} \ No newline at end of file diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/data/repository/AuthRepository.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/data/repository/AuthRepository.kt new file mode 100644 index 0000000..6d5a3b5 --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/data/repository/AuthRepository.kt @@ -0,0 +1,35 @@ +package dev.zxq5.chatapp.android.data.repository + +import dev.zxq5.chatapp.android.api.ApiClient +import dev.zxq5.chatapp.android.core.data.TokenStore +import dev.zxq5.chatapp.android.core.error.ApiResult +// +//class AuthRepository( +// private val apiClient: ApiClient, +// private val tokenStore: TokenStore, +//) { +// +// suspend fun login(username: String, password: String): LoginResult { +//// return when(val result = apiClient.login(username, password)) { +//// is ApiResult.Success -> { +//// tokenStore.save(context = context, result.data.token); +//// } +//// } +// } +//} + + + + +sealed class LoginResult { + object Success : LoginResult() + object TotpRequired : LoginResult() // step 1 outcome → go to totp screen + data class TotpError(val message: String) : LoginResult() // step 2 failure → stay on totp screen, show error + data class Error(val message: String) : LoginResult() // general failure → show on login form +} + +sealed class AuthState { + object Authenticated : AuthState() + object AwaitingTotp : AuthState() + object Unauthenticated : AuthState() +} \ No newline at end of file diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/model/ChatViewModel.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/model/ChatViewModel.kt new file mode 100644 index 0000000..53ea713 --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/model/ChatViewModel.kt @@ -0,0 +1,325 @@ +package dev.zxq5.chatapp.android.model + +import android.util.Log +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dev.zxq5.chatapp.android.api.ApiClient +import dev.zxq5.chatapp.android.core.error.ApiResult +import dev.zxq5.chatapp.android.api.QrResponse +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.catch +import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch + +enum class AuthMode { + LOGIN, SIGNUP +} + +enum class MainScreen { + CHAT, SETTINGS +} + +class ChatViewModel : ViewModel() { + + private val _messages = MutableStateFlow>(emptyList()) + val messages: StateFlow> = _messages + + private val _channelId = MutableStateFlow(null) + val channelId: StateFlow = _channelId + + private val _currentUserId = MutableStateFlow(null) + val currentUserId: StateFlow = _currentUserId + + private val _currentScreen = MutableStateFlow(MainScreen.CHAT) + val currentScreen: StateFlow = _currentScreen + + val loginState = MutableStateFlow(LoginState.Idle) + + // Tracks whether the user is viewing the Login or Signup screen + val authMode = MutableStateFlow(AuthMode.LOGIN) + + // 2FA state + private val _totpQr = MutableStateFlow(null) + val totpQr: StateFlow = _totpQr + + private val _is2faEnabled = MutableStateFlow(false) + val is2faEnabled: StateFlow = _is2faEnabled + + private val _totpError = MutableStateFlow(null) + val totpError: StateFlow = _totpError + + // Settings state + private val _settingsError = MutableStateFlow(null) + val settingsError: StateFlow = _settingsError + + private val _settingsSuccess = MutableStateFlow(null) + val settingsSuccess: StateFlow = _settingsSuccess + + fun clearSettingsMessages() { + _settingsError.value = null + _settingsSuccess.value = null + } + + fun clearTotpError() { + _totpError.value = null + } + + private var streamJob: Job? = null + + init { + initAuth(ApiClient.hasToken()) + } + + fun initAuth(hasToken: Boolean) { + if (hasToken) { + val scope = ApiClient.getTokenScope() + if (scope == TokenScope.TOTP_PENDING) { + loginState.value = LoginState.TwoFactorRequired + } else if (scope == TokenScope.FULL) { + loginState.value = LoginState.Success + _currentUserId.value = ApiClient.getStoredUserId() + _is2faEnabled.value = ApiClient.is2faEnabledLocal() + fetchTotpStatus() + observeChannel() + } else { + loginState.value = LoginState.Error("Unknown token scope: $scope") + } + } else { + loginState.value = LoginState.Idle + } + } + + private fun observeChannel() { + // restart stream whenever channel changes + viewModelScope.launch { + _channelId.filterNotNull().collect { id -> + streamJob?.cancel() + _messages.value = emptyList() + streamJob = launch { + ApiClient.messageStream(id) + .catch { e -> + Log.e("Chat", "Stream error", e) + } + .collect { message -> + _messages.update { it + message } + } + } + } + } + } + + fun navigateTo(screen: MainScreen) { + _currentScreen.value = screen + if (screen == MainScreen.SETTINGS) { + fetchTotpStatus() + } + } + + fun switchChannel(id: Int?) { + _channelId.value = id + } + + fun setAuthMode(mode: AuthMode) { + authMode.value = mode + // Clear errors when switching modes + if (loginState.value is LoginState.Error || loginState.value is LoginState.TwoFactorRequired) { + loginState.value = LoginState.Idle + } + } + + fun sendMessage(text: String) { + val currentId = _channelId.value ?: return + viewModelScope.launch { + runCatching { + ApiClient.sendMessage( + channelId = currentId, + text = text + ) + }.onFailure { e -> + Log.e("Chat", "Send message error", e) + } + } + } + + fun login(username: String, password: String) { + viewModelScope.launch { + loginState.value = LoginState.Loading + when (val result = ApiClient.login(username, password)) { + is ApiResult.Success -> { + when (val scope = ApiClient.getTokenScope()) { + TokenScope.FULL -> { + _currentUserId.value = ApiClient.getStoredUserId() + _is2faEnabled.value = ApiClient.is2faEnabledLocal() + loginState.value = LoginState.Success + fetchTotpStatus() + observeChannel() + } + TokenScope.TOTP_PENDING -> { + loginState.value = LoginState.TwoFactorRequired + } + else -> { + loginState.value = LoginState.Error("Unknown token scope: $scope") + } + } + } + is ApiResult.HttpError -> { + loginState.value = LoginState.Error(result.message) + } + is ApiResult.NetworkError -> { + loginState.value = LoginState.Error("Could not reach server: ${result.message}") + } + } + } + } + + fun verifyLogin2fa(code: String) { + viewModelScope.launch { + loginState.value = LoginState.Loading + when (val result = ApiClient.verifyTotpLogin(code)) { + is ApiResult.Success -> { + val scope = ApiClient.getTokenScope() + if (scope == TokenScope.FULL) { + _currentUserId.value = ApiClient.getStoredUserId() + _is2faEnabled.value = ApiClient.is2faEnabledLocal() + loginState.value = LoginState.Success + fetchTotpStatus() + observeChannel() + } else { + // token came back but scope is wrong — shouldn't happen + loginState.value = LoginState.Error("Unexpected token scope after verification") + } + } + is ApiResult.HttpError -> { + // stay on TOTP screen but show the error + loginState.value = LoginState.TwoFactorRequired + // use a separate error signal so we don't lose the TOTP state + _totpError.value = result.message + } + is ApiResult.NetworkError -> { + loginState.value = LoginState.TwoFactorRequired + _totpError.value = "Could not reach server: ${result.message}" + } + } + } + } + + fun signup(username: String, email: String, password: String, accessToken: String) { + viewModelScope.launch { + loginState.value = LoginState.Loading + try { + + when (val result = ApiClient.signup(username, email, password, accessToken)) { + is ApiResult.Success -> { + _currentUserId.value = ApiClient.getStoredUserId() + _is2faEnabled.value = ApiClient.is2faEnabledLocal() + loginState.value = LoginState.Success + observeChannel() + } + is ApiResult.HttpError -> { + loginState.value = LoginState.Error(result.message) + } + is ApiResult.NetworkError -> { + loginState.value = LoginState.Error("Could not reach server: ${result.message}") + } + } + } catch (e: Exception) { + Log.e("Chat", "Signup error", e) + loginState.value = LoginState.Error("Signup failed: ${e.localizedMessage}") + } + } + } + + fun logout() { + viewModelScope.launch { + ApiClient.logout() + _currentUserId.value = null + _is2faEnabled.value = false + loginState.value = LoginState.Idle + _messages.value = emptyList() + _channelId.value = null + _currentScreen.value = MainScreen.CHAT + streamJob?.cancel() + } + } + + fun fetchTotpQr() { + viewModelScope.launch { + _totpQr.value = ApiClient.getTotpQr() + } + } + + fun confirmTotp(code: String) { + viewModelScope.launch { + val success = ApiClient.confirmTotp(code) + if (success) { + _is2faEnabled.value = true + ApiClient.set2faEnabledLocal(true) + _totpQr.value = null + } else { + _totpError.value = "Invalid verification code" + } + } + } + + fun fetchTotpStatus() { + viewModelScope.launch { + _is2faEnabled.value = ApiClient.getTotpStatus() + } + } + + fun disableTotp() { + viewModelScope.launch { + when (val result = ApiClient.disableTotp()) { + is ApiResult.Success -> { + _is2faEnabled.value = false + _settingsSuccess.value = "2FA disabled successfully" + } + is ApiResult.HttpError -> { + _settingsError.value = result.message + } + is ApiResult.NetworkError -> { + _settingsError.value = "Network error: ${result.message}" + } + } + } + } + + fun changePassword(old: String, new: String) { + viewModelScope.launch { + _settingsError.value = null + _settingsSuccess.value = null + when (val result = ApiClient.changePassword(old, new)) { + is ApiResult.Success -> { + _settingsSuccess.value = "Password updated" + } + is ApiResult.HttpError -> { + _settingsError.value = result.message + } + is ApiResult.NetworkError -> { + _settingsError.value = "Network error: ${result.message}" + } + } + } + } + + fun updateDisplayName(name: String?) { + viewModelScope.launch { + _settingsError.value = null + _settingsSuccess.value = null + val success = ApiClient.updateDisplayName(name) + if (success) { + _settingsSuccess.value = "Display name updated" + } else { + _settingsError.value = "Failed to update display name" + } + } + } +} + +object TokenScope { + const val FULL = "full"; + const val TOTP_PENDING = "totp_pending"; +} diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/model/LoginRequest.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/model/LoginRequest.kt new file mode 100644 index 0000000..ee3730b --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/model/LoginRequest.kt @@ -0,0 +1,11 @@ +package dev.zxq5.chatapp.android.model + +import kotlinx.serialization.Serializable + +@Serializable +data class LoginRequest( + val username: String, + val password: String +) + + diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/model/LoginResponse.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/model/LoginResponse.kt new file mode 100644 index 0000000..3304cdb --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/model/LoginResponse.kt @@ -0,0 +1,6 @@ +package dev.zxq5.chatapp.android.model + +import kotlinx.serialization.Serializable + +@Serializable +data class LoginResponse(val token: String) \ No newline at end of file diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/model/LoginState.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/model/LoginState.kt new file mode 100644 index 0000000..32f53d6 --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/model/LoginState.kt @@ -0,0 +1,9 @@ +package dev.zxq5.chatapp.android.model + +sealed class LoginState { + object Idle : LoginState() + object Loading : LoginState() + object Success : LoginState() + object TwoFactorRequired : LoginState() + data class Error(val message: String) : LoginState() +} \ No newline at end of file diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/model/Message.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/model/Message.kt new file mode 100644 index 0000000..edd97b8 --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/model/Message.kt @@ -0,0 +1,11 @@ +package dev.zxq5.chatapp.android.model + +import kotlinx.serialization.Serializable + +@Serializable +data class Message( + val user_id: Int, + val display_name: String, + val text: String, + val timestamp: Long +) diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/model/SendMessage.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/model/SendMessage.kt new file mode 100644 index 0000000..34254f7 --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/model/SendMessage.kt @@ -0,0 +1,10 @@ +package dev.zxq5.chatapp.android.model + +import kotlinx.serialization.Serializable + +@Serializable +data class SendMessage( + val user_id: Int, + val text: String, + val timestamp: Long +) diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/model/SignupRequest.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/model/SignupRequest.kt new file mode 100644 index 0000000..7e2e626 --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/model/SignupRequest.kt @@ -0,0 +1,14 @@ +package dev.zxq5.chatapp.android.model + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +@Serializable +data class SignupRequest( + val username: String, + val password: String, + val email: String, + + @SerialName("access_token") + val access_token: String +) diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/ui/components/chat.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/ui/components/chat.kt new file mode 100644 index 0000000..9b53965 --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/ui/components/chat.kt @@ -0,0 +1,435 @@ +package dev.zxq5.chatapp.android.ui.components + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.automirrored.filled.ExitToApp +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Send +import androidx.compose.material.icons.filled.Settings +import androidx.compose.material.icons.outlined.ChatBubbleOutline +import androidx.compose.material.icons.outlined.Settings +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.NavigationBar +import androidx.compose.material3.NavigationBarItem +import androidx.compose.material3.NavigationBarItemDefaults +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.unit.dp +import dev.zxq5.chatapp.android.model.ChatViewModel +import dev.zxq5.chatapp.android.model.MainScreen +import dev.zxq5.chatapp.android.model.Message +import java.text.DateFormat +import java.util.Date + +@Composable +fun ChatScreen(viewModel: ChatViewModel) { + val selectedChannelId by viewModel.channelId.collectAsState() + + if (selectedChannelId == null) { + ChannelListScreen( + viewModel = viewModel, + onChannelSelect = { viewModel.switchChannel(it) } + ) + } else { + MessageScreen( + channelId = selectedChannelId!!, + viewModel = viewModel, + onBack = { viewModel.switchChannel(null) } + ) + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ChannelListScreen(viewModel: ChatViewModel, onChannelSelect: (Int) -> Unit) { + Scaffold( + containerColor = MaterialTheme.colorScheme.background, + topBar = { + Column { + Spacer(Modifier.height(8.dp)) + Text( + "contacts", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f), + modifier = Modifier.padding(horizontal = 20.dp) + ) + TopAppBar( + title = { + Text( + "messages", + style = MaterialTheme.typography.titleLarge, + color = MaterialTheme.colorScheme.onSurface + ) + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = Color.Transparent, + titleContentColor = MaterialTheme.colorScheme.onSurface + ) + ) + Text( + "5 channels · end-to-end encrypted", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.4f), + modifier = Modifier.padding(horizontal = 20.dp, vertical = 2.dp) + ) + Spacer(Modifier.height(12.dp)) + + Row( + modifier = Modifier + .fillMaxWidth() + .background(MaterialTheme.colorScheme.secondary.copy(alpha = 0.2f)) + .padding(horizontal = 20.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Box( + modifier = Modifier + .size(6.dp) + .clip(CircleShape) + .background(MaterialTheme.colorScheme.primary) + ) + Spacer(Modifier.width(10.dp)) + Text( + "global · walkie talkie", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.weight(1f) + ) + Surface( + color = Color.Transparent, + border = border(0.5.dp, MaterialTheme.colorScheme.outlineVariant), + shape = RoundedCornerShape(4.dp) + ) { + Text( + "hold to talk", + modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } + }, + bottomBar = { BottomDock(viewModel) } + ) { padding -> + LazyColumn(modifier = Modifier.padding(padding).fillMaxSize()) { + items(10) { i -> + val id = i + 1 + ChannelItem(id = id, onClick = { onChannelSelect(id) }) + HorizontalDivider( + modifier = Modifier.padding(horizontal = 20.dp), + thickness = 0.5.dp, + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.2f) + ) + } + } + } +} + +@Composable +fun BottomDock(viewModel: ChatViewModel) { + val currentScreen by viewModel.currentScreen.collectAsState() + + NavigationBar( + containerColor = MaterialTheme.colorScheme.background, + tonalElevation = 0.dp, + modifier = Modifier.border(0.5.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.2f), RoundedCornerShape(topStart = 0.dp, topEnd = 0.dp)) + ) { + NavigationBarItem( + selected = currentScreen == MainScreen.CHAT, + onClick = { viewModel.navigateTo(MainScreen.CHAT) }, + icon = { Icon(Icons.Outlined.ChatBubbleOutline, contentDescription = "Chat") }, + label = { Text("chat", style = MaterialTheme.typography.labelSmall) }, + colors = NavigationBarItemDefaults.colors( + selectedIconColor = MaterialTheme.colorScheme.primary, + unselectedIconColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f), + indicatorColor = Color.Transparent + ) + ) + NavigationBarItem( + selected = currentScreen == MainScreen.SETTINGS, + onClick = { viewModel.navigateTo(MainScreen.SETTINGS) }, + icon = { Icon(Icons.Outlined.Settings, contentDescription = "Settings") }, + label = { Text("settings", style = MaterialTheme.typography.labelSmall) }, + colors = NavigationBarItemDefaults.colors( + selectedIconColor = MaterialTheme.colorScheme.primary, + unselectedIconColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f), + indicatorColor = Color.Transparent + ) + ) + } +} + +@Composable +fun ChannelItem(id: Int, onClick: () -> Unit) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .padding(horizontal = 20.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Box( + modifier = Modifier + .size(36.dp) + .clip(CircleShape) + .border(0.5.dp, MaterialTheme.colorScheme.outlineVariant, CircleShape), + contentAlignment = Alignment.Center + ) { + Text( + "C$id", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Spacer(Modifier.width(12.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = "channel $id", + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + text = "tap to join", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f) + ) + } + Text( + "14:22", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.3f) + ) + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun MessageScreen(channelId: Int, viewModel: ChatViewModel, onBack: () -> Unit) { + val messages by viewModel.messages.collectAsState() + val currentUserId by viewModel.currentUserId.collectAsState() + var input by remember { mutableStateOf("") } + val listState = rememberLazyListState() + + LaunchedEffect(messages.size) { + if (messages.isNotEmpty()) { + listState.animateScrollToItem(messages.size - 1) + } + } + + Scaffold( + containerColor = MaterialTheme.colorScheme.background, + topBar = { + TopAppBar( + title = { + Column { + Text( + "channel $channelId", + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + "online", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f) + ) + } + }, + navigationIcon = { + IconButton(onClick = onBack) { + Icon( + Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = "Back", + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = Color.Transparent + ) + ) + } + ) { padding -> + Column(modifier = Modifier.padding(padding).fillMaxSize()) { + LazyColumn( + state = listState, + modifier = Modifier.weight(1f).padding(horizontal = 16.dp), + verticalArrangement = Arrangement.spacedBy(10.dp) + ) { + items(messages) { message -> + MessageBubble(message, currentUserId) + } + item { Spacer(Modifier.height(10.dp)) } + } + + Row( + modifier = Modifier + .fillMaxWidth() + .height(IntrinsicSize.Min) + .padding(horizontal = 14.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically + ) { + IconButton( + onClick = { /* add action */ }, + modifier = Modifier + .size(36.dp) + .border(0.5.dp, MaterialTheme.colorScheme.outlineVariant, CircleShape) + ) { + Icon( + Icons.Default.Add, + contentDescription = "Add", + modifier = Modifier.size(16.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + Spacer(Modifier.width(8.dp)) + + Box( + modifier = Modifier + .weight(1f) + .fillMaxHeight() + .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f), RoundedCornerShape(20.dp)) + .border(0.5.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(20.dp)) + .padding(horizontal = 14.dp), + contentAlignment = Alignment.CenterStart + ) { + if (input.isEmpty()) { + Text( + "message", + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f) + ) + } + BasicTextField( + value = input, + onValueChange = { input = it }, + modifier = Modifier.fillMaxWidth(), + textStyle = MaterialTheme.typography.bodyLarge.copy(color = MaterialTheme.colorScheme.onSurface), + cursorBrush = SolidColor(MaterialTheme.colorScheme.primary), + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send), + keyboardActions = KeyboardActions(onSend = { + if (input.isNotBlank()) { + viewModel.sendMessage(input) + input = "" + } + }) + ) + } + + if (input.isNotBlank()) { + Spacer(Modifier.width(8.dp)) + IconButton( + onClick = { + viewModel.sendMessage(input) + input = "" + }, + modifier = Modifier + .size(36.dp) + .background(MaterialTheme.colorScheme.primary, CircleShape) + ) { + Icon( + Icons.Default.Send, + contentDescription = "Send", + modifier = Modifier.size(16.dp), + tint = MaterialTheme.colorScheme.onPrimary + ) + } + } + } + } + } +} + +@Composable +fun MessageBubble(message: Message, currentUserId: Int?) { + val time = remember(message.timestamp) { + DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(message.timestamp)).lowercase() + } + + val isMe = currentUserId != null && message.user_id == currentUserId + + Column( + modifier = Modifier.fillMaxWidth(), + horizontalAlignment = if (isMe) Alignment.End else Alignment.Start + ) { + Surface( + color = if (isMe) MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f) else MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.2f), + shape = RoundedCornerShape( + topStart = 14.dp, + topEnd = 14.dp, + bottomStart = if (isMe) 14.dp else 4.dp, + bottomEnd = if (isMe) 4.dp else 14.dp + ), + border = border(0.5.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)) + ) { + Column(modifier = Modifier.padding(horizontal = 11.dp, vertical = 8.dp)) { + if (!isMe) { + Text( + message.display_name.lowercase(), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary.copy(alpha = 0.7f), + modifier = Modifier.padding(bottom = 2.dp) + ) + } + Text( + text = message.text, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.9f) + ) + } + } + Text( + text = time, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.3f), + modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp) + ) + } +} + +private fun border(width: androidx.compose.ui.unit.Dp, color: Color) = + androidx.compose.foundation.BorderStroke(width, color) diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/ui/components/login.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/ui/components/login.kt new file mode 100644 index 0000000..90e0286 --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/ui/components/login.kt @@ -0,0 +1,318 @@ +package dev.zxq5.chatapp.android.ui.components + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.OutlinedTextFieldDefaults +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import dev.zxq5.chatapp.android.model.AuthMode +import dev.zxq5.chatapp.android.model.ChatViewModel +import dev.zxq5.chatapp.android.model.LoginState + +@Composable +fun AuthScreen(viewModel: ChatViewModel, onSuccess: () -> Unit) { + val loginState by viewModel.loginState.collectAsState() + val authMode by viewModel.authMode.collectAsState() + val totpError by viewModel.totpError.collectAsState() + + var username by remember { mutableStateOf("") } + var email by remember { mutableStateOf("") } + var password by remember { mutableStateOf("") } + var confirmPassword by remember { mutableStateOf("") } + var accessToken by remember { mutableStateOf("") } + var localError by remember { mutableStateOf(null) } + + + + LaunchedEffect(loginState) { + if (loginState is LoginState.Success) onSuccess() + } + + LaunchedEffect(authMode) { + localError = null + } + + if (loginState is LoginState.TwoFactorRequired || + (loginState is LoginState.Loading && totpError != null)) { + TwoFactorLoginScreen( + onVerify = { code -> viewModel.verifyLogin2fa(code) }, + onBack = { + viewModel.clearTotpError() + viewModel.setAuthMode(AuthMode.LOGIN) + }, + isLoading = loginState is LoginState.Loading, + error = totpError + ) + return + } + + Column( + modifier = Modifier + .fillMaxSize() + .background(MaterialTheme.colorScheme.background) + .padding(24.dp) + .verticalScroll(rememberScrollState()), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Spacer(Modifier.height(40.dp)) + + Text( + text = "messenger", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(bottom = 8.dp) + ) + + Text( + text = if (authMode == AuthMode.LOGIN) "welcome back" else "create account", + style = MaterialTheme.typography.headlineMedium, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.padding(bottom = 48.dp) + ) + + Column( + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + TextField( + value = username, + onValueChange = { username = it }, + label = "username" + ) + + if (authMode == AuthMode.SIGNUP) { + TextField( + value = email, + onValueChange = { email = it }, + label = "email" + ) + } + + TextField( + value = password, + onValueChange = { password = it }, + label = "password", + isPassword = true + ) + + if (authMode == AuthMode.SIGNUP) { + TextField( + value = confirmPassword, + onValueChange = { confirmPassword = it }, + label = "confirm password", + isPassword = true + ) + TextField( + value = accessToken, + onValueChange = { accessToken = it }, + label = "access token" + ) + } + } + + Spacer(Modifier.height(32.dp)) + + Button( + onClick = { + localError = null + if (authMode == AuthMode.LOGIN) { + if (username.isBlank() || password.isBlank()) { + localError = "fill all fields" + return@Button + } + viewModel.login(username, password) + } else { + if (username.isBlank() || email.isBlank() || password.isBlank() || accessToken.isBlank()) { + localError = "fill all fields" + return@Button + } + if (password != confirmPassword) { + localError = "passwords mismatch" + return@Button + } + viewModel.signup(username, email, password, accessToken) + } + }, + enabled = loginState !is LoginState.Loading, + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(8.dp), + colors = ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.primary, + contentColor = MaterialTheme.colorScheme.onPrimary, + disabledContainerColor = MaterialTheme.colorScheme.secondary + ) + ) { + if (loginState is LoginState.Loading) { + CircularProgressIndicator(modifier = Modifier.size(16.dp), color = MaterialTheme.colorScheme.onPrimary, strokeWidth = 2.dp) + } else { + Text( + if (authMode == AuthMode.LOGIN) "login" else "sign up", + style = MaterialTheme.typography.bodyLarge + ) + } + } + + val displayError = localError ?: (loginState as? LoginState.Error)?.message + if (displayError != null) { + Text( + text = displayError.lowercase(), + style = MaterialTheme.typography.labelSmall, + color = Color.Red, + modifier = Modifier.padding(top = 16.dp) + ) + } + + Spacer(Modifier.height(16.dp)) + + TextButton( + onClick = { + viewModel.setAuthMode(if (authMode == AuthMode.LOGIN) AuthMode.SIGNUP else AuthMode.LOGIN) + } + ) { + Text( + if (authMode == AuthMode.LOGIN) "no account? sign up" + else "have account? login", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } +} + +@Composable +fun TwoFactorLoginScreen( + onVerify: (String) -> Unit, + onBack: () -> Unit, + isLoading: Boolean, + error: String? +) { + var code by remember { mutableStateOf("") } + + Column( + modifier = Modifier + .fillMaxSize() + .background(MaterialTheme.colorScheme.background) + .padding(24.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically + ) { + IconButton(onClick = onBack) { + Icon( + Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = "Back", + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Text( + "security verification", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + Spacer(Modifier.height(80.dp)) + + Text( + "two-factor auth", + style = MaterialTheme.typography.headlineMedium, + color = MaterialTheme.colorScheme.onSurface + ) + + Text( + "enter the 6-digit code from your app", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f), + modifier = Modifier.padding(top = 8.dp, bottom = 48.dp) + ) + + OutlinedTextField( + value = code, + onValueChange = { if (it.length <= 6) code = it }, + placeholder = { Text("000000", color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.3f)) }, + modifier = Modifier.width(200.dp), + textStyle = MaterialTheme.typography.headlineMedium.copy( + textAlign = TextAlign.Center, + letterSpacing = 8.sp + ), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + shape = RoundedCornerShape(8.dp), + colors = OutlinedTextFieldDefaults.colors( + focusedBorderColor = MaterialTheme.colorScheme.primary, + unfocusedBorderColor = MaterialTheme.colorScheme.outlineVariant, + focusedContainerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.1f), + unfocusedContainerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.1f) + ), + singleLine = true + ) + + if (error != null) { + Text( + text = error.lowercase(), + style = MaterialTheme.typography.labelSmall, + color = Color.Red, + modifier = Modifier.padding(top = 12.dp) + ) + } else { + Spacer(Modifier.height(12.dp)) // keep layout stable when no error + } + + Spacer(Modifier.height(36.dp)) + + Button( + onClick = { if (code.length == 6) onVerify(code) }, + enabled = code.length == 6 && !isLoading, + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(8.dp), + colors = ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.primary, + contentColor = MaterialTheme.colorScheme.onPrimary + ) + ) { + if (isLoading) { + CircularProgressIndicator(modifier = Modifier.size(16.dp), color = MaterialTheme.colorScheme.onPrimary, strokeWidth = 2.dp) + } else { + Text("verify", style = MaterialTheme.typography.bodyLarge) + } + } + } +} + diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/ui/components/settings.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/ui/components/settings.kt new file mode 100644 index 0000000..bb70398 --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/ui/components/settings.kt @@ -0,0 +1,368 @@ +package dev.zxq5.chatapp.android.ui.components + +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +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.Check +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.OutlinedTextFieldDefaults +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Switch +import androidx.compose.material3.SwitchDefaults +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import dev.zxq5.chatapp.android.model.ChatViewModel +import dev.zxq5.chatapp.android.model.MainScreen +import android.util.Base64 +import android.graphics.BitmapFactory +import androidx.compose.runtime.LaunchedEffect + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SettingsScreen(viewModel: ChatViewModel) { + val is2faEnabled by viewModel.is2faEnabled.collectAsState() + val totpQr by viewModel.totpQr.collectAsState() + val settingsError by viewModel.settingsError.collectAsState() + val settingsSuccess by viewModel.settingsSuccess.collectAsState() + + var show2faSetup by remember { mutableStateOf(false) } + var displayName by remember { mutableStateOf("") } + var oldPassword by remember { mutableStateOf("") } + var newPassword by remember { mutableStateOf("") } + + LaunchedEffect(Unit) { + viewModel.clearSettingsMessages() + viewModel.fetchTotpStatus() + } + + Scaffold( + containerColor = MaterialTheme.colorScheme.background, + topBar = { + TopAppBar( + title = { + Text( + "settings", + style = MaterialTheme.typography.titleLarge, + color = MaterialTheme.colorScheme.onSurface + ) + }, + navigationIcon = { + IconButton(onClick = { viewModel.navigateTo(MainScreen.CHAT) }) { + Icon( + Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = "Back", + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = Color.Transparent + ) + ) + } + ) { padding -> + Column( + modifier = Modifier + .padding(padding) + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(20.dp), + verticalArrangement = Arrangement.spacedBy(24.dp) + ) { + if (settingsError != null) { + Text(settingsError!!, color = Color.Red, style = MaterialTheme.typography.bodySmall) + } + if (settingsSuccess != null) { + Text(settingsSuccess!!, color = Color.Green, style = MaterialTheme.typography.bodySmall) + } + + // Profile Section + Column { + Text( + "profile", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f), + modifier = Modifier.padding(bottom = 12.dp) + ) + + OutlinedTextField( + value = displayName, + onValueChange = { displayName = it }, + label = { Text("display name") }, + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(8.dp), + trailingIcon = { + IconButton(onClick = { viewModel.updateDisplayName(displayName.ifBlank { null }) }) { + Icon(Icons.Default.Check, "Save") + } + } + ) + } + + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.2f)) + + // Security Section + Column { + Text( + "account security", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f), + modifier = Modifier.padding(bottom = 12.dp) + ) + + Row( + modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + "two-factor authentication", + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + if (is2faEnabled) "enabled" else "disabled", + style = MaterialTheme.typography.labelSmall, + color = if (is2faEnabled) Color.Green.copy(alpha = 0.7f) else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f) + ) + } + + if (!is2faEnabled) { + Button( + onClick = { + show2faSetup = true + viewModel.fetchTotpQr() + }, + shape = RoundedCornerShape(8.dp), + colors = ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f), + contentColor = MaterialTheme.colorScheme.onSurface + ), + modifier = Modifier.height(32.dp) + ) { + Text("setup", style = MaterialTheme.typography.labelSmall) + } + } else { + Button( + onClick = { viewModel.disableTotp() }, + shape = RoundedCornerShape(8.dp), + colors = ButtonDefaults.buttonColors( + containerColor = Color.Red.copy(alpha = 0.1f), + contentColor = Color.Red + ), + modifier = Modifier.height(32.dp) + ) { + Text("disable", style = MaterialTheme.typography.labelSmall) + } + } + } + + if (show2faSetup && !is2faEnabled) { + Spacer(Modifier.height(16.dp)) + TwoFactorSetup( + qrCodeBase64 = totpQr?.qr_code, + onConfirm = { code -> + viewModel.confirmTotp(code) + }, + onCancel = { show2faSetup = false } + ) + } + + Spacer(Modifier.height(16.dp)) + + Text("change password", style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(bottom = 8.dp)) + OutlinedTextField( + value = oldPassword, + onValueChange = { oldPassword = it }, + label = { Text("old password") }, + visualTransformation = PasswordVisualTransformation(), + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(8.dp) + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = newPassword, + onValueChange = { newPassword = it }, + label = { Text("new password") }, + visualTransformation = PasswordVisualTransformation(), + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(8.dp) + ) + Spacer(Modifier.height(12.dp)) + Button( + onClick = { + viewModel.changePassword(oldPassword, newPassword) + oldPassword = "" + newPassword = "" + }, + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(8.dp), + enabled = oldPassword.isNotEmpty() && newPassword.isNotEmpty() + ) { + Text("update password") + } + } + + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.2f)) + + // Application Section + Column { + Text( + "application", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f), + modifier = Modifier.padding(bottom = 12.dp) + ) + + Button( + onClick = { viewModel.logout() }, + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(8.dp), + colors = ButtonDefaults.buttonColors( + containerColor = Color.Red.copy(alpha = 0.1f), + contentColor = Color.Red + ) + ) { + Text("logout", style = MaterialTheme.typography.bodyLarge) + } + } + } + } +} + +@Composable +fun TwoFactorSetup( + qrCodeBase64: String?, + onConfirm: (String) -> Unit, + onCancel: () -> Unit +) { + var code by remember { mutableStateOf("") } + + Column( + modifier = Modifier + .fillMaxWidth() + .border(0.5.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(12.dp)) + .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.1f), RoundedCornerShape(12.dp)) + .padding(20.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Text( + "scan qr code", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + + Spacer(Modifier.height(16.dp)) + + if (qrCodeBase64 != null) { + val bitmap = remember(qrCodeBase64) { + val base64Data = qrCodeBase64.substringAfter("base64,") + val decodedString = Base64.decode(base64Data, Base64.DEFAULT) + BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size) + } + + bitmap?.let { + Image( + bitmap = it.asImageBitmap(), + contentDescription = "QR Code", + modifier = Modifier + .size(180.dp) + .clip(RoundedCornerShape(8.dp)) + .background(Color.White) // QR codes usually need white background + .padding(8.dp) + ) + } + } else { + Box( + modifier = Modifier.size(180.dp), + contentAlignment = Alignment.Center + ) { + CircularProgressIndicator(color = MaterialTheme.colorScheme.primary) + } + } + + Spacer(Modifier.height(24.dp)) + + OutlinedTextField( + value = code, + onValueChange = { if (it.length <= 6) code = it }, + placeholder = { Text("000000", color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.3f)) }, + modifier = Modifier.width(150.dp), + textStyle = MaterialTheme.typography.headlineMedium.copy( + textAlign = androidx.compose.ui.text.style.TextAlign.Center, + letterSpacing = 4.sp + ), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + shape = RoundedCornerShape(8.dp), + colors = OutlinedTextFieldDefaults.colors( + focusedBorderColor = MaterialTheme.colorScheme.primary, + unfocusedBorderColor = MaterialTheme.colorScheme.outlineVariant + ) + ) + + Spacer(Modifier.height(24.dp)) + + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Button( + onClick = onCancel, + modifier = Modifier.weight(1f), + shape = RoundedCornerShape(8.dp), + colors = ButtonDefaults.buttonColors(containerColor = Color.Transparent, contentColor = MaterialTheme.colorScheme.onSurfaceVariant) + ) { + Text("cancel", style = MaterialTheme.typography.labelSmall) + } + + Button( + onClick = { if (code.length == 6) onConfirm(code) }, + enabled = code.length == 6, + modifier = Modifier.weight(1f), + shape = RoundedCornerShape(8.dp) + ) { + Text("confirm", style = MaterialTheme.typography.labelSmall) + } + } + } +} diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/ui/components/textfield.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/ui/components/textfield.kt new file mode 100644 index 0000000..349cfa3 --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/ui/components/textfield.kt @@ -0,0 +1,45 @@ +package dev.zxq5.chatapp.android.ui.components + +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.OutlinedTextFieldDefaults +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.unit.dp + +@Composable +fun TextField( + value: String, + onValueChange: (String) -> Unit, + label: String, + isPassword: Boolean = false +) { + OutlinedTextField( + value = value, + onValueChange = onValueChange, + placeholder = { + Text( + label, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f) + ) + }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + textStyle = MaterialTheme.typography.bodyLarge, + visualTransformation = if (isPassword) PasswordVisualTransformation() else androidx.compose.ui.text.input.VisualTransformation.None, + shape = RoundedCornerShape(8.dp), + colors = OutlinedTextFieldDefaults.colors( + focusedContainerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f), + unfocusedContainerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f), + focusedBorderColor = MaterialTheme.colorScheme.outlineVariant, + unfocusedBorderColor = MaterialTheme.colorScheme.outline, + focusedTextColor = MaterialTheme.colorScheme.onSurface, + unfocusedTextColor = MaterialTheme.colorScheme.onSurface + ) + ) +} diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/ui/theme/Color.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/ui/theme/Color.kt new file mode 100644 index 0000000..fec32eb --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/ui/theme/Color.kt @@ -0,0 +1,20 @@ +package dev.zxq5.chatapp.android.ui.theme + +import androidx.compose.ui.graphics.Color + +val Black = Color(0xFF0A0A0A) +val DarkGrey = Color(0xFF0D0D0D) +val Grey = Color(0xFF141414) +val LightGrey = Color(0xFF1E1E1E) +val White = Color(0xFFE8E8E8) + +val TextPrimary = Color(0xFFE8E8E8) +val TextSecondary = Color(0xFF888888) +val TextTertiary = Color(0xFF555555) +val TextMuted = Color(0xFF333333) + +val Border = Color(0xFF1A1A1A) +val BorderLight = Color(0xFF222222) + +val Red = Color(0xFFFF0000) +val Surface = Color(0xFF111111) diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/ui/theme/Theme.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/ui/theme/Theme.kt new file mode 100644 index 0000000..363f84a --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/ui/theme/Theme.kt @@ -0,0 +1,48 @@ +package dev.zxq5.chatapp.android.ui.theme + +import android.app.Activity +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.SideEffect +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.platform.LocalView +import androidx.core.view.WindowCompat + +private val DarkColorScheme = darkColorScheme( + primary = White, + onPrimary = Black, + secondary = LightGrey, + onSecondary = White, + tertiary = Grey, + background = Black, + onBackground = White, + surface = Black, + onSurface = White, + surfaceVariant = Grey, + onSurfaceVariant = TextSecondary, + outline = Border, + outlineVariant = BorderLight +) + +@Composable +fun ChatappTheme( + darkTheme: Boolean = true, // Force dark theme for Nothing style + content: @Composable () -> Unit +) { + val colorScheme = DarkColorScheme + val view = LocalView.current + if (!view.isInEditMode) { + SideEffect { + val window = (view.context as Activity).window + window.statusBarColor = Black.toArgb() + WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = false + } + } + + MaterialTheme( + colorScheme = colorScheme, + typography = Typography, + content = content + ) +} diff --git a/android/app/src/main/java/dev/zxq5/chatapp/android/ui/theme/Type.kt b/android/app/src/main/java/dev/zxq5/chatapp/android/ui/theme/Type.kt new file mode 100644 index 0000000..1726004 --- /dev/null +++ b/android/app/src/main/java/dev/zxq5/chatapp/android/ui/theme/Type.kt @@ -0,0 +1,37 @@ +package dev.zxq5.chatapp.android.ui.theme + +import androidx.compose.material3.Typography +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.sp + +val Typography = Typography( + bodyLarge = TextStyle( + fontFamily = FontFamily.Monospace, + fontWeight = FontWeight.Normal, + fontSize = 14.sp, + lineHeight = 20.sp, + letterSpacing = 0.02.sp + ), + titleLarge = TextStyle( + fontFamily = FontFamily.Monospace, + fontWeight = FontWeight.Medium, + fontSize = 20.sp, + lineHeight = 28.sp, + letterSpacing = (-0.02).sp + ), + labelSmall = TextStyle( + fontFamily = FontFamily.Monospace, + fontWeight = FontWeight.Medium, + fontSize = 10.sp, + lineHeight = 14.sp, + letterSpacing = 0.05.sp + ), + headlineMedium = TextStyle( + fontFamily = FontFamily.Monospace, + fontWeight = FontWeight.Normal, + fontSize = 22.sp, + letterSpacing = (-0.02).sp + ) +) diff --git a/android/app/src/main/res/drawable/ic_launcher_background.xml b/android/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..07d5da9 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/android/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..2b068d1 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/mipmap-anydpi/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi/ic_launcher.xml new file mode 100644 index 0000000..6f3b755 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml b/android/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml new file mode 100644 index 0000000..6f3b755 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 0000000..c209e78 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 0000000..b2dfe3d Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 0000000..4f0f1d6 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 0000000..62b611d Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 0000000..948a307 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..1b9a695 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 0000000..28d4b77 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..9287f50 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 0000000..aa7d642 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..9126ae3 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/nothing_messenger_mockup.html b/android/app/src/main/res/nothing_messenger_mockup.html new file mode 100644 index 0000000..f3fc079 --- /dev/null +++ b/android/app/src/main/res/nothing_messenger_mockup.html @@ -0,0 +1,765 @@ + + +
+ + +
+
+
09:41▪▪▪
+
contacts
+
+
messages
+
5 contacts · end-to-end encrypted
+
+ +
+
+
flat · walkie talkie
+
hold to talk
+
+ +
+
+
JM
+
+
jamie
+
voice message · 0:12
+
+
+
now
+
+
+
+
+
RP
+
+
climbing crew
+
priya: who's in sat?
+
+
+
14:22
+
+
+
+
+
AL
+
+
alex
+
sent a file
+
+
+
tue
+
+
+
+
SC
+
+
sam
+
yeah let's do it
+
+
+
mon
+
+
+ +
+
+
add contact
+
tap phones · or share a link
+
+
+ +
+ + + + +
+
+
+ + +
+
+
09:41▪▪▪
+
chat
+
+
+
+
climbing crew
+
3 members · e2e encrypted
+
+
+ + + +
+
+ +
+
+
who's in for saturday?
+
priya · 14:20
+
+ +
+
climbing saturday
+
+
morning
+
+
70%
+
+
+
afternoon
+
+
20%
+
+
+
can't make it
+
+
10%
+
+
+ +
+
morning works, i'll book the wall
+
14:31
+
+
+
+1 2
+
+ +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
0:12
+
+
jamie · 14:38
+
+ +
+
+ +
+
message
+
+ +
+
+ +
+
+
+
+ + +
+
+
09:41▪▪▪
+
shared space
+
+
climbing crew
+
space
+
3 members
+
+ +
+
files
+
docs
+
links
+
+ +
+
+
jpg
+
+
wall-beta-map.jpg
+
priya · 3 days ago
+
+
2.1mb
+
+
+
pdf
+
+
membership-discount.pdf
+
jamie · 1 week ago
+
+
84kb
+
+
+
mp4
+
+
dyno-attempt.mp4
+
you · 2 weeks ago
+
+
18mb
+
+ +
+ +
+
+
+
+
+
+
+
+
gear checklist
+
shared doc · edited yesterday
+
+
+ +
+
+ upload file
+
+ new doc
+
+ +
+
storage used
+
+
+
+
+
34%
+
+
+
+ +
+ + + + +
+
+
+ +
\ No newline at end of file diff --git a/android/app/src/main/res/nothing_table_ui.html b/android/app/src/main/res/nothing_table_ui.html new file mode 100644 index 0000000..86f3719 --- /dev/null +++ b/android/app/src/main/res/nothing_table_ui.html @@ -0,0 +1,627 @@ + + +
+ + +
+
+
09:41▪▪▪
+
shared space · tables
+
+
climbing crew
+
space
+
3 members
+
+
+
files
+
docs
+
tables
+
links
+
+ +
+
+ +
+
+
availability
+
edited today
+
+
+ + + + + + + + + + + + + + + +
namesatsunnotes
priyamorning
jamie
youam only
+
+
+ +
+
+
gear to bring
+
edited 3 days ago
+
+
+ + + + + + + + + + + + + + +
itemwhopacked
ropejamie
crash padpriya
first aidyou
+
+
+ + + +
+
+ +
+ + + + +
+
+
+ + +
+
+
09:41▪▪▪
+
table view
+ +
+
+
climbing crew · space
+
availability
+
+
+
filter
+
+ col
+
+
+ +
+
all rows
+
sat only
+
available
+
missing
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
nametxt
satbool
sunbool
monbool
notestxt
priyamorning only
jamie
youam only
+ add row
+
+ +
+
3 rows · 5 columns
+
synced · e2e
+
+ +
+ + + + +
+
+
+ + +
+
+
09:41▪▪▪
+
new table
+ +
+
climbing crew · space
+
new table
+
define columns · start typing
+
+ +
+ +
+
table name
+
expenses
+
+ +
+
start from template
+
+
availability
+
shopping list
+
expenses
+
tasks
+
blank
+
+
+ +
+
columns
+
+
+
+ + +
+
+
+ + +
+
+
+ + +
+
+
+ + +
+
+ + + add column +
+
+
+ + + +
+
+
+ +
\ No newline at end of file diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..f8c6127 --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..6c72cec --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + Chatapp + \ No newline at end of file diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..5c0fe13 --- /dev/null +++ b/android/app/src/main/res/values/themes.xml @@ -0,0 +1,5 @@ + + + +