Skip to content

Commit

Permalink
code optimisation
Browse files Browse the repository at this point in the history
  • Loading branch information
cp-megh-l committed Jan 24, 2025
1 parent eb0632a commit 8b5d1e2
Show file tree
Hide file tree
Showing 8 changed files with 40 additions and 46 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,10 @@ class JourneyTimelineViewModel @Inject constructor(
val lastJourneyTime = allJourneys.minOfOrNull { it.updated_at }

val locations = if (loadMore) {
journeyService.getMoreJourneyHistory(userId, lastJourneyTime)
state.value.selectedUser?.let { journeyService.getMoreJourneyHistory(it, lastJourneyTime) }
} else {
journeyService.getJourneyHistory(userId, from, to)
}
state.value.selectedUser?.let { journeyService.getJourneyHistory(it, from, to) }
} ?: emptyList()

val filteredLocations = locations.filter {
it.created_at in from..to ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ class SignInMethodViewModelTest {
whenever(authService.verifiedGoogleLogin("uid", "firebaseToken", account))
.thenReturn(true)
viewModel.proceedGoogleSignIn(account)
verify(navigator).navigateTo("set-pin", "sign-in", true)
verify(navigator).navigateTo("onboard", "sign-in", true)
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,16 @@ class LocationUpdateReceiver : BroadcastReceiver() {
LocationResult.extractResult(intent)?.let { locationResult ->
scope.launch {
try {
val userId = authService.currentUser?.id ?: return@launch
val user = authService.currentUser ?: return@launch
Timber.e("Location update received: ${locationResult.locations.size}")
locationResult.locations.forEach { extractedLocation ->
locationService.saveCurrentLocation(
userId,
user,
extractedLocation.latitude,
extractedLocation.longitude,
System.currentTimeMillis()
)
journeyRepository.saveLocationJourney(extractedLocation, userId)
journeyRepository.saveLocationJourney(extractedLocation, user)
}
} catch (e: Exception) {
Timber.e(e, "Error while saving location")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.canopas.yourspace.data.repository

import android.location.Location
import com.canopas.yourspace.data.models.location.LocationJourney
import com.canopas.yourspace.data.models.user.ApiUser
import com.canopas.yourspace.data.service.location.ApiJourneyService
import com.canopas.yourspace.data.storage.LocationCache
import timber.log.Timber
Expand All @@ -15,12 +16,13 @@ class JourneyRepository @Inject constructor(
) {
suspend fun saveLocationJourney(
extractedLocation: Location,
userId: String
user: ApiUser
) {
try {
val userId = user.id
cacheLocations(extractedLocation, userId)

val lastKnownJourney = getLastKnownLocation(userId)
val lastKnownJourney = getLastKnownLocation(user)

val result = getJourney(
userId = userId,
Expand Down Expand Up @@ -56,15 +58,15 @@ class JourneyRepository @Inject constructor(
* with steady state in cache as well as remote database
* */
private suspend fun getLastKnownLocation(
userid: String
user: ApiUser
): LocationJourney? {
// Return last location journey if available from cache
return locationCache.getLastJourney(userid) ?: run {
return locationCache.getLastJourney(user.id) ?: run {
// Here, means no location journey available in cache
// Fetch last location journey from remote database and save it to cache
val lastJourney = journeyService.getLastJourneyLocation(userid)
val lastJourney = journeyService.getLastJourneyLocation(user)
return lastJourney?.let {
locationCache.putLastJourney(it, userid)
locationCache.putLastJourney(it, user.id)
lastJourney
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ class SpaceRepository @Inject constructor(
val user = userService.getUser(member.user_id)
val session = userService.getUserSession(member.user_id)
user?.let {
locationService.getCurrentLocation(user.id)
locationService.getCurrentLocation(user)
.map {
UserInfo(
user,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import com.canopas.yourspace.data.models.location.EncryptedLocationJourney
import com.canopas.yourspace.data.models.location.LocationJourney
import com.canopas.yourspace.data.models.space.GroupKeysDoc
import com.canopas.yourspace.data.models.user.ApiUser
import com.canopas.yourspace.data.service.user.ApiUserService
import com.canopas.yourspace.data.storage.UserPreferences
import com.canopas.yourspace.data.storage.bufferedkeystore.BufferedSenderKeyStore
import com.canopas.yourspace.data.utils.Config
Expand All @@ -31,7 +30,6 @@ import javax.inject.Singleton
@Singleton
class ApiJourneyService @Inject constructor(
db: FirebaseFirestore,
val apiUserService: ApiUserService,
private val userPreferences: UserPreferences,
private val bufferedSenderKeyStore: BufferedSenderKeyStore
) {
Expand Down Expand Up @@ -177,10 +175,9 @@ class ApiJourneyService @Inject constructor(
}
}

suspend fun getLastJourneyLocation(userId: String): LocationJourney? {
val user = apiUserService.getUser(userId) ?: return null
suspend fun getLastJourneyLocation(user: ApiUser): LocationJourney? {
return if (user.isPremiumUser) {
val encryptedJourney = spaceMemberJourneyRef(currentSpaceId, userId)
val encryptedJourney = spaceMemberJourneyRef(currentSpaceId, user.id)
.orderBy("created_at", Query.Direction.DESCENDING)
.limit(1)
.get()
Expand All @@ -194,14 +191,14 @@ class ApiJourneyService @Inject constructor(

runWithGroupCipher(
currentSpaceId,
userId,
user.id,
groupKeysDoc,
encryptedJourney.key_id,
null
) { it.let { cipher -> encryptedJourney.toDecryptedLocationJourney(cipher) } }
} else {
spaceMemberJourneyRef(currentSpaceId, userId)
.whereEqualTo("user_id", userId)
spaceMemberJourneyRef(currentSpaceId, user.id)
.whereEqualTo("user_id", user.id)
.orderBy("created_at", Query.Direction.DESCENDING)
.limit(1)
.get()
Expand All @@ -212,12 +209,11 @@ class ApiJourneyService @Inject constructor(
}
}

suspend fun getMoreJourneyHistory(userId: String, from: Long?): List<LocationJourney> {
val user = apiUserService.getUser(userId) ?: return emptyList()
suspend fun getMoreJourneyHistory(user: ApiUser, from: Long?): List<LocationJourney> {
val groupKeysDoc = if (user.isPremiumUser) getGroupKeyDoc(currentSpaceId) ?: return emptyList() else null

val query = spaceMemberJourneyRef(currentSpaceId, userId)
.whereEqualTo("user_id", userId)
val query = spaceMemberJourneyRef(currentSpaceId, user.id)
.whereEqualTo("user_id", user.id)
.orderBy("created_at", Query.Direction.DESCENDING)
.apply { from?.let { whereLessThan("created_at", it) } }
.limit(20)
Expand All @@ -230,7 +226,7 @@ class ApiJourneyService @Inject constructor(
journeys.mapNotNull { encrypted ->
getGroupCipherByKeyId(
currentSpaceId,
userId,
user.id,
(encrypted as EncryptedLocationJourney).key_id,
groupKeysDoc!!
)?.let { (_, cipher) ->
Expand All @@ -242,22 +238,21 @@ class ApiJourneyService @Inject constructor(
}
}

suspend fun getJourneyHistory(userId: String, from: Long, to: Long): List<LocationJourney> {
suspend fun getJourneyHistory(user: ApiUser, from: Long, to: Long): List<LocationJourney> {
return try {
val user = apiUserService.getUser(userId) ?: return emptyList()
val groupKeysDoc = if (user.isPremiumUser) getGroupKeyDoc(currentSpaceId) ?: return emptyList() else null

val previousDay = spaceMemberJourneyRef(currentSpaceId, userId)
.whereEqualTo("user_id", userId)
val previousDay = spaceMemberJourneyRef(currentSpaceId, user.id)
.whereEqualTo("user_id", user.id)
.whereLessThan("created_at", from)
.whereGreaterThanOrEqualTo("updated_at", from)
.limit(1)
.get()
.await()
.documents

val currentDay = spaceMemberJourneyRef(currentSpaceId, userId)
.whereEqualTo("user_id", userId)
val currentDay = spaceMemberJourneyRef(currentSpaceId, user.id)
.whereEqualTo("user_id", user.id)
.whereGreaterThanOrEqualTo("created_at", from)
.whereLessThanOrEqualTo("created_at", to)
.orderBy("created_at", Query.Direction.DESCENDING)
Expand All @@ -274,7 +269,7 @@ class ApiJourneyService @Inject constructor(
allJourneys.mapNotNull { encrypted ->
getGroupCipherByKeyId(
currentSpaceId,
userId,
user.id,
(encrypted as EncryptedLocationJourney).key_id,
groupKeysDoc!!
)?.let { (_, cipher) ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import com.canopas.yourspace.data.models.space.EncryptedDistribution
import com.canopas.yourspace.data.models.space.GroupKeysDoc
import com.canopas.yourspace.data.models.space.MemberKeyData
import com.canopas.yourspace.data.models.user.ApiUser
import com.canopas.yourspace.data.service.user.ApiUserService
import com.canopas.yourspace.data.storage.UserPreferences
import com.canopas.yourspace.data.storage.bufferedkeystore.BufferedSenderKeyStore
import com.canopas.yourspace.data.utils.Config
Expand All @@ -20,7 +19,6 @@ import com.canopas.yourspace.data.utils.snapshotFlow
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.Query
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.tasks.await
import org.signal.libsignal.protocol.InvalidKeyException
Expand All @@ -40,7 +38,6 @@ import javax.inject.Singleton
@Singleton
class ApiLocationService @Inject constructor(
private val db: FirebaseFirestore,
val apiUserService: ApiUserService,
private val locationManager: LocationManager,
private val userPreferences: UserPreferences,
private val bufferedSenderKeyStore: BufferedSenderKeyStore
Expand All @@ -64,29 +61,29 @@ class ApiLocationService @Inject constructor(
spaceRef.document(spaceId).collection(FIRESTORE_COLLECTION_SPACE_GROUP_KEYS)
.document(FIRESTORE_COLLECTION_SPACE_GROUP_KEYS)

suspend fun saveLastKnownLocation(userId: String) {
suspend fun saveLastKnownLocation(user: ApiUser) {
val lastLocation = locationManager.getLastLocation() ?: return
saveCurrentLocation(
userId = userId,
user = user,
latitude = lastLocation.latitude,
longitude = lastLocation.longitude,
recordedAt = System.currentTimeMillis()
)
}

suspend fun saveCurrentLocation(
userId: String,
user: ApiUser,
latitude: Double,
longitude: Double,
recordedAt: Long
) {
val currentUser = userPreferences.currentUser ?: return
currentUser.space_ids?.forEach { spaceId ->
user.space_ids?.forEach { spaceId ->
val userId = user.id
if (spaceId.isBlank()) return@forEach

// Check if user is premium before encrypting location
// In future, need to check if encryption is enabled for the space
if (currentUser.isPremiumUser) {
if (user.isPremiumUser) {
saveEncryptedLocation(spaceId, userId, latitude, longitude, recordedAt)
} else {
savePlainLocation(spaceId, userId, latitude, longitude, recordedAt)
Expand Down Expand Up @@ -157,8 +154,8 @@ class ApiLocationService @Inject constructor(
spaceMemberLocationRef(spaceId, userId).document(location.id).set(location).await()
}

suspend fun getCurrentLocation(userId: String): Flow<List<ApiLocation?>> {
val user = apiUserService.getUser(userId) ?: return emptyFlow()
suspend fun getCurrentLocation(user: ApiUser): Flow<List<ApiLocation?>> {
val userId = user.id
val locationRef = spaceMemberLocationRef(currentSpaceId, userId)
.whereEqualTo("user_id", userId)
.orderBy("created_at", Query.Direction.DESCENDING)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ class ApiUserService @Inject constructor(
app_version = device.versionCode
)
sessionDocRef.set(session).await()
locationService.saveLastKnownLocation(user.id)
locationService.saveLastKnownLocation(user)
return Triple(true, user, session)
}
}
Expand Down

0 comments on commit 8b5d1e2

Please sign in to comment.