Repository navigation
feat: geo block piggycards for Russia and Cuba - #1456
Conversation
|
Warning Rate limit exceeded
⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughAdds IP- and GPS-based country detection and observation, exposes country info via NetworkState and UserLocationState APIs, integrates location-derived exclude-provider filtering into merchant flows, updates utilities, permissions, logging, and tests for location-aware behavior. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant ExploreViewModel
participant GPS as "GPS Location Service"
participant IP as "IP API Service"
participant DataSource
participant DB as "Merchant DB"
User->>ExploreViewModel: open Explore screen
ExploreViewModel->>GPS: getCountryCodeFromLocation()
GPS-->>ExploreViewModel: countryCode (GPS)
par IP lookup
ExploreViewModel->>IP: getCountryCodeFromIP()
IP-->>ExploreViewModel: countryCode (IP)
end
ExploreViewModel->>ExploreViewModel: combine GPS & IP -> location StateFlow
ExploreViewModel->>DataSource: observePhysicalMerchants(excludeProvider)
DataSource->>DB: query merchants
DB-->>DataSource: merchant list
DataSource->>DataSource: filter merchants by excludeProvider
DataSource-->>ExploreViewModel: filtered merchants
ExploreViewModel-->>User: display merchants
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 8
🤖 Fix all issues with AI agents
In `@common/src/main/java/org/dash/wallet/common/util/Networks.kt`:
- Around line 64-66: The current extraction uses gson.fromJson(...,
Map::class.java) and returns mapper["countryCode"] as String which can throw NPE
or ClassCastException if missing or not a string; update the logic in
Networks.kt to safely read the value (e.g., val mapper = gson.fromJson(...) as?
Map<*,*>?), then val country = mapper?.get("countryCode") as? String ?: "" (or
return null/optional) and return that safe value, or log/handle the
absent/non-string case accordingly; ensure you avoid unchecked casts and handle
body?.string() being null as well.
- Around line 55-71: The getCountryCodeFromIP() function currently calls the
insecure HTTP endpoint; update the Request.Builder URL in getCountryCodeFromIP()
to use the HTTPS endpoint "https://ipapi.co/json/" (or another HTTPS provider)
and adjust the JSON parsing to read the provider's country code key (e.g.,
"country_code" for ipapi.co) instead of "countryCode". Ensure
HTTP_CLIENT.call(request) and response.ensureSuccessful() usage remains, handle
nullable body safely, and return the mapped country code string (or empty string
on error) in the same catch block.
In
`@features/exploredash/src/main/java/org/dash/wallet/features/exploredash/data/explore/ExploreDataSource.kt`:
- Around line 171-182: The current filter in ExploreDataSource uses
giftCardProviderDao.getProvidersByMerchantId(id) inside baseFlow.map which
causes an N+1 query pattern; replace this by pre-fetching provider associations
for all merchants in the flow (or adding a JOIN-based exclusion query on
MerchantDao) and then perform in-memory filtering: inside the baseFlow.map,
collect merchantIds from merchants, call a new DAO method (e.g.,
giftCardProviderDao.getProvidersForMerchants(merchantIds)) to get all providers
in one query and groupBy merchantId, then filter merchants by checking the
grouped providers for the excludeProvider (case-insensitive) instead of calling
getProvidersByMerchantId per merchant; alternatively implement a single SQL
query in MerchantDao that excludes merchants by provider to avoid in-memory
filtering.
In
`@features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/explore/ExploreViewModel.kt`:
- Around line 741-755: The current per-merchant call to
exploreData.getGiftCardProvidersFor(id) inside the lambda causes N+1 queries;
instead, before filtering the paged list (the code using getExcludeProvider()
and filtering "data"), collect all merchant IDs from data and call a new or
existing batch method on ExploreData (e.g.,
exploreData.getGiftCardProvidersFor(ids: List<String>) or
getGiftCardProvidersForMerchantIds) to return a Map<merchantId, List<Provider>>;
then replace the per-merchant lookup with a single map lookup (use
providersMap[merchantId]) and apply the same "any {
!it.provider.equals(excludeProvider, ignoreCase = true) }" logic. Alternatively,
if feasible, move this exclude-provider logic into the SQL layer (ExploreData
DAO) to avoid post-fetch filtering entirely.
- Around line 272-276: The catch blocks in ExploreViewModel (around the location
retrieval that currently do "catch (e: SecurityException) { emit(null) }" and
"catch (e: Exception) { emit(null) }") swallow exceptions; keep the current
behavior of emitting null but also log the caught exception (using the project's
logger—e.g., Log.w/Log.d, Timber.w, or the class' logger) with a brief message
indicating location permission/gps failure and include the exception instance so
stacktrace/details are retained for debugging.
- Around line 638-649: The updateSelectedItem function currently mutates the
Merchant instance by assigning a filtered list to item.giftCardProviders;
instead create a new Merchant copy (use the existing deepCopy() method) with
giftCardProviders replaced by the filtered list (apply getExcludeProvider() and
the same ignoreCase filter) and set _selectedItem.value to that copy so the
original paged/listed Merchant instance is not mutated.
In
`@features/exploredash/src/main/java/org/dash/wallet/features/exploredash/utils/Location.kt`:
- Around line 33-49: The current fused.lastLocation success listener calls
Geocoder.getFromLocation on the main thread and resumes the coroutine without
checking for cancellation or IO errors; update the location lookup so the
Geocoder call runs on Dispatchers.IO (e.g., use withContext(Dispatchers.IO)),
first check Geocoder.isPresent(), wrap getFromLocation in try/catch for
IOException (and other exceptions), and only call continuation.resume(...) if
continuation.isActive; similarly ensure failure listeners also check
continuation.isActive before resuming and surface an empty result on errors or
missing geocoder.
In `@wallet/src/de/schildbach/wallet/service/NetworkState.kt`:
- Around line 67-76: The init block currently calls getCountryCodeFromIP() and
the connectivityManagerCallback's onAvailable also calls getCountryCodeFromIP(),
causing duplicate lookups on startup; to fix, remove the country.value =
getCountryCodeFromIP() invocation from the init block (or add a guard that
checks isConnected.value or a boolean like countryLoaded before launching) so
only the connectivityManagerCallback.onAvailable() performs the network lookup,
referencing init, connectivityManagerCallback, onAvailable, and
getCountryCodeFromIP() to locate the change.
🧹 Nitpick comments (5)
features/exploredash/src/main/AndroidManifest.xml (1)
3-4: Verify runtime permission flow and compliance; consider avoiding fine location.Adding coarse/fine location is a sensitive change. Please confirm runtime permission requests and rationale UI are in place to avoid
SecurityException, and that privacy policy/Data Safety disclosures were updated. If you only need country-level detection, consider dropping fine location to reduce privacy exposure.Optional minimization (if fine location isn’t required)
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/explore/ExploreViewModel.kt (2)
258-258: Consider extracting hardcoded country codes to a constants file.The excluded countries list
listOf("RU", "CU")is hardcoded. For compliance-related configurations that may need updates, consider:
- Moving to a dedicated constants/config file for easier auditing
- Adding a code comment documenting the regulatory reason for these exclusions
302-308: Consider centralizing provider filtering logic.The
getExcludeProvider()helper is called and filtering is applied in multiple places:
openMerchantDetails(lines 512-518)updateSelectedItem(lines 639-648)getBoundedFlow(lines 691-692)getPagingFlow(lines 741-755)Consider extracting a single helper function like
filterExcludedProviders(providers: List<GiftCardProvider>)to reduce duplication and ensure consistent filtering behavior.common/src/main/java/org/dash/wallet/common/util/Networks.kt (1)
55-56: Consider wrapping inwithContext(Dispatchers.IO)for consistency.Unlike
getPublicIPAddress(), this function doesn't wrap the network call inwithContext(Dispatchers.IO). While callers currently launch on IO dispatcher, adding the context wrapper would make this function safe to call from any dispatcher.Suggested change
-suspend fun getCountryCodeFromIP(): String { +suspend fun getCountryCodeFromIP(): String = withContext(Dispatchers.IO) { try { val request = Request.Builder() .url("http://ip-api.com/json/?fields=status,message,countryCode") .build() val response = HTTP_CLIENT.call(request) response.ensureSuccessful() val body = response.body val gson = Gson() - val mapper = gson.fromJson(body?.string() ?: "", Map::class.java) - return mapper["countryCode"] as String + val mapper = gson.fromJson(body?.string() ?: "", Map::class.java) + mapper?.get("countryCode") as? String ?: "" } catch (e: Exception) { log.error("error obtaining country code for this IP", e) - return "" + "" } }wallet/src/de/schildbach/wallet/service/NetworkState.kt (1)
47-54: Consider rate-limiting country code lookups.The
onAvailablecallback fires on every network change, which could rapidly consume API rate limits (ip-api.com allows ~45 requests/minute on free tier). Consider debouncing or tracking the last successful lookup to avoid redundant calls.Example debounce approach
private var lastCountryLookup = 0L private val LOOKUP_DEBOUNCE_MS = 60_000L // 1 minute override fun onAvailable(network: Network) { super.onAvailable(network) isConnected.value = true val now = System.currentTimeMillis() if (now - lastCountryLookup > LOOKUP_DEBOUNCE_MS) { lastCountryLookup = now scope.launch { country.value = getCountryCodeFromIP() } } }
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In
`@features/exploredash/src/main/java/org/dash/wallet/features/exploredash/services/UserLocationState.kt`:
- Around line 189-205: The getCountryCodeFromLocation() implementation must be
refactored to perform the blocking Geocoder.getFromLocation(...) on the IO
dispatcher and to await the location Task with Tasks.await() for proper
exception propagation; replace the addOnSuccessListener/addOnFailureListener
pattern on client.lastLocation with a suspend call that uses
withContext(Dispatchers.IO) { val location = Tasks.await(client.lastLocation)
... } and wrap the Geocoder call (new Geocoder(context,
GenericUtils.getDeviceLocale()).getFromLocation(...)) in try/catch so any
exceptions result in returning an empty string; ensure the method no longer uses
addOnSuccessListener/addOnFailureListener and still returns "" when location is
null or on error.
♻️ Duplicate comments (3)
features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/explore/ExploreViewModel.kt (3)
636-645: Avoid mutatingMerchantin-place when filtering providers.Directly mutating
item.giftCardProviderscan leak into other references (e.g., cached lists). Prefer making a copy and assigning it to_selectedItem.♻️ Suggested refactor
fun updateSelectedItem(item: SearchResult) { // Filter providers if it's a merchant if (item is Merchant && item.giftCardProviders.isNotEmpty()) { val excludeProvider = getExcludeProvider() if (excludeProvider.isNotBlank()) { - item.giftCardProviders = item.giftCardProviders.filter { - !it.provider.equals(excludeProvider, ignoreCase = true) - } + val filtered = item.giftCardProviders.filter { + !it.provider.equals(excludeProvider, ignoreCase = true) + } + _selectedItem.value = item.deepCopy(giftCardProviders = filtered) + return } } _selectedItem.value = item }
270-274: Log GPS/IP exceptions before emitting null.Right now exceptions are swallowed; adding debug/warn logs will help troubleshoot location failures without changing control flow.
🔧 Suggested fix
- } catch (e: SecurityException) { - emit(null) // Location permissions not granted - } catch (e: Exception) { - emit(null) // GPS location failed - } + } catch (e: SecurityException) { + log.debug("Location permissions not granted", e) + emit(null) // Location permissions not granted + } catch (e: Exception) { + log.warn("GPS location failed", e) + emit(null) // GPS location failed + }
739-753: Avoid per-merchant provider lookup in paging (N+1).Each merchant triggers
getGiftCardProvidersFor(id)during paging, which scales poorly and can add latency. Consider batching provider lookups for the page (map by merchantId) or moving the exclusion into the DAO query.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In
`@features/exploredash/src/main/java/org/dash/wallet/features/exploredash/services/UserLocationState.kt`:
- Around line 196-207: The suspension block should capture the location Task
once instead of calling client.lastLocation twice; create a single val task =
client.lastLocation and attach addOnSuccessListener and addOnFailureListener to
that task so both listeners operate on the same Task instance, then inside
addOnSuccessListener resume the continuation with Geocoder(context,
GenericUtils.getDeviceLocale()).getFromLocation(location.latitude,
location.longitude, 1)?.firstOrNull()?.countryCode ?: "" (or "" if location is
null) and in addOnFailureListener resume with ""; ensure you still reference
continuation and Geocoder exactly as in the current logic.
♻️ Duplicate comments (1)
features/exploredash/src/main/java/org/dash/wallet/features/exploredash/services/UserLocationState.kt (1)
198-201: Move Geocoder work off the main thread and catch exceptions.Line 199–201 calls
Geocoder.getFromLocation()on the main thread viaaddOnSuccessListenerand without try/catch, risking ANRs or crashes. PreferwithContext(Dispatchers.IO)+tasks.await()and wrap the geocoder call.🔧 Suggested replacement
- override suspend fun getCountryCodeFromLocation(): String { - return suspendCancellableCoroutine { continuation -> - client.lastLocation.addOnSuccessListener { location -> - if (location != null) { - val geocoder = Geocoder(context, GenericUtils.getDeviceLocale()) - val results = geocoder.getFromLocation(location.latitude, location.longitude, 1) - continuation.resume(results?.firstOrNull()?.countryCode ?: "") - } else { - continuation.resume("") - } - } - client.lastLocation.addOnFailureListener { - continuation.resume("") - } - } - } + override suspend fun getCountryCodeFromLocation(): String = withContext(Dispatchers.IO) { + try { + val location = client.lastLocation.await() ?: return@withContext "" + val geocoder = Geocoder(context, GenericUtils.getDeviceLocale()) + geocoder.getFromLocation(location.latitude, location.longitude, 1) + ?.firstOrNull() + ?.countryCode + .orEmpty() + } catch (e: Exception) { + log.info("GeocoderException ${e.message}") + "" + } + }
🧹 Nitpick comments (1)
features/exploredash/src/main/java/org/dash/wallet/features/exploredash/services/UserLocationState.kt (1)
212-226: Remove the commented-out alternative implementation.The commented block and TODO add noise and can confuse future edits. Prefer deleting it or tracking the alternative in an issue.
🧹 Cleanup
- // TODO: this doesn't give the country name, though it doesn't use callbacks -// `@RequiresPermission`(anyOf = [Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION]) -// override suspend fun getCountryCodeFromLocation(): String = withContext(Dispatchers.IO) { -// try { -// val location = client.lastLocation.await() ?: return@withContext "" -// val geocoder = Geocoder(context, GenericUtils.getDeviceLocale()) -// geocoder.getFromLocation(location.latitude, location.longitude, 1) -// ?.firstOrNull() -// ?.countryCode -// .orEmpty() -// } catch (e: Exception) { -// log.info("GeocoderException ${e.message}") -// "" -// } -// }
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In
`@features/exploredash/src/main/java/org/dash/wallet/features/exploredash/services/UserLocationState.kt`:
- Around line 196-198: Wrap the Geocoder.getFromLocation(...) call inside a
try-catch in the same suspend/resume block so exceptions don't escape; catch
IOException and IllegalArgumentException (or a general Exception) around the
call in UserLocationState.kt and on exception resume the Continuation with an
empty string (as done in getCurrentLocationAddress()) and ensure resume is only
called once (use continuation.resume or continuation.resumeWith as appropriate).
This change should be applied where geocoder is created and results are resumed
to prevent coroutine crashes in the code path using Geocoder.getFromLocation.
♻️ Duplicate comments (1)
features/exploredash/src/main/java/org/dash/wallet/features/exploredash/services/UserLocationState.kt (1)
194-205: Captureclient.lastLocationonce before attaching both listeners.Lines 194 and 203 call
client.lastLocationseparately, which may return different Task instances. Capture the Task once for consistency.🔧 Proposed fix
`@RequiresPermission`(anyOf = [Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION]) override suspend fun getCountryCodeFromLocation(): String { return suspendCancellableCoroutine { continuation -> - client.lastLocation.addOnSuccessListener { location -> + val task = client.lastLocation + task.addOnSuccessListener { location -> if (location != null) { val geocoder = Geocoder(context, GenericUtils.getDeviceLocale()) val results = geocoder.getFromLocation(location.latitude, location.longitude, 1) continuation.resume(results?.firstOrNull()?.countryCode ?: "") } else { continuation.resume("") } } - client.lastLocation.addOnFailureListener { + task.addOnFailureListener { continuation.resume("") } } }
🧹 Nitpick comments (1)
features/exploredash/src/main/java/org/dash/wallet/features/exploredash/services/UserLocationState.kt (1)
209-223: Consider removing or documenting the commented-out alternative.This commented block serves as documentation for why the callback approach was chosen. Consider either:
- Removing it entirely if the reasoning is documented elsewhere
- Converting the TODO to a KDoc comment on the function explaining why callbacks are used instead of
Tasks.await()
Issue being fixed or feature implemented
Related PR's and Dependencies
Screenshots / Videos
How Has This Been Tested?
Checklist:
Summary by CodeRabbit
New Features
Permissions
Behavior Changes
Bug Fixes / Privacy
Tests
✏️ Tip: You can customize this high-level summary in your review settings.