diff --git a/app/build.gradle b/app/build.gradle index 4b489df7..2aa53dd0 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -126,6 +126,9 @@ dependencies { // In-app Updates implementation libs.play.app.update implementation libs.play.app.update.ktx + + // Barcode rendering + implementation libs.zxing.core } protobuf { diff --git a/app/src/main/java/com/cornellappdev/android/eatery/data/NetworkingApi.kt b/app/src/main/java/com/cornellappdev/android/eatery/data/NetworkingApi.kt index 81566a69..e526bcb7 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/data/NetworkingApi.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/data/NetworkingApi.kt @@ -17,6 +17,7 @@ import com.cornellappdev.android.eatery.data.models.NotificationIds import com.cornellappdev.android.eatery.data.models.RefreshRequest import com.cornellappdev.android.eatery.data.models.ReportSendBody import com.cornellappdev.android.eatery.data.models.SessionID +import com.cornellappdev.android.eatery.data.models.UserProfileResponse import com.cornellappdev.android.eatery.data.models.UserSettings import com.cornellappdev.android.eatery.data.models.UserSettingsUpdate import retrofit2.http.Body @@ -122,6 +123,12 @@ interface NetworkApi { @Body sessionId: SessionID ): BarcodeResponse + /** The user's name, email, and photo. Never cache or log the response. */ + @POST("/users/get-profile") + suspend fun getProfile( + @Body sessionId: SessionID + ): UserProfileResponse + @GET("/users/favorites/matches") suspend fun getFavoriteMatches(): List } \ No newline at end of file diff --git a/app/src/main/java/com/cornellappdev/android/eatery/data/models/UserProfile.kt b/app/src/main/java/com/cornellappdev/android/eatery/data/models/UserProfile.kt new file mode 100644 index 00000000..7cdfcfed --- /dev/null +++ b/app/src/main/java/com/cornellappdev/android/eatery/data/models/UserProfile.kt @@ -0,0 +1,57 @@ +package com.cornellappdev.android.eatery.data.models + +import android.graphics.BitmapFactory +import android.util.Base64 +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asImageBitmap +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass + +/** + * Basic identity info for the logged-in user, displayed on the Account page. + * Any field may be null when the backend doesn't provide it. + * + * Held in memory only: the backend asks that profile data not be cached or logged. + */ +data class UserProfile( + val name: String? = null, + val email: String? = null, + val photo: ImageBitmap? = null, +) + +/** Response body of `POST /users/get-profile`. Every field may be null. */ +@JsonClass(generateAdapter = true) +data class UserProfileResponse( + @Json(name = "firstName") val firstName: String? = null, + @Json(name = "middleName") val middleName: String? = null, + @Json(name = "lastName") val lastName: String? = null, + @Json(name = "email") val email: String? = null, + @Json(name = "photo") val photo: ProfilePhoto? = null, +) + +/** A profile photo as base64-encoded image bytes of type [mimeType] (e.g. `image/jpeg`). */ +@JsonClass(generateAdapter = true) +data class ProfilePhoto( + @Json(name = "mimeType") val mimeType: String? = null, + @Json(name = "data") val data: String? = null, +) + +/** + * Converts the backend response into a [UserProfile], joining the name parts and decoding + * the photo. A photo that fails to decode is dropped rather than failing the whole profile. + */ +fun UserProfileResponse.toUserProfile(): UserProfile = UserProfile( + name = listOf(firstName, middleName, lastName) + .filterNot { it.isNullOrBlank() } + .joinToString(" ") + .ifEmpty { null }, + email = email?.takeIf { it.isNotBlank() }, + photo = photo?.toImageBitmap(), +) + +private fun ProfilePhoto.toImageBitmap(): ImageBitmap? { + if (mimeType?.startsWith("image/") == false) return null + val bytes = runCatching { Base64.decode(data ?: return null, Base64.DEFAULT) } + .getOrNull() ?: return null + return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)?.asImageBitmap() +} diff --git a/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/GETAccountRepository.kt b/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/GETAccountRepository.kt index d44e0a53..91d00e6c 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/GETAccountRepository.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/GETAccountRepository.kt @@ -7,6 +7,7 @@ import com.cornellappdev.android.eatery.data.models.LoginRequest import com.cornellappdev.android.eatery.data.models.Result import com.cornellappdev.android.eatery.data.models.SessionID import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.firstOrNull import javax.inject.Inject import javax.inject.Singleton @@ -77,7 +78,14 @@ class GETAccountRepository @Inject constructor( * Null if they haven't been fetched for the current GET account. */ suspend fun getCachedBarcodeCredentials(): BarcodeCredentials? = - userPreferencesRepository.barcodeCredentialsFlow.firstOrNull() + barcodeCredentialsFlow.firstOrNull() + + /** + * Emits the cached barcode credentials whenever they change, or null when none are cached + * for the current GET account. Works offline. + */ + val barcodeCredentialsFlow: Flow = + userPreferencesRepository.barcodeCredentialsFlow suspend fun clearBarcodeData() = userPreferencesRepository.clearBarcodeData() diff --git a/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/UserRepository.kt b/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/UserRepository.kt index bc946b4f..9f74431d 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/UserRepository.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/data/repositories/UserRepository.kt @@ -10,13 +10,20 @@ import com.cornellappdev.android.eatery.data.models.Result import com.cornellappdev.android.eatery.data.models.SessionID import com.cornellappdev.android.eatery.data.models.Transaction import com.cornellappdev.android.eatery.data.models.User +import com.cornellappdev.android.eatery.data.models.UserProfile import com.cornellappdev.android.eatery.data.models.toTransactionAccountType +import com.cornellappdev.android.eatery.data.models.toUserProfile +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.update +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import retrofit2.HttpException import java.time.LocalDateTime import java.time.ZonedDateTime import java.time.format.DateTimeFormatter @@ -55,6 +62,17 @@ class UserRepository @Inject constructor( /** Expose whether a user is currently logged in. Delegates to UserPreferencesRepository. */ val isLoggedInFlow: Flow = userPreferencesRepository.isLoggedInFlow + private val _userProfile: MutableStateFlow = MutableStateFlow(UserProfile()) + + /** + * The logged-in user's name, email, and profile picture. Kept in memory only, since the + * backend asks that profile data not be cached. + */ + val userProfileFlow: StateFlow = _userProfile.asStateFlow() + + /** Makes [getProfile]'s session check and write atomic with [logout]. */ + private val profileMutex = Mutex() + private val useLocalFavorites = BuildConfig.USE_LOCAL_FAVORITES suspend fun updateFavorites(): Result { @@ -205,6 +223,37 @@ class UserRepository @Inject constructor( financials } + /** + * Fetches the user's name, email, and photo. If the GET session has expired (401), gets a + * new session with the saved PIN and tries once more, like [getFinancials]. + * + * The profile is dropped if the user logged out or linked another account while the request + * was in flight, so a late response can't show the old account's profile, like + * [GETAccountRepository.refreshBarcodeData]. + */ + suspend fun getProfile(): Result = resultOfNetworkCall { + var sessionId = getAccountRepository.getSessionId() + val response = try { + networkApi.getProfile(sessionId = SessionID(sessionId)) + } catch (e: HttpException) { + if (e.code() != 401) throw e + val pin = getAccountRepository.getPin() ?: throw e + val refreshResult = getAccountRepository.refreshLogin(pin = pin) + if (refreshResult is Result.Error) throw IllegalStateException("refreshLogin failed") + sessionId = getAccountRepository.getSessionId() + networkApi.getProfile(sessionId = SessionID(sessionId)) + } + val profile = withContext(Dispatchers.Default) { response.toUserProfile() } + // Under the lock, logout either already cleared the session, so the check fails, or + // hasn't started, so it resets the profile after this write. + profileMutex.withLock { + if (!sessionId.isNullOrEmpty() && getAccountRepository.getSessionId() == sessionId) { + _userProfile.value = profile + } + } + profile + } + private fun String.toLocalDateTime(): LocalDateTime? { val inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX") return runCatching { @@ -215,11 +264,12 @@ class UserRepository @Inject constructor( }.getOrNull() } - suspend fun logout() { + suspend fun logout() = profileMutex.withLock { _loadedUser.value = null getAccountRepository.clearSessionId() getAccountRepository.clearBarcodeData() getAccountRepository.setIsLoggedIn(false) + _userProfile.value = UserProfile() } suspend fun hasOnboarded(): Boolean = diff --git a/app/src/main/java/com/cornellappdev/android/eatery/di/NetworkingModule.kt b/app/src/main/java/com/cornellappdev/android/eatery/di/NetworkingModule.kt index 24aad3bd..ea19e7aa 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/di/NetworkingModule.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/di/NetworkingModule.kt @@ -28,8 +28,11 @@ import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object NetworkModule { - /** Paths whose bodies hold payment credentials, so only the method, URL and status are logged. */ - private val CREDENTIAL_PATHS = setOf("/financials/barcode") + /** + * Paths whose bodies hold payment credentials or personal info, so only the method, URL and + * status are logged. + */ + private val CREDENTIAL_PATHS = setOf("/financials/barcode", "/users/get-profile") @Singleton @Provides diff --git a/app/src/main/java/com/cornellappdev/android/eatery/ui/components/login/AccountPage.kt b/app/src/main/java/com/cornellappdev/android/eatery/ui/components/login/AccountPage.kt index 9bc777fa..5cb1f6e5 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/ui/components/login/AccountPage.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/ui/components/login/AccountPage.kt @@ -2,14 +2,18 @@ package com.cornellappdev.android.eatery.ui.components.login import androidx.annotation.StringRes import androidx.compose.animation.AnimatedContent +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.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBarsPadding @@ -22,6 +26,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.KeyboardArrowDown +import androidx.compose.material.icons.outlined.QrCodeScanner import androidx.compose.material.icons.outlined.Settings import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults @@ -38,29 +43,45 @@ import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope 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.FilterQuality +import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.layout.layout +import androidx.compose.ui.res.imageResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.vectorResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.cornellappdev.android.eatery.R import com.cornellappdev.android.eatery.data.models.AccountBalances import com.cornellappdev.android.eatery.data.models.MealSwipePlan import com.cornellappdev.android.eatery.data.models.TransactionAccountType +import com.cornellappdev.android.eatery.data.models.UserProfile import com.cornellappdev.android.eatery.ui.components.general.SearchBar import com.cornellappdev.android.eatery.ui.components.home.BottomSheetContent import com.cornellappdev.android.eatery.ui.theme.EateryBlueTypography import com.cornellappdev.android.eatery.ui.theme.currentColors +import com.cornellappdev.android.eatery.ui.viewmodels.state.BarcodeUiState import com.cornellappdev.android.eatery.ui.viewmodels.state.DisplayTransaction import com.cornellappdev.android.eatery.util.DualModePreview import com.cornellappdev.android.eatery.util.EateryPreview +import com.cornellappdev.android.eatery.util.Pdf417Encoder +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.launch import kotlin.math.abs @OptIn( @@ -74,10 +95,15 @@ fun AccountPage( filteredTransactions: List, filterText: String, onQueryChanged: (String) -> Unit, - updateAccountFilter: (TransactionAccountType) -> Unit + updateAccountFilter: (TransactionAccountType) -> Unit, + userProfile: UserProfile = UserProfile(), + barcodeUiState: Flow = flowOf(BarcodeUiState.Unavailable), ) { val modalBottomSheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) var showBottomSheet by remember { mutableStateOf(false) } + val barcodeSheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) + var showBarcodeSheet by remember { mutableStateOf(false) } + val scope = rememberCoroutineScope() var sheetContent by remember { mutableStateOf(BottomSheetContent.ACCOUNT_TYPE) } AccountPageContent( onSettingsClicked, @@ -88,8 +114,33 @@ fun AccountPage( setFilterText = onQueryChanged, filteredTransactions, setSheetContent = { sheetContent = it }, + userProfile = userProfile, + onBarcodeClicked = { showBarcodeSheet = true }, ) + if (showBarcodeSheet) { + ModalBottomSheet( + onDismissRequest = { showBarcodeSheet = false }, + sheetState = barcodeSheetState, + containerColor = currentColors.backgroundDefault, + contentColor = currentColors.textPrimary, + shape = RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp), + dragHandle = null + ) { + // Collected only while the sheet is open, so the barcode refreshes only then. + val barcode by barcodeUiState.collectAsStateWithLifecycle(BarcodeUiState.Loading) + DiningBarcodeSheet( + userProfile = userProfile, + barcodeUiState = barcode, + onClose = { + scope.launch { barcodeSheetState.hide() }.invokeOnCompletion { + if (!barcodeSheetState.isVisible) showBarcodeSheet = false + } + } + ) + } + } + if (showBottomSheet) { ModalBottomSheet( onDismissRequest = { showBottomSheet = false }, @@ -124,6 +175,13 @@ fun AccountPage( } } +/** + * Position of the sticky transactions header in the account list, after the profile card, its + * spacer, the balances and their spacer. Once it reaches the top the balances have scrolled off, + * so the page header switches to the compact title. + */ +private const val TRANSACTIONS_HEADER_INDEX = 4 + @Composable private fun AccountPageContent( onSettingsClicked: () -> Unit, @@ -133,17 +191,42 @@ private fun AccountPageContent( filterText: String, setFilterText: (String) -> Unit, filteredTransactions: List, - setSheetContent: (BottomSheetContent) -> Unit + setSheetContent: (BottomSheetContent) -> Unit, + userProfile: UserProfile = UserProfile(), + onBarcodeClicked: () -> Unit = {} ) { val innerListState = rememberLazyListState() - val isFirstVisible by remember { derivedStateOf { innerListState.firstVisibleItemIndex > 1 } } + val isFirstVisible by remember { + derivedStateOf { + innerListState.firstVisibleItemIndex >= TRANSACTIONS_HEADER_INDEX + } + } Column( modifier = Modifier .fillMaxWidth() .background(currentColors.backgroundDefault) ) { AccountPageHeader(isFirstVisible, onSettingsClicked) + // Adding or removing an item above the transactions header? Update + // TRANSACTIONS_HEADER_INDEX. LazyColumn(state = innerListState) { + item { + ProfileCard( + userProfile = userProfile, + onBarcodeClicked = onBarcodeClicked, + modifier = Modifier.padding(16.dp) + ) + } + + item { + Spacer( + modifier = Modifier + .fillMaxWidth() + .height(16.dp) + .background(currentColors.accentPrimary) + ) + } + item { (Column(modifier = Modifier.padding(horizontal = 16.dp)) { Column { @@ -211,6 +294,224 @@ private fun AccountPageContent( } } +/** + * Card at the top of the Account page showing the user's profile picture, name, and email, + * plus a button to show their barcode. + */ +@Composable +private fun ProfileCard( + userProfile: UserProfile, + onBarcodeClicked: () -> Unit, + modifier: Modifier = Modifier +) { + Column( + modifier = modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .background(currentColors.backgroundSecondary) + .padding(16.dp) + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + ProfilePicture( + photo = userProfile.photo, + modifier = Modifier.size(64.dp) + ) + Column(modifier = Modifier.padding(start = 16.dp)) { + userProfile.name?.let { + Text( + text = it, + style = EateryBlueTypography.h5, + color = currentColors.oppTextPrimary, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + userProfile.email?.let { + Text( + text = it, + style = EateryBlueTypography.subtitle2, + color = currentColors.oppTextPrimary, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + } + } + Button( + onClick = onBarcodeClicked, + modifier = Modifier + .fillMaxWidth() + .padding(top = 16.dp), + shape = RoundedCornerShape(8.dp), + colors = ButtonDefaults.buttonColors( + containerColor = currentColors.backgroundDefault, + contentColor = currentColors.textPrimary + ) + ) { + Icon( + imageVector = Icons.Outlined.QrCodeScanner, + contentDescription = null, + modifier = Modifier.size(18.dp) + ) + Text( + text = stringResource(R.string.account_barcode), + style = EateryBlueTypography.button, + modifier = Modifier.padding(start = 8.dp) + ) + } + } +} + +/** + * Bottom sheet showing the user's dining barcode beneath their name and email. + */ +@Composable +private fun DiningBarcodeSheet( + userProfile: UserProfile, + barcodeUiState: BarcodeUiState, + onClose: () -> Unit +) { + Column( + modifier = Modifier + .fillMaxWidth() + .navigationBarsPadding() + .padding(start = 16.dp, end = 16.dp, top = 24.dp, bottom = 32.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = stringResource(R.string.account_dining_barcode), + style = EateryBlueTypography.h4, + color = currentColors.textPrimary, + modifier = Modifier.weight(1f) + ) + IconButton( + onClick = onClose, + modifier = Modifier + .size(40.dp) + .background(color = currentColors.accentPrimary, shape = CircleShape) + ) { + Icon( + Icons.Default.Close, + contentDescription = stringResource(R.string.close), + tint = currentColors.textPrimary + ) + } + } + Column( + modifier = Modifier + .padding(top = 16.dp) + .fillMaxWidth() + .clip(RoundedCornerShape(8.dp)) + .border(1.dp, currentColors.borderDefault, RoundedCornerShape(8.dp)) + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .background(currentColors.backgroundSecondary) + .padding(horizontal = 12.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + ProfilePicture( + photo = userProfile.photo, + modifier = Modifier.size(40.dp) + ) + Column(modifier = Modifier.padding(start = 12.dp)) { + userProfile.name?.let { + Text( + text = it, + style = EateryBlueTypography.h5, + color = currentColors.oppTextPrimary, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + userProfile.email?.let { + Text( + text = it, + style = EateryBlueTypography.subtitle2, + color = currentColors.oppTextPrimary, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + } + } + DiningBarcode(barcodeUiState) + } + } +} + +/** + * The dining barcode as a PDF417 symbol. Always black on white, even in dark mode, with a white + * margin around it so scanners can find its edges. + */ +@Composable +private fun DiningBarcode(barcodeUiState: BarcodeUiState) { + Box( + modifier = Modifier + .fillMaxWidth() + .height(96.dp) + .background(Color.White) + .padding(horizontal = 16.dp, vertical = 12.dp), + contentAlignment = Alignment.Center + ) { + when (barcodeUiState) { + BarcodeUiState.Loading -> Unit + BarcodeUiState.Unavailable -> Text( + text = stringResource(R.string.account_barcode_unavailable), + style = EateryBlueTypography.subtitle2, + color = Color.Black, + textAlign = TextAlign.Center + ) + + is BarcodeUiState.Ready -> { + val image = remember(barcodeUiState.digits) { + Pdf417Encoder.encodeToImageBitmap(barcodeUiState.digits) + } + Image( + bitmap = image, + contentDescription = stringResource(R.string.account_dining_barcode), + // Scale by a whole number so every module is the same number of pixels wide; + // a fractional scale makes some bars a pixel wider than others. + modifier = Modifier.layout { measurable, constraints -> + val scale = minOf( + constraints.maxWidth / image.width, + constraints.maxHeight / image.height + ).coerceAtLeast(1) + val placeable = measurable.measure( + Constraints.fixed(image.width * scale, image.height * scale) + ) + layout(placeable.width, placeable.height) { placeable.place(0, 0) } + }, + contentScale = ContentScale.FillBounds, + filterQuality = FilterQuality.None + ) + } + } + } +} + +@Composable +private fun ProfilePicture(photo: ImageBitmap?, modifier: Modifier = Modifier) { + Box( + modifier = modifier + .clip(CircleShape) + .background(currentColors.backgroundDefault) + ) { + photo?.let { + Image( + bitmap = it, + contentDescription = stringResource(R.string.a11y_profile_picture), + contentScale = ContentScale.Crop, + modifier = Modifier.fillMaxSize() + ) + } + } +} + @Composable private fun TransactionsHeader( accountFilter: TransactionAccountType, @@ -621,7 +922,26 @@ private fun AccountPagePreview() = EateryPreview { formattedDate = "2:00 PM · Monday, October 2" ) ), - setSheetContent = {} + setSheetContent = {}, + userProfile = previewUserProfile() + ) +} + +@DualModePreview +@Composable +private fun DiningBarcodeSheetPreview() = EateryPreview { + DiningBarcodeSheet( + userProfile = previewUserProfile(), + // Fake value from BarcodeGeneratorTest, not a live account. + barcodeUiState = BarcodeUiState.Ready("1700000000102731570695"), + onClose = {} ) } +/** Sample profile for previews, with a bundled image standing in for the user's photo. */ +@Composable +private fun previewUserProfile() = UserProfile( + name = "Jane Doe", + email = "jd123@cornell.edu", + photo = ImageBitmap.imageResource(R.drawable.blank_eatery_square) +) diff --git a/app/src/main/java/com/cornellappdev/android/eatery/ui/screens/ProfileScreen.kt b/app/src/main/java/com/cornellappdev/android/eatery/ui/screens/ProfileScreen.kt index 13b1efd9..2624a9c0 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/ui/screens/ProfileScreen.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/ui/screens/ProfileScreen.kt @@ -9,14 +9,18 @@ import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.cornellappdev.android.eatery.data.models.AccountBalances import com.cornellappdev.android.eatery.data.models.TransactionAccountType +import com.cornellappdev.android.eatery.data.models.UserProfile import com.cornellappdev.android.eatery.ui.components.general.NetworkErrorToast import com.cornellappdev.android.eatery.ui.components.login.AccountPage import com.cornellappdev.android.eatery.ui.components.login.LoginPage import com.cornellappdev.android.eatery.ui.theme.currentColors import com.cornellappdev.android.eatery.ui.viewmodels.LoginViewModel +import com.cornellappdev.android.eatery.ui.viewmodels.state.BarcodeUiState import com.cornellappdev.android.eatery.ui.viewmodels.state.DisplayTransaction import com.cornellappdev.android.eatery.util.DualModePreview import com.cornellappdev.android.eatery.util.EateryPreview +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf @Composable @@ -48,7 +52,9 @@ fun ProfileScreen( filterText = uiState.filterText, filteredTransactions = uiState.filteredTransactions, onQueryChanged = loginViewModel::setQuery, - updateAccountFilter = loginViewModel::updateAccountFilter + updateAccountFilter = loginViewModel::updateAccountFilter, + userProfile = uiState.userProfile, + barcodeUiState = loginViewModel.barcodeUiState ) } @@ -66,7 +72,9 @@ private fun ProfileScreenContent( onSettingsClicked: () -> Unit, filteredTransactions: List, onQueryChanged: (String) -> Unit, - updateAccountFilter: (TransactionAccountType) -> Unit + updateAccountFilter: (TransactionAccountType) -> Unit, + userProfile: UserProfile = UserProfile(), + barcodeUiState: Flow = flowOf(BarcodeUiState.Unavailable) ) { Box( modifier = Modifier @@ -90,7 +98,9 @@ private fun ProfileScreenContent( filteredTransactions = filteredTransactions, filterText = filterText, onQueryChanged = onQueryChanged, - updateAccountFilter = updateAccountFilter + updateAccountFilter = updateAccountFilter, + userProfile = userProfile, + barcodeUiState = barcodeUiState ) } } @@ -145,7 +155,8 @@ private fun ProfileScreenAccountPreview() = EateryPreview { ) ), onQueryChanged = {}, - updateAccountFilter = {} + updateAccountFilter = {}, + userProfile = UserProfile(name = "Wonjin Eum", email = "we46@cornell.edu") ) } diff --git a/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/LoginViewModel.kt b/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/LoginViewModel.kt index 731c99c6..b8b20d26 100644 --- a/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/LoginViewModel.kt +++ b/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/LoginViewModel.kt @@ -3,26 +3,39 @@ package com.cornellappdev.android.eatery.ui.viewmodels import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.cornellappdev.android.eatery.data.models.AccountBalances +import com.cornellappdev.android.eatery.data.models.BarcodeCredentials import com.cornellappdev.android.eatery.data.models.NetworkError import com.cornellappdev.android.eatery.data.models.Result import com.cornellappdev.android.eatery.data.models.Transaction import com.cornellappdev.android.eatery.data.models.TransactionAccountType import com.cornellappdev.android.eatery.data.models.User +import com.cornellappdev.android.eatery.data.models.UserProfile import com.cornellappdev.android.eatery.data.repositories.GETAccountRepository import com.cornellappdev.android.eatery.data.repositories.UserRepository +import com.cornellappdev.android.eatery.ui.viewmodels.state.BarcodeUiState import com.cornellappdev.android.eatery.ui.viewmodels.state.DisplayTransaction import com.cornellappdev.android.eatery.ui.viewmodels.state.NetworkAction import com.cornellappdev.android.eatery.ui.viewmodels.state.NetworkUiError +import com.cornellappdev.android.eatery.util.BarcodeGenerator import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch +import java.time.Instant import java.time.LocalDateTime import java.time.format.DateTimeFormatter import javax.inject.Inject +import kotlin.time.Duration.Companion.seconds @HiltViewModel class LoginViewModel @Inject constructor( @@ -37,6 +50,7 @@ class LoginViewModel @Inject constructor( val accountFilter: TransactionAccountType = TransactionAccountType.BRBS, val filterText: String = "", val filteredTransactions: List = emptyList(), + val userProfile: UserProfile = UserProfile(), val error: NetworkUiError? = null ) @@ -77,8 +91,12 @@ class LoginViewModel @Inject constructor( ) } - val uiState = combine(loginDataState, _error) { dataState, error -> - dataState.copy(error = error) + val uiState = combine( + loginDataState, + _error, + userRepository.userProfileFlow + ) { dataState, error, userProfile -> + dataState.copy(error = error, userProfile = userProfile) }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), @@ -99,6 +117,9 @@ class LoginViewModel @Inject constructor( } companion object { + /** How often the barcode regenerates, matching iOS. Its value encodes the time. */ + private val BARCODE_REFRESH_INTERVAL = 5.seconds + private fun LocalDateTime.formatDate(): String { val outputFormatter = DateTimeFormatter.ofPattern("h:mm a · EEEE, MMMM d") return outputFormatter.format(this) @@ -188,17 +209,66 @@ class LoginViewModel @Inject constructor( when (val result = userRepository.getFinancials()) { is Result.Success -> { onNetworkSuccess() - refreshBarcodeData() + refreshProfileAndBarcodeData() } is Result.Error -> onNetworkFailure(NetworkAction.GetFinancials, result.error) } } /** - * Refreshes the cached barcode data while online so the barcode can be generated offline later. - * A failure keeps the existing cache and shows no error, since the balances already loaded. + * Loads the user's name, email, and photo if they aren't loaded yet, then refreshes the cached + * barcode data so the barcode can be generated offline later. Runs after financials so it + * doesn't hold up the balances. + * + * The profile stays in [UserRepository] until logout, so it's fetched once per login rather + * than on every visit to this screen. Logging out clears it, so the next account fetches its + * own. + * + * Each request renews the GET session if it has expired, so they run one after the other: + * run at once, both could renew the session and invalidate each other's new session ID. + * Failures show no error, since the balances already loaded: the profile card stays empty and + * the existing barcode cache is kept. + */ + private fun refreshProfileAndBarcodeData() { + viewModelScope.launch { + if (userRepository.userProfileFlow.value == UserProfile()) { + userRepository.getProfile() + } + getAccountRepository.refreshBarcodeData() + } + } + + /** + * The dining barcode, regenerated every [BARCODE_REFRESH_INTERVAL] while collected. Cold: + * collect it only while the barcode is on screen. Uses the cached credentials, so it works + * offline, and updates when a refresh caches new ones. */ - private fun refreshBarcodeData() { - viewModelScope.launch { getAccountRepository.refreshBarcodeData() } + @OptIn(ExperimentalCoroutinesApi::class) + val barcodeUiState: Flow = getAccountRepository.barcodeCredentialsFlow + .distinctUntilChanged() + .flatMapLatest { credentials -> + if (credentials == null) { + flowOf(BarcodeUiState.Unavailable) + } else { + flow { + while (true) { + emit(generateBarcode(credentials)) + delay(BARCODE_REFRESH_INTERVAL) + } + } + } + } + .onStart { emit(BarcodeUiState.Loading) } + + private fun generateBarcode(credentials: BarcodeCredentials): BarcodeUiState = try { + BarcodeUiState.Ready( + BarcodeGenerator.generateBarcode( + seedHex = credentials.barcodeSeed, + cashlessKey = credentials.patronId, + timestamp = Instant.now().epochSecond + ) + ) + } catch (_: IllegalArgumentException) { + BarcodeUiState.Unavailable } } diff --git a/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/state/BarcodeUiState.kt b/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/state/BarcodeUiState.kt new file mode 100644 index 00000000..aa89773a --- /dev/null +++ b/app/src/main/java/com/cornellappdev/android/eatery/ui/viewmodels/state/BarcodeUiState.kt @@ -0,0 +1,18 @@ +package com.cornellappdev.android.eatery.ui.viewmodels.state + +/** What the dining barcode sheet shows. */ +sealed interface BarcodeUiState { + /** The cached credentials haven't been read yet. */ + data object Loading : BarcodeUiState + + /** + * No barcode can be shown: the credentials haven't been fetched for this account yet, or + * they couldn't be turned into a barcode. + */ + data object Unavailable : BarcodeUiState + + /** The current barcode value. A payment credential: never log it. */ + data class Ready(val digits: String) : BarcodeUiState { + override fun toString() = "Ready(digits=)" + } +} diff --git a/app/src/main/java/com/cornellappdev/android/eatery/util/Pdf417Encoder.kt b/app/src/main/java/com/cornellappdev/android/eatery/util/Pdf417Encoder.kt new file mode 100644 index 00000000..0990f9c6 --- /dev/null +++ b/app/src/main/java/com/cornellappdev/android/eatery/util/Pdf417Encoder.kt @@ -0,0 +1,48 @@ +package com.cornellappdev.android.eatery.util + +import android.graphics.Bitmap +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asImageBitmap +import com.google.zxing.BarcodeFormat +import com.google.zxing.EncodeHintType +import com.google.zxing.common.BitMatrix +import com.google.zxing.pdf417.PDF417Writer + +/** + * Draws the GET barcode as a PDF417 symbol, the format the dining scanners read. iOS draws the + * same symbol with `CIPDF417BarcodeGenerator`. + */ +object Pdf417Encoder { + private const val BLACK = 0xFF000000.toInt() + private const val WHITE = 0xFFFFFFFF.toInt() + + /** + * Encodes [contents] at its natural size with no quiet zone: one pixel per module across, a + * few pixels per row down. Requesting a wider-than-tall size keeps the symbol horizontal; a + * size this small is never scaled up. The caller must leave a white margin around the drawn + * symbol so scanners can find its edges. + * + * @throws com.google.zxing.WriterException if [contents] can't be encoded + */ + fun encode(contents: String): BitMatrix = PDF417Writer().encode( + contents, + BarcodeFormat.PDF_417, + /* width = */ 2, + /* height = */ 1, + mapOf(EncodeHintType.MARGIN to 0) + ) + + /** + * Returns [contents] as a black-on-white PDF417 image at its natural size. Draw it with + * `FilterQuality.None` so scaling it up keeps the edges sharp. + */ + fun encodeToImageBitmap(contents: String): ImageBitmap = + encode(contents).toBitmap().asImageBitmap() + + private fun BitMatrix.toBitmap(): Bitmap { + val pixels = IntArray(width * height) { index -> + if (get(index % width, index / width)) BLACK else WHITE + } + return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888) + } +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e542793f..e4457b81 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -137,6 +137,10 @@ Search for transactions… Past 30 Days Show transactions + Barcode + Dining Barcode + Sorry, barcode unavailable right now. Please try again later! + Profile picture Change account type Location permissions are necessary to show you eateries that are the closest to you! diff --git a/app/src/test/java/com/cornellappdev/android/eatery/util/Pdf417EncoderTest.kt b/app/src/test/java/com/cornellappdev/android/eatery/util/Pdf417EncoderTest.kt new file mode 100644 index 00000000..c354e4aa --- /dev/null +++ b/app/src/test/java/com/cornellappdev/android/eatery/util/Pdf417EncoderTest.kt @@ -0,0 +1,47 @@ +package com.cornellappdev.android.eatery.util + +import com.google.zxing.BinaryBitmap +import com.google.zxing.RGBLuminanceSource +import com.google.zxing.common.BitMatrix +import com.google.zxing.common.HybridBinarizer +import com.google.zxing.pdf417.PDF417Reader +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class Pdf417EncoderTest { + private val sampleBarcode = + BarcodeGenerator.generateBarcode("0123456789abcdef", "12345", 1_700_000_000) + + @Test + fun decodesBackToTheBarcodeDigits() { + assertEquals(sampleBarcode, decode(Pdf417Encoder.encode(sampleBarcode))) + } + + @Test + fun symbolIsWiderThanTall() { + val matrix = Pdf417Encoder.encode(sampleBarcode) + assertTrue(matrix.width > matrix.height) + } + + /** Scales [matrix] up and pads it with a white quiet zone, as the UI does, then decodes it. */ + private fun decode(matrix: BitMatrix): String { + val scale = 4 + val margin = 10 * scale + val width = matrix.width * scale + margin * 2 + val height = matrix.height * scale + margin * 2 + val pixels = IntArray(width * height) { index -> + val x = (index % width - margin) + val y = (index / width - margin) + val inside = x in 0 until matrix.width * scale && y in 0 until matrix.height * scale + if (inside && matrix.get(x / scale, y / scale)) BLACK else WHITE + } + val bitmap = BinaryBitmap(HybridBinarizer(RGBLuminanceSource(width, height, pixels))) + return PDF417Reader().decode(bitmap).text + } + + private companion object { + const val BLACK = 0xFF000000.toInt() + const val WHITE = 0xFFFFFFFF.toInt() + } +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index b540b962..d35efaa9 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -32,6 +32,7 @@ composeShimmer = "1.5.0" coil = "2.7.0" hiltLifecycleViewmodelCompose = "1.4.0" appUpdate = "2.1.0" +zxing = "3.5.4" [libraries] junit = { module = "junit:junit", version.ref = "junit" } @@ -90,6 +91,7 @@ coil-compose = { module = "io.coil-kt:coil-compose", version.ref = "coil" } play-app-update = { module = "com.google.android.play:app-update", version.ref = "appUpdate" } play-app-update-ktx = { module = "com.google.android.play:app-update-ktx", version.ref = "appUpdate" } +zxing-core = { module = "com.google.zxing:core", version.ref = "zxing" } [plugins] android-application = { id = "com.android.application", version.ref = "agp" }