Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check accuracy before updating user's location #102

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

cp-megh-l
Copy link
Collaborator

@cp-megh-l cp-megh-l commented Oct 16, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced location update functionality with improved accuracy checks and distance filtering.
    • New caching mechanism for storing the last extracted location for users.
    • Added ability to switch between time-based and distance-based location updates.
    • Integrated location management into notification handling for improved user journey tracking.
  • Bug Fixes

    • Streamlined journey saving process by simplifying method signatures.
  • Documentation

    • Updated comments for clarity throughout various classes.
  • Chores

    • Configuration updates for project settings to support a lower Java version.

Copy link

coderabbitai bot commented Oct 16, 2024

Walkthrough

This pull request introduces modifications across several files, focusing on updating configuration settings and enhancing location management functionalities. The .idea/compiler.xml and .idea/misc.xml files have been updated to change the target Java version from 21 to 17. Additionally, significant changes have been made to classes related to location updates, including the introduction of new methods, constants, and dependency injections to improve the handling of location data and user journeys.

Changes

File Path Change Summary
.idea/compiler.xml Updated bytecodeTargetLevel from 21 to 17.
.idea/misc.xml Changed languageLevel from JDK_21 to JDK_17, updated project-jdk-name from jbr-21 to jbr-17, and added ExternalStorageConfigurationManager component with enabled="true".
data/src/main/java/com/canopas/yourspace/data/receiver/location/LocationUpdateReceiver.kt Enhanced logging in onReceive method by adding a new logging statement for location updates and removing the previous statement about the size of the locations array.
data/src/main/java/com/canopas/yourspace/data/repository/JourneyRepository.kt Introduced CoroutineScope and Timer for managing a steady location timer, updated constructor, and added methods for starting and canceling the timer.
data/src/main/java/com/canopas/yourspace/data/service/location/ApiJourneyService.kt Modified saveCurrentJourney method to return a String instead of using a callback, removed newJourneyId parameter, and adjusted the position of the updateAt parameter.
data/src/main/java/com/canopas/yourspace/data/service/location/LocationManager.kt Introduced MINIMUM_DISTANCE, refactored createRequest, added createRequestWithMinimumDistance, and implemented methods for switching between time-based and distance-based updates.
app/src/main/java/com/canopas/yourspace/domain/fcm/YourSpaceFcmService.kt Injected new dependencies LocationCache and JourneyRepository, updated handleUpdateStateNotification method to save location data when relevant notifications are received.

Possibly related PRs

  • Added steady for time for steady location. #103: The changes in this PR involve updates to the JourneyTimelineScreen and JourneyDetailScreen, which may relate to the overall handling of location data and user journeys, similar to the modifications in the main PR regarding project configuration for location management.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary or Summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 9

🧹 Outside diff range and nitpick comments (7)
data/src/main/java/com/canopas/yourspace/data/storage/LocationCache.kt (2)

23-25: LGTM: New method to store last extracted location.

The putLastExtractedLocation method is implemented correctly. It follows the class's naming conventions and properly stores the location in the cache.

Consider adding input validation to ensure that neither location nor userId is null before storing in the cache.


Line range hint 40-43: Update the clear method to include the new cache.

The clear method currently doesn't clear the newly added lastExtractedLocation cache. This could lead to stale location data persisting when other caches are cleared.

Update the clear method to include the new cache:

 fun clear() {
     lastJourneyCache.evictAll()
     lastFiveLocationsCache.evictAll()
+    lastExtractedLocation.evictAll()
 }
data/src/main/java/com/canopas/yourspace/data/service/location/ApiJourneyService.kt (1)

38-39: Approve changes with a suggestion for error handling

The modifications to the saveCurrentJourney method are well-implemented:

  1. Returning String instead of using a callback simplifies usage and allows for better error propagation.
  2. Removal of the newJourneyId parameter aligns with the new return type.
  3. Moving updateAt to the end of the parameter list maintains backwards compatibility and follows Kotlin conventions.

These changes improve the method's usability and adhere to Kotlin best practices.

Consider adding error handling to catch potential exceptions from the Firestore operation:

suspend fun saveCurrentJourney(
    // ... other parameters ...
    updateAt: Long? = null
): String {
    val docRef = journeyRef(userId).document()
    val journey = LocationJourney(
        // ... journey initialization ...
    )
    
    return try {
        docRef.set(journey).await()
        docRef.id
    } catch (e: Exception) {
        Timber.e(e, "Error saving current journey")
        throw e // or handle the error as appropriate for your use case
    }
}

This addition would provide better visibility into potential issues during the save operation.

Also applies to: 57-58

data/src/main/java/com/canopas/yourspace/data/receiver/location/LocationUpdateReceiver.kt (4)

60-61: Adjust logging level from error to debug or info

The log message "Skipping location update due to low accuracy: $accuracy" indicates a normal control flow and not an error condition. Using Timber.e (error) might be misleading. Consider using Timber.d (debug) or Timber.i (info) to reflect that this is expected behavior.


67-68: Adjust logging level from error to debug or info

The message "Distance is less than $MINIMUM_DISTANCE meters, skipping location update" represents normal operation when the user hasn't moved significantly. Logging this as an error with Timber.e may not be appropriate. Consider switching to Timber.d or Timber.i to indicate that this is standard behavior.


Line range hint 77-79: Catch more specific exceptions instead of generic Exception

Catching the generic Exception can mask other unexpected runtime exceptions and make debugging harder. Consider catching more specific exceptions that are likely to be thrown during the location saving process, such as IOException or any custom exceptions.


56-56: Consider logging when location has no accuracy

Currently, when extractedLocation.hasAccuracy() returns false, the loop continues without any logging. For better debugging and monitoring, consider adding a log statement to indicate that a location update was skipped due to missing accuracy information.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 793cf91 and 4132b4d.

📒 Files selected for processing (7)
  • .idea/compiler.xml (1 hunks)
  • .idea/misc.xml (1 hunks)
  • data/src/main/java/com/canopas/yourspace/data/receiver/location/LocationUpdateReceiver.kt (4 hunks)
  • data/src/main/java/com/canopas/yourspace/data/repository/JourneyRepository.kt (9 hunks)
  • data/src/main/java/com/canopas/yourspace/data/service/location/ApiJourneyService.kt (2 hunks)
  • data/src/main/java/com/canopas/yourspace/data/service/location/LocationManager.kt (4 hunks)
  • data/src/main/java/com/canopas/yourspace/data/storage/LocationCache.kt (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .idea/compiler.xml
🧰 Additional context used
🔇 Additional comments (14)
.idea/misc.xml (2)

4-4: Java version downgraded from 21 to 17

The project's Java version has been changed from 21 to 17. This is a significant change that will affect the entire project's compilation and potentially its runtime behavior.

To ensure this change is applied consistently and to understand its impact, please run the following checks:

#!/bin/bash
# Check for Java 21 specific features that might need to be refactored
rg --type java "sealed|record\s+class|pattern\s+matching.*instanceof"

# Verify build files are updated accordingly
rg --type gradle "sourceCompatibility|targetCompatibility"

# Check if any dependencies require Java 21
rg --type gradle "requires\s+java\s*21"

Please ensure that:

  1. All team members are aware of this change and have updated their local environments.
  2. CI/CD pipelines are updated to use Java 17.
  3. Any code using Java 21 specific features has been refactored.
  4. All dependencies are compatible with Java 17.

Consider documenting the reason for this downgrade in the project's README or a similar location to provide context for future developers.


3-3: New external storage configuration added

The addition of <component name="ExternalStorageConfigurationManager" enabled="true" /> indicates that the project is now using external storage for some of its configuration. This change doesn't directly affect the code but may impact how the project is managed in the IDE.

To ensure this change is consistent with other project files, let's check for any related configurations:

✅ Verification successful

External storage configuration addition verified

The addition of <component name="ExternalStorageConfigurationManager" enabled="true" /> has been verified, and no additional references to this component were found in the project. This change does not affect the code directly but may impact how the project is managed within the IDE.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other files that might reference external storage configuration
rg --type xml "ExternalStorageConfigurationManager"

Length of output: 472


Script:

#!/bin/bash
# Search for references to ExternalStorageConfigurationManager in all XML files
rg "ExternalStorageConfigurationManager" --glob "*.xml"

Length of output: 55

data/src/main/java/com/canopas/yourspace/data/storage/LocationCache.kt (2)

12-12: LGTM: New cache for last extracted location.

The addition of lastExtractedLocation cache is well-implemented. It uses LruCache appropriately, has a reasonable size, and maintains proper encapsulation.


27-29: LGTM: New method to retrieve last extracted location.

The getLastExtractedLocation method is well-implemented. It follows the class's naming conventions, handles potential null values correctly, and has an appropriate nullable return type.

data/src/main/java/com/canopas/yourspace/data/receiver/location/LocationUpdateReceiver.kt (1)

64-64: Confirm behavior when lastLocation is null

When lastLocation is null, distance is set to Float.MAX_VALUE, which ensures that updateLocation() is called. Verify that this is the intended behavior and that updating the location when there is no previous location is desired.

data/src/main/java/com/canopas/yourspace/data/repository/JourneyRepository.kt (8)

11-11: Approved: Added import for LocationManager

The import statement correctly brings in the LocationManager class needed for the new functionality.


25-26: Verify Dependency Injection for LocationManager

You've added locationManager as a new dependency in the constructor. Please ensure that:

  • All instances of JourneyRepository are provided with a LocationManager instance.
  • The Dependency Injection framework (e.g., Dagger/Hilt) is properly configured to inject LocationManager.

80-86: Verify Removal of createdAt and updatedAt Parameters

You've removed createdAt and updatedAt from the saveCurrentJourney method call. Ensure that:

  • The saveCurrentJourney method has default handling for these parameters internally.
  • Omitting these parameters doesn't lead to incorrect timestamp data or errors when saving a journey.

110-113: Approved: Added Day Change Check for Last Known Journey

Including the isDayChanged check ensures that the journey data remains accurate by handling day transitions properly.


172-176: Approved: Adjusted Location Requests Based on User Movement

The logic correctly switches the location request strategy:

  • When the user starts moving, it switches to time-based requests.
  • When the user remains steady, it switches to distance-based requests.

This should optimize battery usage and location accuracy.


199-202: Approved: Updated Location Requests When User Stops Moving

By transitioning to distance-based updates when the user stops moving, you optimize the application's performance and resource utilization.


229-237: Verify Null Handling for routeDuration and Consistency in Method Calls

In this call to saveCurrentJourney:

  • routeDuration is explicitly set to null.
  • createdAt and updatedAt are omitted.

Please verify:

  • That routeDuration being null is acceptable and won't cause issues when saving the journey.
  • The saveCurrentJourney method can handle these parameters being null or absent.
  • Consistency in parameter usage across all calls to saveCurrentJourney.

358-358: Verify Parameters for saveCurrentJourney Method

In this call, only fromLatitude and fromLongitude are provided. Ensure that:

  • The method can handle calls with only these parameters.
  • Any required parameters are either optional or have default values.
  • This won't lead to incomplete journey data being saved.
data/src/main/java/com/canopas/yourspace/data/service/location/LocationManager.kt (1)

78-80: ⚠️ Potential issue

Verify that request is always initialized before starting location tracking

While request is initialized in the init block, it's crucial to ensure that startLocationTracking() cannot be called before initialization. If there is any possibility of startLocationTracking() being invoked before the constructor completes, consider guarding against uninitialized access.

To verify, ensure that no code paths allow startLocationTracking() to be called before object initialization completes.

@@ -21,18 +22,20 @@ import javax.inject.Inject
import javax.inject.Singleton

private const val LOCATION_UPDATE_INTERVAL = 10000L
private const val MINIMUM_DISTANCE = 10f
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider making MINIMUM_DISTANCE configurable

The MINIMUM_DISTANCE constant is currently hardcoded to 10f. Making this value configurable or injecting it via the constructor can enhance the flexibility of the LocationManager, allowing different parts of the application to specify their desired minimum distance for location updates.

@cp-megh-l cp-megh-l marked this pull request as draft October 16, 2024 08:32
@cp-megh-l cp-megh-l changed the title Use accuracy to update location and update location builder based on user state Use accuracy before updating user's location Oct 16, 2024
@cp-megh-l cp-megh-l changed the title Use accuracy before updating user's location Check accuracy before updating user's location Oct 16, 2024
@cp-megh-l cp-megh-l marked this pull request as ready for review October 16, 2024 10:18
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (3)
data/src/main/java/com/canopas/yourspace/data/repository/JourneyRepository.kt (3)

42-44: LGTM: Improved steady location tracking

The addition of timer cancellation and restarting in saveLocationJourney enhances the accuracy of steady location tracking. This ensures that the timer is properly reset with each new location update.

Consider adding a brief comment explaining the purpose of the 5-minute timer for better code readability.


65-84: LGTM: Well-implemented steady location timer

The startSteadyLocationTimer method effectively implements the logic for detecting and handling steady locations. The use of coroutines for asynchronous saving and proper timer cancellation are good practices.

Consider adding a catch block to handle potential exceptions in the coroutine launch, ensuring that the timer is always cancelled even if an error occurs during the journey saving process.


146-149: LGTM: Improved day change handling in getLastKnownLocation

The addition of the day change check in getLastKnownLocation enhances the accuracy of location tracking across day boundaries. This prevents the use of outdated journey information when a new day has started.

Consider extracting the condition !isDayChanged(extractedLocation, it) into a well-named variable for improved readability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4132b4d and c2fdcc0.

📒 Files selected for processing (3)
  • data/src/main/java/com/canopas/yourspace/data/receiver/location/LocationUpdateReceiver.kt (1 hunks)
  • data/src/main/java/com/canopas/yourspace/data/repository/JourneyRepository.kt (9 hunks)
  • data/src/main/java/com/canopas/yourspace/data/service/location/LocationManager.kt (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • data/src/main/java/com/canopas/yourspace/data/receiver/location/LocationUpdateReceiver.kt
  • data/src/main/java/com/canopas/yourspace/data/service/location/LocationManager.kt
🧰 Additional context used
🔇 Additional comments (5)
data/src/main/java/com/canopas/yourspace/data/repository/JourneyRepository.kt (5)

12-15: LGTM: Improved asynchronous handling with CoroutineScope and Timer

The addition of CoroutineScope, Timer, and related imports, along with the new steadyLocationTimer property and scope, enhances the class's ability to manage asynchronous operations and timed tasks. This change allows for more efficient background processing and better control over location-related operations.

Also applies to: 18-19, 32-33


86-89: LGTM: Proper timer cancellation

The cancelSteadyLocationTimer method correctly cancels the timer and sets it to null, which is a good practice to prevent memory leaks and ensure the timer is properly cleaned up.


116-122: LGTM: Simplified journey saving process

The direct assignment of the saveCurrentJourney result to newJourneyId streamlines the code. The added comment provides helpful context for the parameter changes.

Regarding the past comment about inconsistent use of createdAt: This change addresses the inconsistency by removing createdAt and updatedAt parameters from saveCurrentJourney. This standardization improves code consistency across different calls to this method.


324-329: LGTM: Consistent use of createdAt in saveJourneyOnJourneyStopped

The addition of the createdAt parameter in the call to saveCurrentJourney ensures consistency in journey creation times. This change addresses the previous concern about inconsistent use of createdAt across different calls to saveCurrentJourney.

This improvement enhances the accuracy of journey timelines and resolves the inconsistency highlighted in the past review comment.


Line range hint 1-424: Overall: Significant improvements to JourneyRepository

The changes in this file have substantially improved the JourneyRepository class. Key enhancements include:

  1. Better asynchronous handling with CoroutineScope and Timer.
  2. Improved steady location tracking mechanism.
  3. More accurate day change handling in location journeys.
  4. Consistent use of creation times across journey saving methods.

These improvements enhance the reliability and accuracy of location tracking and journey management. The code is now more robust and consistent in its handling of various scenarios.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c2fdcc0 and 4eaf58c.

📒 Files selected for processing (3)
  • app/src/main/java/com/canopas/yourspace/domain/fcm/YourSpaceFcmService.kt (3 hunks)
  • data/src/main/java/com/canopas/yourspace/data/receiver/location/LocationUpdateReceiver.kt (1 hunks)
  • data/src/main/java/com/canopas/yourspace/data/repository/JourneyRepository.kt (10 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • data/src/main/java/com/canopas/yourspace/data/receiver/location/LocationUpdateReceiver.kt
  • data/src/main/java/com/canopas/yourspace/data/repository/JourneyRepository.kt
🧰 Additional context used

Comment on lines +88 to +89
@Inject
lateinit var locationCache: LocationCache
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider using constructor injection for dependencies.

Using constructor injection for locationCache and journeyRepository can improve testability and avoid the use of lateinit variables. This approach promotes immutability and makes the class easier to unit test.

Also applies to: 91-92

Comment on lines +164 to +170
scope.launch {
val extractedLocation = locationCache.getLastExtractedLocation(userId = authService.currentUser?.id ?: "")
extractedLocation?.let {
journeyRepository.saveLocationJourney(
extractedLocation,
authService.currentUser?.id ?: ""
)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Simplify null checks for authService.currentUser.

Since authService.currentUser is already verified to be non-null at the beginning of the function, you can safely access authService.currentUser.id without the safe-call operator and default value. This simplifies the code and avoids unnecessary null coalescing.

Apply this diff to simplify the code:

-            val extractedLocation = locationCache.getLastExtractedLocation(userId = authService.currentUser?.id ?: "")
+            val extractedLocation = locationCache.getLastExtractedLocation(userId = authService.currentUser.id)

And in the saveLocationJourney call:

-                    authService.currentUser?.id ?: ""
+                    authService.currentUser.id
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
scope.launch {
val extractedLocation = locationCache.getLastExtractedLocation(userId = authService.currentUser?.id ?: "")
extractedLocation?.let {
journeyRepository.saveLocationJourney(
extractedLocation,
authService.currentUser?.id ?: ""
)
scope.launch {
val extractedLocation = locationCache.getLastExtractedLocation(userId = authService.currentUser.id)
extractedLocation?.let {
journeyRepository.saveLocationJourney(
extractedLocation,
authService.currentUser.id
)

Comment on lines +164 to +172
scope.launch {
val extractedLocation = locationCache.getLastExtractedLocation(userId = authService.currentUser?.id ?: "")
extractedLocation?.let {
journeyRepository.saveLocationJourney(
extractedLocation,
authService.currentUser?.id ?: ""
)
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling within the coroutine.

Consider adding a try-catch block inside the coroutine to handle any potential exceptions from getLastExtractedLocation or saveLocationJourney. This ensures that unexpected errors do not crash the application and can be properly logged or managed.

Apply this diff to add error handling:

 scope.launch {
+    try {
         val extractedLocation = locationCache.getLastExtractedLocation(userId = authService.currentUser.id)
         extractedLocation?.let {
             journeyRepository.saveLocationJourney(
                 extractedLocation,
                 authService.currentUser.id
             )
         }
+    } catch (e: Exception) {
+        Timber.e(e, "Error updating location journey")
+    }
 }

Committable suggestion was skipped due to low confidence.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant