Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<Match>
}
Original file line number Diff line number Diff line change
@@ -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) }
Comment thread
mqiu90 marked this conversation as resolved.
Resolved
.getOrNull() ?: return null
return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)?.asImageBitmap()
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<BarcodeCredentials?> =
userPreferencesRepository.barcodeCredentialsFlow

suspend fun clearBarcodeData() = userPreferencesRepository.clearBarcodeData()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -55,6 +62,17 @@ class UserRepository @Inject constructor(
/** Expose whether a user is currently logged in. Delegates to UserPreferencesRepository. */
val isLoggedInFlow: Flow<Boolean> = userPreferencesRepository.isLoggedInFlow

private val _userProfile: MutableStateFlow<UserProfile> = 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> = _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<Unit> {
Expand Down Expand Up @@ -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<UserProfile> = resultOfNetworkCall {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need this to return anything if we already have the flow? Maybe change function name and return type so it's more of an update function.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

^^

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")
Comment on lines +240 to +242

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this logic seems repeated. can we refactor it out

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also caleb's comment here is still open, could u pull the 401 retry into a shared helper that getFinancials and getProfile both use?

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 {
Expand All @@ -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 =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading