new app: taxi
- Commit
e0bdc915fadde5563b3d40f0cfd9f764f5b33d24- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-08 01:27 UTC (4 months ago)
- Parents
e141291
Diff
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 7949e17225..a79b4ccf91 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -90,6 +90,7 @@ include(":appstore") include(":fooddelivery") include(":musicbrainz") include(":measure")+include(":taxi") // Personal / private app modules live under personal/ (gitignored). Included only // when present so the public repo still configures without them.@@ -102,6 +103,3 @@ if (file("personal/amazon").exists()) { if (file("personal/kaiser").exists()) { include(":personal:kaiser") }-if (file("personal/taxi").exists()) {- include(":personal:taxi")-}
taxi/build.gradle.kts
diff --git a/taxi/build.gradle.kts b/taxi/build.gradle.ktsnew file mode 100644index 0000000000..b506d45a5f--- /dev/null+++ b/taxi/build.gradle.kts@@ -0,0 +1,22 @@+plugins {+ id("common-conventions-app")+}++launcherIcon {+ symbol = "local_taxi"+}++android {+ defaultConfig {+ applicationId = "com.vayunmathur.taxi"+ }+}++dependencies {+ implementation(project(":library:network"))+ implementation(project(":library:map"))+ implementation(project(":library:image"))+ implementation(libs.kotlinx.serialization.json)+ implementation(libs.androidx.datastore.preferences)+ implementation(libs.kotlinx.coroutines.android)+}
taxi/src/main/AndroidManifest.xml
diff --git a/taxi/src/main/AndroidManifest.xml b/taxi/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..8b60c37ba9--- /dev/null+++ b/taxi/src/main/AndroidManifest.xml@@ -0,0 +1,36 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <uses-permission android:name="android.permission.INTERNET" />+ <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />++ <!-- Package visibility: without these the deep-link handoff cannot resolve+ the official apps and silently falls back to the browser. -->+ <queries>+ <package android:name="com.ubercab" />+ <package android:name="me.lyft.android" />+ </queries>++ <application+ android:allowBackup="false"+ android:dataExtractionRules="@xml/data_extraction_rules"+ android:icon="@mipmap/ic_launcher"+ android:roundIcon="@mipmap/ic_launcher"+ android:label="@string/app_name"+ android:supportsRtl="true"+ android:theme="@style/Theme.General">++ <activity+ android:name=".MainActivity"+ android:exported="true"+ android:windowSoftInputMode="adjustResize"+ android:theme="@style/Theme.General">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ </activity>+ </application>++</manifest>
taxi/src/main/java/com/vayunmathur/taxi/MainActivity.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/MainActivity.kt b/taxi/src/main/java/com/vayunmathur/taxi/MainActivity.ktnew file mode 100644index 0000000000..4f39ae9cc4--- /dev/null+++ b/taxi/src/main/java/com/vayunmathur/taxi/MainActivity.kt@@ -0,0 +1,71 @@+package com.vayunmathur.taxi++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.compose.runtime.Composable+import androidx.compose.ui.res.stringResource+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.TrustBundle+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.IconMap+import com.vayunmathur.library.ui.IconNavigationArrow+import com.vayunmathur.library.ui.IconSettings+import com.vayunmathur.library.util.BottomBarItem+import com.vayunmathur.library.util.BottomNavBar+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.NavKey+import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.taxi.ui.AccountsScreen+import com.vayunmathur.taxi.ui.CurrentRideScreen+import com.vayunmathur.taxi.ui.LyftSignInScreen+import com.vayunmathur.taxi.ui.RideScreen+import kotlinx.serialization.Serializable++sealed interface Route : NavKey {+ @Serializable data object Ride : Route+ @Serializable data object CurrentRide : Route+ @Serializable data object Accounts : Route+ @Serializable data object LyftSignIn : Route+}++class MainActivity : ComponentActivity() {+ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ NetworkClient.init(this, TrustBundle.STANDARD)+ enableEdgeToEdge()++ setContent {+ DynamicTheme {+ TaxiApp()+ }+ }+ }+}++@Composable+private fun TaxiApp() {+ val backStack = rememberNavBackStack<Route>(Route.Ride)+ val currentPage = backStack.backStack.last()++ val pages = listOf(+ BottomBarItem(stringResource(R.string.nav_ride), Route.Ride) { IconMap() },+ BottomBarItem(stringResource(R.string.nav_current_ride), Route.CurrentRide) { IconNavigationArrow() },+ BottomBarItem(stringResource(R.string.nav_settings), Route.Accounts) { IconSettings() },+ )++ MainNavigation(+ backStack = backStack,+ bottomBar = { BottomNavBar(backStack, pages, currentPage) },+ ) {+ entry<Route.Ride> { RideScreen() }+ entry<Route.CurrentRide> { CurrentRideScreen() }+ entry<Route.Accounts> {+ AccountsScreen(+ onConnectLyft = { backStack.add(Route.LyftSignIn) },+ )+ }+ entry<Route.LyftSignIn> { LyftSignInScreen(onBack = { backStack.pop() }) }+ }+}
taxi/src/main/java/com/vayunmathur/taxi/data/Models.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/data/Models.kt b/taxi/src/main/java/com/vayunmathur/taxi/data/Models.ktnew file mode 100644index 0000000000..a434e0d251--- /dev/null+++ b/taxi/src/main/java/com/vayunmathur/taxi/data/Models.kt@@ -0,0 +1,269 @@+package com.vayunmathur.taxi.data++data class LatLng(+ val latitude: Double,+ val longitude: Double,+)++data class Place(+ val name: String,+ val address: String?,+ val location: LatLng,+)++enum class Provider(val label: String, val packageName: String) {+ UBER("Uber", "com.ubercab"),+ LYFT("Lyft", "me.lyft.android"),+}++/**+ * A bookable option from one provider. Fares are in minor currency units so the two+ * providers stay comparable without float rounding; [fareLowMinor] equals [fareHighMinor]+ * when the provider quotes an exact price rather than a range.+ *+ * The trailing [offerId]/[offerToken]/[costToken]/[rideType]/[costTokenExpiryMs] fields carry+ * the tokens an in-app booking needs. They are populated only for providers that support+ * in-app booking (Lyft) and stay null everywhere else, so quote-only and deep-link paths are+ * unaffected. The cost token expires (see [costTokenExpiryMs]); a stale token must be+ * re-quoted before booking.+ */+data class RideQuote(+ val provider: Provider,+ val productId: String,+ val displayName: String,+ val fareLowMinor: Long,+ val fareHighMinor: Long,+ val currency: String,+ val pickupEtaMinutes: Int?,+ val tripDurationMinutes: Int?,+ val surgeMultiplier: Double?,+ val capacity: Int?,+ val offerId: String? = null,+ val offerToken: String? = null,+ val costToken: String? = null,+ val rideType: String? = null,+ val costTokenExpiryMs: Long? = null,+) {+ val isRange: Boolean get() = fareLowMinor != fareHighMinor+}++sealed interface QuoteResult {+ /**+ * [purchaseSessionId] and [offersResponseId] are response-level identifiers from the offers+ * call, reused when creating a ride so the server can deduplicate a retried booking (see+ * `DuplicatedRideRequestException` in the API notes). Null for providers that do not return+ * them.+ */+ data class Success(+ val quotes: List<RideQuote>,+ val purchaseSessionId: String? = null,+ val offersResponseId: String? = null,+ ) : QuoteResult++ /** The provider is reachable but we are not signed in to it. */+ data object NotSignedIn : QuoteResult++ data class Failed(val message: String) : QuoteResult+}++/**+ * A Lyft payment method, fetched live and held only in memory — never persisted. [id] is the+ * charge-account id; [chargeToken] is the token the booking request passes when this account is+ * the one being charged (may be null when the account id alone is used). [label] is a+ * display string such as "Visa ••1234".+ */+data class ChargeAccount(+ val id: String,+ val chargeToken: String?,+ val label: String,+ val isDefault: Boolean,+)++/** Result of fetching a provider's payment methods (in-memory, never persisted). */+sealed interface PaymentMethodsResult {+ data class Success(val accounts: List<ChargeAccount>) : PaymentMethodsResult++ data object NotSignedIn : PaymentMethodsResult++ data class Failed(val message: String) : PaymentMethodsResult++ /** The provider does not support in-app payment management. */+ data object Unsupported : PaymentMethodsResult+}++/** Result of a payment-method mutation (set default / remove). */+sealed interface PaymentActionResult {+ /** [accounts] is the refreshed list when the server returned one, else null. */+ data class Success(val accounts: List<ChargeAccount>?) : PaymentActionResult++ data class Failed(val message: String) : PaymentActionResult++ data object Unsupported : PaymentActionResult+}++/**+ * A raw card the user typed in, held only in memory for the duration of an add-card call and+ * never persisted or logged in full. [number] and [cvc] leave the process only as a processor+ * token/nonce (Stripe/Braintree), never as-is to Lyft.+ */+data class NewCard(+ val number: String,+ val expMonth: Int,+ val expYear: Int,+ val cvc: String,+ val postalCode: String,+) {+ /** Last four digits — safe to display/log. */+ val last4: String get() = number.takeLast(4)++ /** Issuer identification number (leading digits) — used to pick a tokenizer strategy. */+ val bin: String get() = number.take(8)+}++/** Result of adding a card. Mirrors [PaymentActionResult]; [accounts] is the refreshed list. */+sealed interface AddCardResult {+ data class Success(val accounts: List<ChargeAccount>?) : AddCardResult++ data class Failed(val message: String) : AddCardResult++ data object Unsupported : AddCardResult+}++/**+ * Result of creating a ride. [DryRun] carries the exact request that *would* be sent so the UI+ * and logs can verify it against a real capture before any live send — no charge occurs.+ */+sealed interface BookingResult {+ data class DryRun(val requestJson: String, val account: ChargeAccount?) : BookingResult++ data class Created(val rideId: String?, val status: String?, val raw: String) : BookingResult++ data class Failed(val message: String) : BookingResult++ data object Unsupported : BookingResult+}++/** The driver's live position on the map. [bearing] is degrees clockwise from north, if known. */+data class DriverLocation(+ val latitude: Double,+ val longitude: Double,+ val bearing: Double?,+)++/** The assigned driver. All fields are optional — the server omits what it hasn't populated yet. */+data class DriverInfo(+ val firstName: String?,+ val lastName: String?,+ val imageUrl: String?,+ val phoneNumber: String?,+ val rating: Double?,+) {+ /** First + last name joined; blank when the server hasn't sent a name yet. */+ val displayName: String+ get() = listOfNotNull(firstName, lastName).joinToString(" ").trim()+}++/** The assigned vehicle. */+data class VehicleInfo(+ val make: String?,+ val model: String?,+ val color: String?,+ val licensePlate: String?,+ val imageUrl: String?,+) {+ /** "Color Make Model", omitting whatever is missing; blank when nothing is known. */+ val description: String+ get() = listOfNotNull(color, make, model).joinToString(" ").trim()+}++/** A pickup / waypoint / dropoff stop on the ride, with the live per-stop ETA when present. */+data class RideStopInfo(+ val location: LatLng?,+ val name: String?,+ val kind: String?,+ val etaSeconds: Int?,+ val completed: Boolean,+) {+ val isPickup: Boolean get() = kind?.equals("pickup", ignoreCase = true) == true+ val isDropoff: Boolean get() = kind?.equals("dropoff", ignoreCase = true) == true+}++/**+ * The lifecycle state of a ride (`PassengerRideStatus`). [fromWire] maps the server's string onto+ * this enum, falling back to [UNKNOWN] for anything unrecognised.+ */+enum class RideStatus(val wire: String) {+ IDLE("idle"),+ LAPSED("lapsed"),+ PENDING("pending"),+ ACCEPTED("accepted"),+ APPROACHING("approaching"),+ CANCELED("canceled"),+ ARRIVED("arrived"),+ PICKED_UP("pickedUp"),+ DROPPED_OFF("droppedOff"),+ COMPLETED("completed"),+ PROCESSED("processed"),+ UNKNOWN("");++ /** Driver assigned and on the way to the pickup, but the rider isn't in the car yet. */+ val isPrePickup: Boolean get() = this == PENDING || this == ACCEPTED || this == APPROACHING || this == ARRIVED++ /** The ride has finished (or was cancelled) — polling should stop. */+ val isTerminal: Boolean get() = this == DROPPED_OFF || this == COMPLETED || this == PROCESSED || this == CANCELED++ /** There is a live ride worth tracking (pre-pickup or in-trip). */+ val isActive: Boolean get() = isPrePickup || this == PICKED_UP++ companion object {+ fun fromWire(raw: String?): RideStatus {+ if (raw.isNullOrBlank()) return UNKNOWN+ return entries.firstOrNull { it.wire.equals(raw, ignoreCase = true) } ?: UNKNOWN+ }+ }+}++/**+ * A ride in progress, parsed from `PassengerRide`. [driverLocation] is the live driver position;+ * [stops] carries per-stop ETAs. [raw] is a truncated copy of the response for display/debugging.+ */+data class ActiveRide(+ val rideId: String?,+ val status: RideStatus,+ val statusRaw: String?,+ val driver: DriverInfo?,+ val vehicle: VehicleInfo?,+ val driverLocation: DriverLocation?,+ val stops: List<RideStopInfo>,+ val raw: String,+) {+ /** Live "N seconds away" from the pickup stop, or the first stop still incomplete. */+ val pickupEtaSeconds: Int?+ get() = stops.firstOrNull { it.isPickup && !it.completed }?.etaSeconds+ ?: stops.firstOrNull { !it.completed }?.etaSeconds++ /** True when the ride carries enough to be worth surfacing (id, known status, or a driver). */+ val hasContent: Boolean+ get() = rideId != null || status != RideStatus.UNKNOWN || driverLocation != null || driver != null+}++/** Result of reading the active ride. */+sealed interface RideStatusResult {+ data class Active(val ride: ActiveRide) : RideStatusResult++ /** No ride in progress. */+ data object None : RideStatusResult++ data class Failed(val message: String) : RideStatusResult++ data object Unsupported : RideStatusResult+}++/** Result of a cancel request. Server response is surfaced verbatim — a cancel may incur a fee. */+sealed interface CancelResult {+ data class Done(val message: String) : CancelResult++ data class Failed(val message: String) : CancelResult++ data object Unsupported : CancelResult+}
taxi/src/main/java/com/vayunmathur/taxi/deeplink/RideDeepLinks.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/deeplink/RideDeepLinks.kt b/taxi/src/main/java/com/vayunmathur/taxi/deeplink/RideDeepLinks.ktnew file mode 100644index 0000000000..9c7c4c6bba--- /dev/null+++ b/taxi/src/main/java/com/vayunmathur/taxi/deeplink/RideDeepLinks.kt@@ -0,0 +1,89 @@+package com.vayunmathur.taxi.deeplink++import android.content.Context+import android.content.Intent+import androidx.core.net.toUri+import com.vayunmathur.taxi.data.Place+import com.vayunmathur.taxi.data.Provider+import com.vayunmathur.taxi.data.RideQuote++/**+ * Builds the "open the provider with this trip pre-filled" links.+ *+ * Parameter names were read as string literals out of each production APK — see+ * `uber-re/api-notes.md` §5 and `lyft-re/api-notes.md`. The one exception is Lyft's `id`+ * (ride type), which comes from Lyft's published deep-link format rather than a literal we+ * recovered, so a wrong value degrades to "no ride type preselected" rather than a broken link.+ *+ * Web URLs are the default because the target device is degoogled and will not have the+ * official apps installed; [openBooking] upgrades to the app scheme only when the package+ * actually resolves.+ */+object RideDeepLinks {++ fun webUri(provider: Provider, pickup: Place, dropoff: Place, quote: RideQuote?): String =+ when (provider) {+ Provider.UBER -> uber(base = "https://m.uber.com/ul/", pickup, dropoff, quote)+ Provider.LYFT -> lyft(base = "https://lyft.com/ride", pickup, dropoff, quote)+ }++ fun appUri(provider: Provider, pickup: Place, dropoff: Place, quote: RideQuote?): String =+ when (provider) {+ Provider.UBER -> uber(base = "uber://", pickup, dropoff, quote)+ Provider.LYFT -> lyft(base = "lyft://ridetype", pickup, dropoff, quote)+ }++ private fun uber(base: String, pickup: Place, dropoff: Place, quote: RideQuote?): String =+ base.toUri().buildUpon().apply {+ appendQueryParameter("action", "setPickup")+ appendQueryParameter("pickup[latitude]", pickup.location.latitude.toString())+ appendQueryParameter("pickup[longitude]", pickup.location.longitude.toString())+ appendQueryParameter("pickup[nickname]", pickup.name)+ appendQueryParameter("dropoff[latitude]", dropoff.location.latitude.toString())+ appendQueryParameter("dropoff[longitude]", dropoff.location.longitude.toString())+ appendQueryParameter("dropoff[nickname]", dropoff.name)+ quote?.let { appendQueryParameter("product_id", it.productId) }+ }.build().toString()++ private fun lyft(base: String, pickup: Place, dropoff: Place, quote: RideQuote?): String =+ base.toUri().buildUpon().apply {+ appendQueryParameter("id", quote?.productId ?: "lyft")+ appendQueryParameter("pickup[latitude]", pickup.location.latitude.toString())+ appendQueryParameter("pickup[longitude]", pickup.location.longitude.toString())+ pickup.address?.let { appendQueryParameter("pickup[address]", it) }+ appendQueryParameter("destination[latitude]", dropoff.location.latitude.toString())+ appendQueryParameter("destination[longitude]", dropoff.location.longitude.toString())+ dropoff.address?.let { appendQueryParameter("destination[address]", it) }+ }.build().toString()++ /**+ * Opens the trip in the official app when it is installed, otherwise on the provider's+ * mobile web. Returns false when neither could be launched.+ */+ fun openBooking(+ context: Context,+ provider: Provider,+ pickup: Place,+ dropoff: Place,+ quote: RideQuote?,+ ): Boolean {+ val candidates = buildList {+ if (isInstalled(context, provider.packageName)) {+ add(appUri(provider, pickup, dropoff, quote))+ }+ add(webUri(provider, pickup, dropoff, quote))+ }+ for (uri in candidates) {+ val intent = Intent(Intent.ACTION_VIEW, uri.toUri())+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ if (runCatching { context.startActivity(intent) }.isSuccess) return true+ }+ return false+ }++ private fun isInstalled(context: Context, packageName: String): Boolean =+ runCatching {+ @Suppress("DEPRECATION")+ context.packageManager.getPackageInfo(packageName, 0)+ }.isSuccess+}
taxi/src/main/java/com/vayunmathur/taxi/location/LocationProvider.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/location/LocationProvider.kt b/taxi/src/main/java/com/vayunmathur/taxi/location/LocationProvider.ktnew file mode 100644index 0000000000..e745f89288--- /dev/null+++ b/taxi/src/main/java/com/vayunmathur/taxi/location/LocationProvider.kt@@ -0,0 +1,162 @@+package com.vayunmathur.taxi.location++import android.Manifest+import android.annotation.SuppressLint+import android.content.Context+import android.content.pm.PackageManager+import android.location.Geocoder+import android.location.LocationManager+import android.os.Build+import androidx.core.content.ContextCompat+import com.vayunmathur.taxi.data.LatLng+import com.vayunmathur.taxi.data.Place+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlinx.coroutines.withTimeoutOrNull+import kotlinx.coroutines.withContext+import java.util.Locale+import kotlin.coroutines.resume++/**+ * Location and geocoding on the platform APIs only — the target device is degoogled, so+ * `play-services-location` and the Places SDK are both unavailable.+ */+object LocationProvider {++ fun hasPermission(context: Context): Boolean =+ ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) ==+ PackageManager.PERMISSION_GRANTED ||+ ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) ==+ PackageManager.PERMISSION_GRANTED++ @SuppressLint("MissingPermission")+ suspend fun current(context: Context): LatLng? {+ if (!hasPermission(context)) return null+ val manager = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager+ ?: return null+ val providers = listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER)+ .filter { runCatching { manager.isProviderEnabled(it) }.getOrDefault(false) }+ // A recent cached fix is good enough to centre a map and anchor a pickup, and avoids+ // making the user wait on a GPS lock before they can see any prices.+ providers.firstNotNullOfOrNull { provider ->+ runCatching { manager.getLastKnownLocation(provider) }.getOrNull()+ }?.let { return LatLng(it.latitude, it.longitude) }++ val provider = providers.firstOrNull() ?: return null+ // Bounded: a live request that never gets a fix (indoors, no signal) must not suspend+ // the caller indefinitely, and the listener has to come off either way.+ return withTimeoutOrNull(LIVE_FIX_TIMEOUT_MS) {+ suspendCancellableCoroutine { cont ->+ val listener = object : android.location.LocationListener {+ override fun onLocationChanged(location: android.location.Location) {+ manager.removeUpdates(this)+ if (cont.isActive) cont.resume(LatLng(location.latitude, location.longitude))+ }+ }+ runCatching {+ manager.requestSingleUpdateCompat(provider, listener, context)+ }.onFailure {+ if (cont.isActive) cont.resume(null)+ }+ cont.invokeOnCancellation { runCatching { manager.removeUpdates(listener) } }+ }+ }+ }++ private const val LIVE_FIX_TIMEOUT_MS = 15_000L++ @SuppressLint("MissingPermission")+ private fun LocationManager.requestSingleUpdateCompat(+ provider: String,+ listener: android.location.LocationListener,+ context: Context,+ ) {+ requestLocationUpdates(provider, 0L, 0f, listener, context.mainLooper)+ }++ /**+ * Forward-geocodes a typed address. Returns an empty list when no geocoder backend answers.+ *+ * Deliberately does not gate on [Geocoder.isPresent] — it reports false on some degoogled+ * builds that nonetheless resolve fine, so we attempt the lookup and degrade on failure,+ * matching findfamily's `fetchAddress`.+ */+ suspend fun search(context: Context, query: String): List<Place> {+ if (query.isBlank()) return emptyList()+ val geocoder = Geocoder(context, Locale.getDefault())+ return withContext(Dispatchers.IO) {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ suspendCancellableCoroutine { cont ->+ // onError must be supplied: its default implementation is empty, so a+ // geocoder failure would otherwise leave this coroutine suspended forever.+ geocoder.getFromLocationName(+ query,+ 5,+ object : Geocoder.GeocodeListener {+ override fun onGeocode(addresses: MutableList<android.location.Address>) {+ if (cont.isActive) cont.resume(addresses.map { it.toPlace() })+ }++ override fun onError(errorMessage: String?) {+ if (cont.isActive) cont.resume(emptyList())+ }+ },+ )+ }+ } else {+ @Suppress("DEPRECATION")+ runCatching { geocoder.getFromLocationName(query, 5) }+ .getOrNull()+ ?.map { it.toPlace() }+ ?: emptyList()+ }+ }+ }++ suspend fun describe(context: Context, location: LatLng): Place {+ val fallback = Place("Current location", null, location)+ val geocoder = Geocoder(context, Locale.getDefault())+ return withContext(Dispatchers.IO) {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ suspendCancellableCoroutine { cont ->+ geocoder.getFromLocation(+ location.latitude,+ location.longitude,+ 1,+ object : Geocoder.GeocodeListener {+ override fun onGeocode(addresses: MutableList<android.location.Address>) {+ if (cont.isActive) {+ cont.resume(addresses.firstOrNull()?.toPlace() ?: fallback)+ }+ }++ override fun onError(errorMessage: String?) {+ if (cont.isActive) cont.resume(fallback)+ }+ },+ )+ }+ } else {+ @Suppress("DEPRECATION")+ runCatching {+ geocoder.getFromLocation(location.latitude, location.longitude, 1)+ }.getOrNull()?.firstOrNull()?.toPlace() ?: fallback+ }+ }+ }+}++private fun android.location.Address.toPlace(): Place {+ val line = (0..maxAddressLineIndex).mapNotNull { getAddressLine(it) }.firstOrNull()+ // Prefer a street address with the house number (subThoroughfare) so a pickup reads+ // "123 Main St" rather than just "Main St"; fall back to a POI/feature name when there+ // is no house number (typical of searched landmarks).+ val houseAndStreet = subThoroughfare?.let { house ->+ thoroughfare?.let { street -> "$house $street" }+ }+ return Place(+ name = houseAndStreet ?: featureName ?: thoroughfare ?: line ?: "Dropped pin",+ address = line,+ location = LatLng(latitude, longitude),+ )+}
taxi/src/main/java/com/vayunmathur/taxi/lyft/LyftAuth.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/lyft/LyftAuth.kt b/taxi/src/main/java/com/vayunmathur/taxi/lyft/LyftAuth.ktnew file mode 100644index 0000000000..6a7cf59af4--- /dev/null+++ b/taxi/src/main/java/com/vayunmathur/taxi/lyft/LyftAuth.kt@@ -0,0 +1,297 @@+package com.vayunmathur.taxi.lyft++import android.os.Build+import android.util.Base64+import android.util.Log+import com.vayunmathur.library.network.NetworkClient+import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import java.net.URLEncoder+import java.util.Locale+import java.util.UUID++@Serializable+data class LyftToken(+ @SerialName("access_token") val accessToken: String,+ @SerialName("token_type") val tokenType: String? = null,+ @SerialName("refresh_token") val refreshToken: String? = null,+ @SerialName("expires_in") val expiresIn: Long = 0,+ @SerialName("scope") val scope: String? = null,+ @SerialName("user_id") val userId: String? = null,+)++sealed interface LyftAuthResult {+ data class Success(val token: LyftToken) : LyftAuthResult++ /** Lyft wants a web challenge finished first; [url] comes from BrowserRedirectRequiredError. */+ data class NeedsWebChallenge(val url: String) : LyftAuthResult++ /**+ * Lyft recognised the number but wants a second factor before issuing a token — typically+ * `email_match` when signing in from an unrecognised device. [hint] is Lyft's masked value+ * (e.g. `v******t@u*c.edu`). Answered by resending the phone grant with the email filled in.+ */+ data class NeedsChallenge(+ val identifier: String,+ val hint: String?,+ val description: String?,+ ) : LyftAuthResult++ data class Failed(val code: String?, val message: String) : LyftAuthResult+}++/**+ * Lyft OAuth2, replicating the official app's phone + SMS flow.+ *+ * See `lyft-re/api-notes.md` §2. The client id/secret are string resources shipped in every copy+ * of the APK — they identify the app, not the user.+ */+object LyftAuth {+ private const val TAG = "LyftAuth"+ const val BASE = "https://api.lyft.com"++ private const val CLIENT_ID = "eSat7-iu9doM"+ private const val CLIENT_SECRET = "ZtvLDz0n1-kJVwkIvxC4iSJ0yMvJydPq"++ private const val GRANT_PHONE = "urn:lyft:oauth2:grant_type:phone"+ private const val GRANT_CLIENT = "client_credentials"++ /**+ * Token for the "logged out user", used to authorize pre-login calls such as+ * `/v1/phoneauth`.+ *+ * From `defpackage/o92.d()`: when there is no user session the app mints one with+ * `grant_type=client_credentials` against the same token endpoint (Basic client auth), then+ * `o92.c()` wraps it as `Bearer <token>` for outgoing requests. Basic auth is only ever sent+ * to `/oauth2/access_token` itself — sending it anywhere else yields `invalid_client`.+ */+ @Volatile+ private var cachedClientToken: String? = null++ private val json = Json { ignoreUnknownKeys = true; isLenient = true }++ /**+ * The app version we impersonate. Lyft maps the `invalid_client` OAuth error to the message+ * "this version of the Lyft app is no longer supported" (`auth_invalid_client_message`), so+ * this has to track a version the server still accepts.+ */+ private const val APP_VERSION = "2026.29.3.1785309574"++ /**+ * The subset of `defpackage/tmi.b()` we can reproduce without the app's internals.+ *+ * `tmi.a()` drops null/empty values, so the omitted headers (`x-session`, `x-carrier`,+ * `x-location`, `x-client-session-id`, `x-device-density`) are all optional by construction.+ * User-agent format is from `defpackage/i8g0.invoke()`:+ * `"%s:android:%s:%s".format(applicationIdForUserAgent, Build.VERSION.RELEASE, appVersion)`,+ * where `applicationIdForUserAgent` is `"lyft"` per `me.lyft.android.BuildConfig`.+ */+ internal fun commonHeaders(): Map<String, String> {+ val locale = Locale.getDefault()+ val model = Build.MODEL.uppercase(locale)+ val manufacturer = Build.MANUFACTURER.uppercase(locale)+ val device = if (model.startsWith(manufacturer)) Build.MODEL else "${Build.MANUFACTURER} ${Build.MODEL}"+ return buildMap {+ put("user-agent", "lyft:android:${Build.VERSION.RELEASE}:$APP_VERSION")+ put("user-device", device)+ put("x-design-id", "X")+ put("x-timestamp-ms", System.currentTimeMillis().toString())+ put("x-timestamp-source", "system")+ locale.language.takeIf { it.isNotBlank() }?.let { put("x-locale-language", it) }+ locale.country.takeIf { it.isNotBlank() }?.let { put("x-locale-region", it) }+ put("accept-language", locale.toLanguageTag())+ // `tmi.b()` sets these on EVERY production request — both branches of its+ // geo/compliance block (lines 124-136) always emit them, so unlike the other+ // `x-*` headers they are never dropped. Values for the North-American API root+ // (`api.lyft.com`): `nq1.NORTH_AMERICA.getGeoRegionHeaderValue()` = "GEO_REGION_NA"+ // and `x-lyft-payload-compliance` = "COMPLIANCE_REGION_CCPA" (tmi.java:129-130).+ // Reads/quotes tolerate their absence; payment-write (charge-account) validation+ // appears to require the compliance region to be declared, else 422.+ put("x-lyft-geo-region", "GEO_REGION_NA")+ put("x-lyft-payload-compliance", "COMPLIANCE_REGION_CCPA")+ }+ }++ private val basicAuth: String by lazy {+ val raw = "$CLIENT_ID:$CLIENT_SECRET".toByteArray()+ "Basic " + Base64.encodeToString(raw, Base64.NO_WRAP)+ }++ /** New id per login attempt, carried through both legs so the server can correlate them. */+ fun newSessionUuid(): String = UUID.randomUUID().toString()++ private suspend fun clientToken(): String? {+ cachedClientToken?.let { return it }+ val result = tokenCall(formEncode("grant_type" to GRANT_CLIENT))+ val token = (result as? LyftAuthResult.Success)?.token?.accessToken?.takeIf { it.isNotBlank() }+ cachedClientToken = token+ return token+ }++ /**+ * Asks Lyft to text a code to [phoneNumber] (E.164).+ *+ * Recovered from `defpackage/xnk.c` →+ * `bdj.a(…, "/v1/phoneauth", eks.POST, …, 8064)` and the request DTO `defpackage/ypa`+ * (proto `pb.api.endpoints.v1.phone_auth.CreatePhoneAuthRequest`): tag 1 `phone_number`,+ * tag 2 `voice_verification`, tag 3 `message_format`, tag 4 `client_configuration`.+ *+ * The flags word 8064 sets bit 128, so no header map is passed at the call site — the+ * `Authorization` comes from the transport's auth provider, which is the+ * `client_credentials` bearer above. 8064 also sets bit 2048, suppressing the+ * form-urlencoded default in `bdj.a`, so the body is JSON.+ *+ * `message_format` is `sms_android_retriever` in the official app only when it uses the SMS+ * Retriever API; we type the code by hand, so `sms_basic` is correct.+ */+ suspend fun requestSmsCode(phoneNumber: String): LyftAuthResult {+ val bearer = clientToken()+ ?: return LyftAuthResult.Failed(null, "Could not obtain a Lyft client token")+ val body = json.encodeToString(+ PhoneAuthRequest.serializer(),+ PhoneAuthRequest(phoneNumber = phoneNumber),+ )+ val resp = NetworkClient.performRequest(+ url = "$BASE/v1/phoneauth",+ method = "POST",+ headers = commonHeaders() + mapOf(+ "Authorization" to "Bearer $bearer",+ "Content-Type" to "application/json",+ "Accept" to "application/json",+ ),+ body = body,+ )+ Log.d(TAG, "POST /v1/phoneauth -> ${resp.status}")+ return if (resp.isSuccess) {+ LyftAuthResult.Success(LyftToken(accessToken = ""))+ } else {+ Log.w(TAG, "phoneauth failed ${resp.status}: ${resp.body.take(600)}")+ failure(resp.status, resp.body)+ }+ }++ /**+ * Exchanges the SMS code for a token.+ *+ * [email] answers an `email_match` challenge. From `OAuth2Service.e`, the app does not use a+ * separate challenge endpoint for this — it reissues the same phone grant with the `email`+ * field (tag 7) populated, so the SMS code must still be valid on the retry.+ */+ suspend fun verifySmsCode(+ phoneNumber: String,+ code: String,+ sessionUuid: String,+ email: String? = null,+ ): LyftAuthResult {+ val fields = buildList {+ add("grant_type" to GRANT_PHONE)+ add("phone_number" to phoneNumber)+ add("phone_code" to code)+ add("login_session_uuid" to sessionUuid)+ email?.takeIf { it.isNotBlank() }?.let {+ add("email" to it)+ // Mirrors the "This is my account" prompt_action Lyft offers alongside the+ // challenge; without it the server can read the retry as a new-account attempt.+ add("confirm" to "true")+ }+ }+ return tokenCall(formEncode(*fields.toTypedArray()))+ }++ suspend fun refresh(refreshToken: String): LyftToken? {+ val form = formEncode(+ "grant_type" to "refresh_token",+ "refresh_token" to refreshToken,+ )+ return (tokenCall(form) as? LyftAuthResult.Success)?.token+ }++ /**+ * Revokes a token server-side (`POST /oauth2/revoke_token`, Basic client auth, form body+ * `token=<token>`), so signing out invalidates the session on Lyft's side rather than only+ * dropping it locally. Best-effort: returns whether the server accepted it.+ */+ suspend fun revoke(token: String): Boolean {+ val resp = NetworkClient.performRequest(+ url = "$BASE/oauth2/revoke_token",+ method = "POST",+ headers = commonHeaders() + mapOf(+ "Authorization" to basicAuth,+ "Content-Type" to "application/x-www-form-urlencoded",+ "Accept" to "application/json",+ ),+ body = formEncode("token" to token),+ )+ Log.d(TAG, "POST /oauth2/revoke_token -> ${resp.status}")+ return resp.isSuccess+ }++ private suspend fun tokenCall(form: String): LyftAuthResult {+ val resp = NetworkClient.performRequest(+ url = "$BASE/oauth2/access_token",+ method = "POST",+ headers = commonHeaders() + mapOf(+ "Authorization" to basicAuth,+ "Content-Type" to "application/x-www-form-urlencoded",+ "Accept" to "application/json",+ ),+ body = form,+ )+ Log.d(TAG, "POST /oauth2/access_token -> ${resp.status}")+ if (!resp.isSuccess) {+ // Body only on failure — a success body carries the tokens.+ Log.w(TAG, "token failed ${resp.status}: ${resp.body.take(600)}")+ return failure(resp.status, resp.body)+ }+ val token = runCatching { json.decodeFromString(LyftToken.serializer(), resp.body) }+ .getOrElse { return LyftAuthResult.Failed(null, "Unreadable token response") }+ return LyftAuthResult.Success(token)+ }++ private fun failure(status: Int, body: String): LyftAuthResult {+ val error = runCatching { json.decodeFromString(LyftError.serializer(), body) }.getOrNull()+ error?.redirectUri?.takeIf { it.isNotBlank() }?.let {+ return LyftAuthResult.NeedsWebChallenge(it)+ }+ error?.challenges?.firstOrNull()?.let { challenge ->+ return LyftAuthResult.NeedsChallenge(+ identifier = challenge.identifier,+ hint = challenge.data,+ description = error.errorDescription,+ )+ }+ val message = error?.errorDescription ?: error?.error ?: "HTTP $status"+ return LyftAuthResult.Failed(error?.error, message)+ }++ private fun formEncode(vararg pairs: Pair<String, String>): String =+ pairs.joinToString("&") { (k, v) ->+ "${enc(k)}=${enc(v)}"+ }++ private fun enc(s: String): String = URLEncoder.encode(s, "UTF-8")+}++@Serializable+private data class PhoneAuthRequest(+ @SerialName("phone_number") val phoneNumber: String,+ @SerialName("voice_verification") val voiceVerification: Boolean = false,+ @SerialName("message_format") val messageFormat: String = "sms_basic",+ @SerialName("client_configuration") val clientConfiguration: String = "release",+)++@Serializable+private data class LyftError(+ val error: String? = null,+ @SerialName("error_description") val errorDescription: String? = null,+ @SerialName("redirect_uri") val redirectUri: String? = null,+ val challenges: List<LyftChallenge> = emptyList(),+)++@Serializable+private data class LyftChallenge(+ val identifier: String,+ /** Masked hint for the expected answer, e.g. `v******t@u*c.edu`. */+ val data: String? = null,+)
taxi/src/main/java/com/vayunmathur/taxi/lyft/LyftProvider.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/lyft/LyftProvider.kt b/taxi/src/main/java/com/vayunmathur/taxi/lyft/LyftProvider.ktnew file mode 100644index 0000000000..32905bfd65--- /dev/null+++ b/taxi/src/main/java/com/vayunmathur/taxi/lyft/LyftProvider.kt@@ -0,0 +1,1420 @@+package com.vayunmathur.taxi.lyft++import android.content.Context+import android.net.Uri+import android.util.Base64+import android.util.Log+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.RawResponse+import com.vayunmathur.taxi.data.AddCardResult+import com.vayunmathur.taxi.data.ActiveRide+import com.vayunmathur.taxi.data.BookingResult+import com.vayunmathur.taxi.data.CancelResult+import com.vayunmathur.taxi.data.ChargeAccount+import com.vayunmathur.taxi.data.DriverInfo+import com.vayunmathur.taxi.data.DriverLocation+import com.vayunmathur.taxi.data.LatLng+import com.vayunmathur.taxi.data.NewCard+import com.vayunmathur.taxi.data.PaymentActionResult+import com.vayunmathur.taxi.data.PaymentMethodsResult+import com.vayunmathur.taxi.data.Place+import com.vayunmathur.taxi.data.Provider+import com.vayunmathur.taxi.data.QuoteResult+import com.vayunmathur.taxi.data.RideQuote+import com.vayunmathur.taxi.data.RideStatus+import com.vayunmathur.taxi.data.RideStatusResult+import com.vayunmathur.taxi.data.RideStopInfo+import com.vayunmathur.taxi.data.VehicleInfo+import com.vayunmathur.taxi.deeplink.RideDeepLinks+import com.vayunmathur.taxi.provider.RideProvider+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.addJsonObject+import kotlinx.serialization.json.booleanOrNull+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.contentOrNull+import kotlinx.serialization.json.doubleOrNull+import kotlinx.serialization.json.intOrNull+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.longOrNull+import kotlinx.serialization.json.put+import kotlinx.serialization.json.putJsonArray+import kotlinx.serialization.json.putJsonObject+import java.security.KeyStore+import javax.net.ssl.SSLContext+import javax.net.ssl.SSLSocketFactory+import javax.net.ssl.TrustManagerFactory+import kotlin.math.roundToInt+import kotlin.math.roundToLong++/**+ * Lyft fares from `POST /v2/offerings` (`/pb.api.endpoints.v1.offers.Offers/ReadOffersV2`).+ *+ * Request/response shapes recovered from the production APK (`me.lyft.android` v2026.29.3) with+ * jadx — see `lyft-re/api-notes.md` §3. The request is the proto-JSON form of `OffersRequestDTO`.+ * On success the server negotiates a body: it may reply with proto-JSON **or** binary protobuf+ * depending on `Accept`, so we read raw bytes and parse whichever came back (protobuf via the+ * hand-rolled reader below, keyed by the same field tags as the DTOs).+ */+class LyftProvider(private val context: Context) : RideProvider {+ override val provider = Provider.LYFT++ private val tokens = LyftTokenStore(context.applicationContext)+ private val json = Json { ignoreUnknownKeys = true; isLenient = true }++ /**+ * TLS factory over the platform (system) CA store, for the external payment processors+ * (Stripe/Braintree). The shared [NetworkClient] is initialised with a reduced trust bundle+ * that only covers Lyft's own hosts, and its `useSystemTrust` flag falls back to that bundle+ * rather than to system trust — so passing an explicit system factory is the only way to+ * reach public processor endpoints without touching the shared network library.+ */+ private val systemTrustFactory: SSLSocketFactory by lazy {+ val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())+ tmf.init(null as KeyStore?) // null keystore => platform default CAs+ SSLContext.getInstance("TLS").apply { init(null, tmf.trustManagers, null) }.socketFactory+ }++ override suspend fun isSignedIn(): Boolean = tokens.isSignedIn()++ override suspend fun quotes(pickup: Place, dropoff: Place): QuoteResult {+ val token = accessToken() ?: return QuoteResult.NotSignedIn+ return readOffers(token, "${LyftAuth.BASE}/v2/offerings", offersBody(pickup, dropoff, null, null))+ }++ /**+ * Re-quotes an existing offer set via `/v2/offerings/update` (`ReadOffersV2Update`), carrying+ * [lastOffersId] (the previous `offers_response_id`) and [purchaseSessionId] so the server+ * refreshes the same session's prices/cost-tokens. Used to replace fares whose cost token is+ * about to expire. Response shape matches `/v2/offerings`.+ */+ suspend fun updateQuotes(+ pickup: Place,+ dropoff: Place,+ lastOffersId: String?,+ purchaseSessionId: String?,+ ): QuoteResult {+ val token = accessToken() ?: return QuoteResult.NotSignedIn+ return readOffers(+ token,+ "${LyftAuth.BASE}/v2/offerings/update",+ offersBody(pickup, dropoff, lastOffersId, purchaseSessionId),+ )+ }++ /**+ * OffersRequestDTO body shared by `/v2/offerings` and `/v2/offerings/update`. See api-notes §3:+ * origin(1)+destination(2) as E6LatLng, request_source=OFFER_SELECTOR,+ * offer_selector_type=CATEGORIZED_VERTICAL, a session id, and an entry context. The update+ * path additionally carries `last_offers_id` + `purchase_session_id` to refresh a session.+ */+ private fun offersBody(+ pickup: Place,+ dropoff: Place,+ lastOffersId: String?,+ purchaseSessionId: String?,+ ): String = buildString {+ append("{")+ append(""""origin":${e6(pickup)},""")+ append(""""destination":${e6(dropoff)},""")+ append(""""request_source":"OFFER_SELECTOR",""")+ append(""""offer_selector_type":"CATEGORIZED_VERTICAL",""")+ append(""""offer_selector_session_id":"${java.util.UUID.randomUUID()}",""")+ lastOffersId?.let { append(""""last_offers_id":"$it",""") }+ purchaseSessionId?.let { append(""""purchase_session_id":"$it",""") }+ append(""""request_entry_context":{"entry_point":{"home":{}}}""")+ append("}")+ }++ private suspend fun readOffers(token: String, url: String, body: String): QuoteResult {+ val resp = NetworkClient.execute(+ url = url,+ method = "POST",+ // Reuse the exact standard header set the app sends (user-agent, user-device,+ // x-design-id, locale, timestamps). Without a valid `user-agent` the server+ // rejects the call outright ("invalid user agent") even with a good token.+ headers = LyftAuth.commonHeaders() + mapOf(+ "Authorization" to "Bearer $token",+ "Content-Type" to "application/json",+ "Accept" to "application/x-protobuf, application/json",+ ),+ body = body,+ )+ val contentType = resp.header("Content-Type")?.lowercase().orEmpty()+ Log.d(TAG, "POST $url -> ${resp.status} ($contentType, ${resp.bytes.size} bytes)")+ if (!resp.isSuccess) {+ // Error bodies come back as JSON regardless of Accept; surface the reason.+ return QuoteResult.Failed("Lyft returned HTTP ${resp.status}: ${resp.text.take(300)}")+ }++ val isProto = contentType.contains("protobuf") || contentType.contains("octet-stream")+ var parsed = runCatching {+ if (isProto) parseOfferingsProto(resp.bytes) else parseOfferingsJson(resp.text)+ }.onFailure { Log.w(TAG, "primary parse failed (proto=$isProto)", it) }.getOrDefault(ParsedOffers.EMPTY)+ // Content-Type can lie or be absent; fall back to the other codec before giving up.+ if (parsed.quotes.isEmpty()) {+ parsed = runCatching {+ if (isProto) parseOfferingsJson(resp.text) else parseOfferingsProto(resp.bytes)+ }.getOrDefault(ParsedOffers.EMPTY)+ }++ return if (parsed.quotes.isEmpty()) {+ QuoteResult.Failed("Lyft 200 ($contentType) but no offers parsed")+ } else {+ QuoteResult.Success(+ quotes = parsed.quotes,+ purchaseSessionId = parsed.purchaseSessionId,+ offersResponseId = parsed.offersResponseId,+ )+ }+ }++ override fun bookingUri(pickup: Place, dropoff: Place, quote: RideQuote?): String =+ RideDeepLinks.webUri(Provider.LYFT, pickup, dropoff, quote)++ // ----------------------------------------------------------------------------------------+ // In-app booking + payment management+ //+ // Endpoints recovered from the APK (`defpackage/l77`, `d77`, `ech0`, response DTO `u77` /+ // `c67`):+ // GET /chargeaccounts → ReadChargeAccounts (list)+ // PUT /charge-accounts-multi-provider → UpdateChargeAccount… (set default)+ // DELETE /chargeaccounts/{id} → DeleteChargeAccount (remove)+ // POST /v1/core_trips/create → CreateTrip (book)+ // GET /v1/activeride → ReadActiveRide (status)+ // POST /v1/rides/{id}/cancel → CancelRide (cancel)+ // Payment methods are held only in memory by callers and never persisted here.+ // ----------------------------------------------------------------------------------------++ override suspend fun paymentMethods(): PaymentMethodsResult {+ val token = accessToken() ?: return PaymentMethodsResult.NotSignedIn+ val resp = NetworkClient.execute(+ url = "${LyftAuth.BASE}/chargeaccounts",+ method = "GET",+ headers = authHeaders(token),+ )+ Log.d(TAG, "GET /chargeaccounts -> ${resp.status} (${resp.bytes.size} bytes)")+ if (!resp.isSuccess) {+ return PaymentMethodsResult.Failed(httpError(resp))+ }+ return PaymentMethodsResult.Success(parseChargeAccounts(resp))+ }++ override suspend fun setDefaultPaymentMethod(id: String): PaymentActionResult {+ val token = accessToken() ?: return PaymentActionResult.Failed("Not signed in to Lyft")+ // UpdateChargeAccountMultiProvider (fvf0). The real client (t77.b via ech0, for+ // MakePersonalDefault + TriggerDebtCollection) always sends four fields on this PUT:+ // default (tag 2, BoolValue) = true+ // charge_account_id (tag 4, string) = id+ // skip_debt_collection (tag 8, BoolValue) = false (TriggerDebtCollection)+ // skip_persisted_challenge (tag 9, ...) = false+ // Omitting the two skip_* wrappers makes the server reject the update with 422, so we+ // mirror the real client exactly.+ val body = buildJsonObject {+ put("charge_account_id", id)+ put("default", true)+ put("skip_debt_collection", false)+ put("skip_persisted_challenge", false)+ }.toString()+ val resp = NetworkClient.execute(+ url = "${LyftAuth.BASE}/charge-accounts-multi-provider",+ method = "PUT",+ headers = authProtoJsonHeaders(+ token,+ "pb.api.endpoints.charge_accounts.UpdateChargeAccountMultipleProviderRequest",+ ),+ body = body,+ )+ Log.d(TAG, "PUT /charge-accounts-multi-provider -> ${resp.status}")+ if (!resp.isSuccess) {+ // 422s here are opaque without the server's reason — log the full exchange so the+ // exact validation error (field name / compliance / challenge) is visible.+ Log.w(TAG, "set-default failed ${resp.status}: req=$body resp=${resp.text}")+ return PaymentActionResult.Failed(httpError(resp))+ }+ // The response is a ChargeAccountsResponse; return the refreshed list when it parses.+ val accounts = runCatching { parseChargeAccounts(resp) }.getOrDefault(emptyList())+ return PaymentActionResult.Success(accounts.ifEmpty { null })+ }++ override suspend fun removePaymentMethod(id: String): PaymentActionResult {+ val token = accessToken() ?: return PaymentActionResult.Failed("Not signed in to Lyft")+ val resp = NetworkClient.execute(+ url = "${LyftAuth.BASE}/chargeaccounts/${Uri.encode(id)}",+ method = "DELETE",+ headers = authHeaders(token),+ )+ Log.d(TAG, "DELETE /chargeaccounts/{id} -> ${resp.status}")+ if (!resp.isSuccess) return PaymentActionResult.Failed(httpError(resp))+ // Callers re-fetch the list after a delete.+ return PaymentActionResult.Success(null)+ }++ // ----------------------------------------------------------------------------------------+ // Add a card (Create)+ //+ // Lyft never accepts a raw PAN. The card is tokenized by a payment processor first, and only+ // the resulting token/nonce is sent on. Two hops:+ // 1. POST /v1/tokenization_strategies (PostTokenizationStrategies, req `n1z` / resp `o1z`)+ // → a list of TokenizationStrategy (`sbe0`), each carrying its processor's client key+ // under `api_key` (Stripe publishable key `thc0`, Braintree client token `zo3`).+ // NB: the strategy comes from *this* endpoint, not from `payment_options_response`.+ // 2. Tokenize at the processor (Stripe `POST /v1/tokens`, Braintree GraphQL) → token|nonce.+ // 3. POST /charge-accounts-multi-provider (CreateChargeAccountMultiProvider, req `una`)+ // with provider_representation + card_meta_data → refreshed ChargeAccountsResponse.+ // Card data lives only for the duration of this call; full PAN/CVV are never logged.+ // ----------------------------------------------------------------------------------------++ override suspend fun addCard(card: NewCard, makeDefault: Boolean): AddCardResult {+ val token = accessToken() ?: return AddCardResult.Failed("Not signed in to Lyft")++ // No retrievable processor config → native add-card is blocked for this session.+ val config = fetchTokenizerConfig(token, card) ?: return AddCardResult.Unsupported++ val tokenized = when (val r = tokenizeCard(config, card)) {+ is TokenizeResult.Err -> return AddCardResult.Failed(r.message)+ is TokenizeResult.Ok -> r+ }++ // `una`: default(2, bool), provider_representation(4, repeated `mt00`), card_meta_data(6,+ // `lf6`), skip_debt_collection(8), skip_persisted_challenge(9). The real create (`t77.a`)+ // sets default only when making default, always sends the two skip_* flags, and each Stripe+ // `mt00` carries a `version` (STRIPE_TOKEN / STRIPE_SETUP_INTENT). Wrapper types serialize+ // as bare scalars in proto3-JSON, so this maps 1:1 onto the DTO.+ val body = buildJsonObject {+ if (makeDefault) put("default", true)+ put("skip_debt_collection", false)+ put("skip_persisted_challenge", false)+ putJsonArray("provider_representation") {+ addJsonObject {+ put("provider", tokenized.provider)+ tokenized.token?.let { put("token", it) }+ tokenized.nonce?.let { put("nonce", it) }+ tokenized.version?.let { put("version", it) }+ }+ }+ putJsonObject("card_meta_data") {+ put("expiration_month", card.expMonth)+ put("expiration_year", card.expYear)+ if (card.postalCode.isNotBlank()) put("postal_code", card.postalCode)+ }+ }.toString()++ val resp = runCatching {+ NetworkClient.execute(+ url = "${LyftAuth.BASE}/charge-accounts-multi-provider",+ method = "POST",+ headers = authProtoJsonHeaders(+ token,+ "pb.api.endpoints.charge_accounts.CreateChargeAccountMultipleProviderRequest",+ ),+ body = body,+ )+ }.getOrElse { return AddCardResult.Failed("Create card request failed: ${it.message}") }+ Log.d(TAG, "POST /charge-accounts-multi-provider (create) -> ${resp.status}")+ if (!resp.isSuccess) {+ Log.w(TAG, "add-card failed ${resp.status}: req=$body resp=${resp.text}")+ return AddCardResult.Failed(httpError(resp))+ }+ // Response is a ChargeAccountsResponse; return the refreshed list when it parses.+ val accounts = runCatching { parseChargeAccounts(resp) }.getOrDefault(emptyList())+ return AddCardResult.Success(accounts.ifEmpty { null })+ }++ /**+ * Resolves which processor to tokenize the card with by calling PostTokenizationStrategies.+ * The response (`o1z`) lists per-provider strategies (`sbe0`); the card ones carry the+ * processor's client key under `api_key`. Stripe is preferred, then Braintree; providers we+ * don't implement (Adyen etc.) yield null → caller reports Unsupported. Logs the resolved+ * provider and a redacted key so the residual "where does the key live" unknown is closed.+ */+ private suspend fun fetchTokenizerConfig(token: String, card: NewCard): TokenizerConfig? {+ // `n1z`: purpose(1, enum) = PAYIN, card_request(11) = { bin(1), last_four(2) }.+ val body = buildJsonObject {+ put("purpose", "PAYIN")+ putJsonObject("card_request") {+ put("bin", card.bin)+ put("last_four", card.last4)+ }+ }.toString()+ val resp = runCatching {+ NetworkClient.execute(+ url = "${LyftAuth.BASE}/v1/tokenization_strategies",+ method = "POST",+ headers = authJsonHeaders(token),+ body = body,+ )+ }.getOrElse {+ Log.w(TAG, "tokenization_strategies request failed", it)+ return null+ }+ Log.d(TAG, "POST /v1/tokenization_strategies -> ${resp.status} (${resp.bytes.size} bytes)")+ if (!resp.isSuccess) {+ Log.w(TAG, "tokenization_strategies failed: ${resp.text.take(200)}")+ return null+ }+ val config = parseTokenizerConfig(resp)+ if (config == null) {+ Log.w(TAG, "No supported tokenizer strategy in response")+ } else {+ Log.d(TAG, "Tokenizer resolved: provider=${config.provider} key=${redactKey(config.key)}")+ }+ return config+ }++ /**+ * `PostTokenizationStrategiesResponse` (`o1z`): strategies(1, repeated `sbe0`). Each `sbe0`+ * has stripe_card_data(10)→api_key(1) and braintree_card_data(11)→api_key(1). Tries JSON then+ * protobuf, matching the codec negotiation the rest of this class uses.+ */+ private fun parseTokenizerConfig(resp: RawResponse): TokenizerConfig? {+ val contentType = resp.header("Content-Type")?.lowercase().orEmpty()+ val isProto = contentType.contains("protobuf") || contentType.contains("octet-stream")+ return if (isProto) {+ parseTokenizerConfigProto(resp.bytes) ?: parseTokenizerConfigJson(resp.text)+ } else {+ parseTokenizerConfigJson(resp.text) ?: parseTokenizerConfigProto(resp.bytes)+ }+ }++ /**+ * `PostTokenizationStrategiesResponse` (`o1z`): strategies(1, repeated `sbe0`). The real client+ * prioritises the modern SCA strategy `stripe_card_setup_intent_data` (tag 22, `uhc0`) far above+ * legacy `stripe_card_data` (tag 10) — a 2026 build returns the SetupIntent one for cards, which+ * is why only recognising the legacy strategies made add-card fail (no config → Unsupported).+ * Order here mirrors that: SetupIntent → legacy Stripe token → Braintree.+ */+ private fun parseTokenizerConfigJson(raw: String): TokenizerConfig? {+ val root = runCatching { json.parseToJsonElement(raw) }.getOrNull() as? JsonObject+ ?: return null+ val strategies = root["strategies"]?.jsonArray?.mapNotNull { it as? JsonObject }+ ?: return null+ strategies.firstNotNullOfOrNull { s ->+ (s["stripe_card_setup_intent_data"] as? JsonObject)?.let { d ->+ d.str("api_key")?.let { apiKey ->+ TokenizerConfig(+ provider = "stripe_setup_intent",+ key = apiKey,+ clientSecret = d.str("client_secret"),+ setupIntentId = d.str("setup_intent_id"),+ stripeApiVersion = d.str("stripe_api_version"),+ )+ }+ }+ }?.let { return it }+ strategies.firstNotNullOfOrNull { s ->+ (s["stripe_card_data"] as? JsonObject)?.str("api_key")+ ?.let { TokenizerConfig("stripe", it) }+ }?.let { return it }+ return strategies.firstNotNullOfOrNull { s ->+ (s["braintree_card_data"] as? JsonObject)?.str("api_key")+ ?.let { TokenizerConfig("braintree", it) }+ }+ }++ private fun parseTokenizerConfigProto(bytes: ByteArray): TokenizerConfig? {+ val strategies = runCatching { ProtoMessage(bytes, 0, bytes.size).messages(1) }+ .getOrDefault(emptyList())+ // stripe_card_setup_intent_data (tag 22): api_key(1), client_secret(2), setup_intent_id(3),+ // stripe_api_version(4).+ strategies.firstNotNullOfOrNull { s ->+ s.message(22)?.let { d ->+ d.string(1)?.let { apiKey ->+ TokenizerConfig(+ provider = "stripe_setup_intent",+ key = apiKey,+ clientSecret = d.string(2),+ setupIntentId = d.string(3),+ stripeApiVersion = d.string(4),+ )+ }+ }+ }?.let { return it }+ strategies.firstNotNullOfOrNull { it.message(10)?.string(1) }+ ?.let { return TokenizerConfig("stripe", it) }+ return strategies.firstNotNullOfOrNull { it.message(11)?.string(1) }+ ?.let { TokenizerConfig("braintree", it) }+ }++ private suspend fun tokenizeCard(config: TokenizerConfig, card: NewCard): TokenizeResult =+ when (config.provider) {+ "stripe_setup_intent" -> tokenizeStripeSetupIntent(config, card)+ "stripe" -> tokenizeStripe(config.key, card)+ "braintree" -> tokenizeBraintree(config.key, card)+ else -> TokenizeResult.Err("Unsupported card processor: ${config.provider}")+ }++ /**+ * Modern SCA-compliant Stripe path (`sbe0` tag 22 `StripeCardSetupIntentDataDTO`, tokenized in+ * `ol6.c` case 2 via `qic0`). The server pre-creates a SetupIntent; we confirm it with the raw+ * card inline:+ * POST https://api.stripe.com/v1/setup_intents/{setup_intent_id}/confirm+ * Authorization: Bearer <api_key>; Stripe-Version: <stripe_api_version>; form-encoded+ * client_secret + payment_method_data[type|card[...]|billing_details[address][postal_code]]+ * The confirm response's `payment_method` (`pm_…`, `mna.payment_method`) is the token, sent on+ * as `mt00.token` with version `STRIPE_SETUP_INTENT` (`it00`).+ */+ private suspend fun tokenizeStripeSetupIntent(+ config: TokenizerConfig,+ card: NewCard,+ ): TokenizeResult {+ val setupIntentId = config.setupIntentId+ ?: return TokenizeResult.Err("Stripe SetupIntent strategy missing setup_intent_id")+ val clientSecret = config.clientSecret+ ?: return TokenizeResult.Err("Stripe SetupIntent strategy missing client_secret")+ val form = buildString {+ append("client_secret=").append(Uri.encode(clientSecret))+ append("&payment_method_data[type]=card")+ append("&payment_method_data[card][number]=").append(Uri.encode(card.number))+ append("&payment_method_data[card][exp_month]=").append(card.expMonth)+ append("&payment_method_data[card][exp_year]=").append(card.expYear)+ append("&payment_method_data[card][cvc]=").append(Uri.encode(card.cvc))+ if (card.postalCode.isNotBlank()) {+ append("&payment_method_data[billing_details][address][postal_code]=")+ append(Uri.encode(card.postalCode))+ }+ }+ val headers = buildMap {+ put("Authorization", "Bearer ${config.key}")+ put("Content-Type", "application/x-www-form-urlencoded")+ put("Accept", "application/json")+ config.stripeApiVersion?.takeIf { it.isNotBlank() }?.let { put("Stripe-Version", it) }+ }+ val resp = runCatching {+ NetworkClient.execute(+ url = "https://api.stripe.com/v1/setup_intents/${Uri.encode(setupIntentId)}/confirm",+ method = "POST",+ headers = headers,+ body = form,+ sslSocketFactory = systemTrustFactory,+ )+ }.getOrElse { return TokenizeResult.Err("Stripe SetupIntent request failed: ${it.message}") }+ val root = runCatching { json.parseToJsonElement(resp.text) as? JsonObject }.getOrNull()+ if (!resp.isSuccess) {+ val msg = root?.get("error")?.jsonObject?.str("message")+ ?: "Stripe HTTP ${resp.status}: ${resp.text.take(200)}"+ return TokenizeResult.Err(msg)+ }+ val pm = root?.str("payment_method")+ ?: return TokenizeResult.Err("Stripe returned no payment_method")+ Log.d(TAG, "Stripe SetupIntent confirmed ••${card.last4} -> ${pm.take(8)}…")+ // mt00.provider for a Stripe card is jju.h(qbe0.STRIPE.name()) = "stripe".+ return TokenizeResult.Ok("stripe", token = pm, nonce = null, version = "STRIPE_SETUP_INTENT")+ }++ /**+ * Stripe card token: `POST https://api.stripe.com/v1/tokens`, form-encoded, publishable key+ * as Bearer (mirrors `ol6` case STRIPE_CARD_DATA). Returns a `tok_…` used as `mt00.token`.+ */+ private suspend fun tokenizeStripe(publishableKey: String, card: NewCard): TokenizeResult {+ val form = buildString {+ append("card[number]=").append(Uri.encode(card.number))+ append("&card[exp_month]=").append(card.expMonth)+ append("&card[exp_year]=").append(card.expYear)+ append("&card[cvc]=").append(Uri.encode(card.cvc))+ }+ // External host: force system CAs via an explicit factory. (NetworkClient's own+ // useSystemTrust flag falls back to the Lyft-only bundle, which rejects Stripe.) Guard+ // the call so a transport/TLS failure surfaces as an error rather than crashing.+ val resp = runCatching {+ NetworkClient.execute(+ url = "https://api.stripe.com/v1/tokens",+ method = "POST",+ headers = mapOf(+ "Authorization" to "Bearer $publishableKey",+ "Content-Type" to "application/x-www-form-urlencoded",+ "Accept" to "application/json",+ "Stripe-Version" to "2015-10-12",+ ),+ body = form,+ sslSocketFactory = systemTrustFactory,+ )+ }.getOrElse { return TokenizeResult.Err("Stripe request failed: ${it.message}") }+ val root = runCatching { json.parseToJsonElement(resp.text) as? JsonObject }.getOrNull()+ if (!resp.isSuccess) {+ val msg = root?.get("error")?.jsonObject?.str("message")+ ?: "Stripe HTTP ${resp.status}: ${resp.text.take(200)}"+ return TokenizeResult.Err(msg)+ }+ val tok = root?.str("id") ?: return TokenizeResult.Err("Stripe returned no token")+ Log.d(TAG, "Stripe tokenized ••${card.last4} -> ${tok.take(8)}…")+ return TokenizeResult.Ok("stripe", token = tok, nonce = null, version = "STRIPE_TOKEN")+ }++ /**+ * Braintree card nonce. The Braintree `card` SDK module isn't bundled in the Lyft APK, so the+ * flow is hand-built: parse the client token (`av7` → `authorizationFingerprint` + GraphQL+ * url), then run the `tokenizeCreditCard` mutation against the GraphQL endpoint. Returns a+ * nonce used as `mt00.nonce`.+ */+ private suspend fun tokenizeBraintree(clientToken: String, card: NewCard): TokenizeResult {+ val parsed = parseBraintreeClientToken(clientToken)+ ?: return TokenizeResult.Err("Couldn't parse Braintree client token")+ val (graphQlUrl, fingerprint) = parsed+ val query = "mutation TokenizeCard(\$input: TokenizeCreditCardInput!) { " ++ "tokenizeCreditCard(input: \$input) { token } }"+ val reqBody = buildJsonObject {+ put("query", query)+ putJsonObject("variables") {+ putJsonObject("input") {+ putJsonObject("creditCard") {+ put("number", card.number)+ put("expirationMonth", card.expMonth.toString())+ put("expirationYear", card.expYear.toString())+ put("cvv", card.cvc)+ }+ }+ }+ }.toString()+ val resp = runCatching {+ NetworkClient.execute(+ url = graphQlUrl,+ method = "POST",+ headers = mapOf(+ "Authorization" to "Bearer $fingerprint",+ "Content-Type" to "application/json",+ "Accept" to "application/json",+ "Braintree-Version" to "2024-08-23",+ ),+ body = reqBody,+ sslSocketFactory = systemTrustFactory,+ )+ }.getOrElse { return TokenizeResult.Err("Braintree request failed: ${it.message}") }+ val root = runCatching { json.parseToJsonElement(resp.text) as? JsonObject }.getOrNull()+ // Braintree GraphQL returns 200 with a non-empty `errors` array on failure.+ val errors = root?.get("errors")?.jsonArray+ if (!resp.isSuccess || !errors.isNullOrEmpty()) {+ val msg = errors?.firstOrNull()?.jsonObject?.str("message")+ ?: "Braintree HTTP ${resp.status}: ${resp.text.take(200)}"+ return TokenizeResult.Err(msg)+ }+ val nonce = root?.get("data")?.jsonObject+ ?.get("tokenizeCreditCard")?.jsonObject+ ?.str("token")+ ?: return TokenizeResult.Err("Braintree returned no nonce")+ Log.d(TAG, "Braintree tokenized ••${card.last4} -> nonce ${nonce.take(6)}…")+ return TokenizeResult.Ok("braintree", token = null, nonce = nonce)+ }++ /**+ * A Braintree client token is either raw JSON or base64-encoded JSON (`av7` base64-decodes+ * when it matches). We need `authorizationFingerprint` and the GraphQL url (`graphQL.url`,+ * defaulting to the public endpoint).+ */+ private fun parseBraintreeClientToken(clientToken: String): Pair<String, String>? {+ val raw = if (clientToken.trimStart().startsWith("{")) {+ clientToken+ } else {+ runCatching { String(Base64.decode(clientToken, Base64.DEFAULT), Charsets.UTF_8) }+ .getOrNull() ?: return null+ }+ val obj = runCatching { json.parseToJsonElement(raw) as? JsonObject }.getOrNull()+ ?: return null+ val fingerprint = obj.str("authorizationFingerprint") ?: return null+ val url = obj["graphQL"]?.jsonObject?.str("url")+ ?: "https://payments.braintree-api.com/graphql"+ return url to fingerprint+ }++ private fun redactKey(key: String): String =+ if (key.length <= 8) "***" else "${key.take(8)}…(len ${key.length})"++ override suspend fun createRide(+ quote: RideQuote,+ pickup: Place,+ dropoff: Place,+ account: ChargeAccount?,+ purchaseSessionId: String?,+ dryRun: Boolean,+ ): BookingResult {+ val token = accessToken() ?: return BookingResult.Failed("Not signed in to Lyft")+ val offerId = quote.offerId+ ?: return BookingResult.Failed("This fare has no offer id — re-quote and try again")+ val riderId = tokens.userId()++ // CreateTripRequest (defpackage/ura): rider_id(1), offer_id(2), origin(3), destination(4),+ // ride_segment_creation_args(5). Sent as proto-JSON, as the offers call is.+ val request = buildJsonObject {+ riderId?.let { put("rider_id", it) } // uint64 → string in proto-JSON+ put("offer_id", offerId)+ put("origin", locationV2(pickup))+ put("destination", locationV2(dropoff))+ putJsonObject("ride_segment_creation_args") {+ quote.offerToken?.let { put("offer_token", it) }+ quote.rideType?.let { put("ride_type", it) }+ quote.costToken?.let { put("cost_token", it) }+ put("party_size", 1)+ // pickup_mode defaults to "standard" in the official app (RideSegmentCreationArgs+ // tag 9); the resolver expects it set.+ put("pickup_mode", "standard")+ // ChargeAccountDTO exposes only an id; passed as charge_token (tag 12). Exact+ // charge_token vs shared_charge_account_id split is unverified — dry-run surfaces+ // the built body so it can be checked against a real capture.+ account?.let { put("charge_token", it.chargeToken ?: it.id) }+ }+ // NB: purchase_session_id is NOT a field on CreateTripRequest (it belongs to the+ // offers request); server-side dedupe is handled by the request throttler instead.+ }+ val requestJson = request.toString()++ // Master guard: never send while BOOKING_LIVE is false, or when the caller asked for a+ // dry run. The full request is returned so the UI/logcat can verify it — no charge.+ if (!BOOKING_LIVE || dryRun) {+ Log.i(TAG, "DRY-RUN /v1/core_trips/create (not sent): $requestJson")+ return BookingResult.DryRun(requestJson, account)+ }++ val resp = NetworkClient.execute(+ url = "${LyftAuth.BASE}/v1/core_trips/create",+ method = "POST",+ headers = authJsonHeaders(token),+ body = requestJson,+ )+ Log.d(TAG, "POST /v1/core_trips/create -> ${resp.status}")+ if (!resp.isSuccess) return BookingResult.Failed(httpError(resp))+ // CreateTripResponse (vra): trip_details(1 = TripDetails) → trip_id(1). No status here;+ // parse the id (JSON or protobuf) for tracking and show nothing else.+ return BookingResult.Created(rideId = parseCreatedRideId(resp), status = null, raw = "")+ }++ /** Extracts `trip_details.trip_id` from a CreateTripResponse (JSON or binary protobuf). */+ private fun parseCreatedRideId(resp: RawResponse): String? {+ val contentType = resp.header("Content-Type")?.lowercase().orEmpty()+ val isProto = contentType.contains("protobuf") || contentType.contains("octet-stream")+ fun proto(): String? = runCatching {+ ProtoMessage(resp.bytes, 0, resp.bytes.size).message(1)?.varint(1)?.toString()+ }.getOrNull()+ fun asJson(): String? = runCatching {+ (json.parseToJsonElement(resp.text) as? JsonObject)+ ?.get("trip_details")?.jsonObject+ ?.let { it.str("trip_id") ?: it.str("id") }+ }.getOrNull()+ return if (isProto) (proto() ?: asJson()) else (asJson() ?: proto())+ }++ override suspend fun activeRide(): RideStatusResult {+ val token = accessToken() ?: return RideStatusResult.Failed("Not signed in to Lyft")+ val resp = NetworkClient.execute(+ url = "${LyftAuth.BASE}/v1/activeride",+ method = "GET",+ headers = authHeaders(token),+ )+ Log.d(TAG, "GET /v1/activeride -> ${resp.status} (${resp.bytes.size} bytes)")+ if (resp.status == 404) return RideStatusResult.None+ if (!resp.isSuccess) return RideStatusResult.Failed(httpError(resp))+ val ride = parseActiveRide(resp)+ return if (ride == null || !ride.hasContent) RideStatusResult.None else RideStatusResult.Active(ride)+ }++ override suspend fun driverLocation(rideId: String): DriverLocation? {+ val token = accessToken() ?: return null+ val resp = NetworkClient.execute(+ url = "${LyftAuth.BASE}/v1/rides/${Uri.encode(rideId)}/driver-location",+ method = "GET",+ headers = authHeaders(token),+ )+ Log.d(TAG, "GET /v1/rides/{id}/driver-location -> ${resp.status}")+ if (!resp.isSuccess) return null+ return parseDriverLocation(resp)+ }++ override suspend fun cancelRide(rideId: String): CancelResult {+ val token = accessToken() ?: return CancelResult.Failed("Not signed in to Lyft")+ // A cancel genuinely cancels a live ride (and may incur a fee), so it is sent live+ // regardless of BOOKING_LIVE — that flag only gates ride *creation*.+ val resp = NetworkClient.execute(+ url = "${LyftAuth.BASE}/v1/rides/${Uri.encode(rideId)}/cancel",+ method = "POST",+ headers = authJsonHeaders(token),+ body = "{}",+ )+ Log.d(TAG, "POST /v1/rides/{id}/cancel -> ${resp.status}")+ // Surface the server response verbatim either way — a cancel can carry a fee.+ return if (resp.isSuccess) {+ CancelResult.Done(resp.text.take(2000).ifBlank { "Ride cancelled" })+ } else {+ CancelResult.Failed(httpError(resp))+ }+ }++ /**+ * Signs out of Lyft: best-effort revokes the refresh and access tokens server-side, then+ * clears the local session regardless of the server's response.+ */+ suspend fun signOut() {+ tokens.refreshToken()?.let { LyftAuth.revoke(it) }+ tokens.accessToken()?.let { LyftAuth.revoke(it) }+ tokens.clear()+ }++ /** Reads a specific ride by id (`GET /v1/rides/{id}`), parsed like the active ride. */+ suspend fun rideById(rideId: String): RideStatusResult {+ val token = accessToken() ?: return RideStatusResult.Failed("Not signed in to Lyft")+ val resp = NetworkClient.execute(+ url = "${LyftAuth.BASE}/v1/rides/${Uri.encode(rideId)}",+ method = "GET",+ headers = authHeaders(token),+ )+ Log.d(TAG, "GET /v1/rides/{id} -> ${resp.status}")+ if (resp.status == 404) return RideStatusResult.None+ if (!resp.isSuccess) return RideStatusResult.Failed(httpError(resp))+ val ride = parseActiveRide(resp)+ return if (ride == null || !ride.hasContent) RideStatusResult.None else RideStatusResult.Active(ride)+ }++ // ----------------------------------------------------------------------------------------+ // Best-effort car ride endpoints. Their request/response shapes are unverified in the APK+ // teardown (api-notes §3/§4), so these issue the documented HTTP call and return the raw+ // response body (truncated) for the caller to interpret; null on any non-2xx or when signed+ // out. No dedicated UI consumes them yet.+ // ----------------------------------------------------------------------------------------++ /** `GET /v1/active-offer` — the current unaccepted offer, if any. */+ suspend fun activeOffer(): String? = getRaw("/v1/active-offer")++ /** `GET /v1/rides/{id}/pickupgeofence` — the pickup geofence for a ride. */+ suspend fun pickupGeofence(rideId: String): String? =+ getRaw("/v1/rides/${Uri.encode(rideId)}/pickupgeofence")++ /** `GET /v1/rides/{id}/paymentdetails` — payment breakdown for a ride. */+ suspend fun paymentDetails(rideId: String): String? =+ getRaw("/v1/rides/${Uri.encode(rideId)}/paymentdetails")++ /** `POST /v1/updated-cost-estimate/{id}` — refreshed cost for an in-flight ride. */+ suspend fun updatedCostEstimate(rideId: String): String? =+ postRaw("/v1/updated-cost-estimate/${Uri.encode(rideId)}", "{}")++ /** `POST /v1/scheduledridetimeestimates` — pickup-time estimates for a scheduled ride. */+ suspend fun scheduledRideTimeEstimates(pickup: Place, dropoff: Place): String? =+ postRaw("/v1/scheduledridetimeestimates", offersBody(pickup, dropoff, null, null))++ /** `POST /v1/offerings/overview` — offer overview for a route. */+ suspend fun offeringsOverview(pickup: Place, dropoff: Place): String? =+ postRaw("/v1/offerings/overview", offersBody(pickup, dropoff, null, null))++ /** `POST /v1/rides/{id}/pickup` — move the pickup of an existing ride. Mutates a live ride. */+ suspend fun updatePickup(rideId: String, pickup: Place): String? =+ postRaw("/v1/rides/${Uri.encode(rideId)}/pickup", locationV2(pickup).toString())++ /** `POST /v1/rides/redispatch` — request a new driver for a ride. Mutates a live ride. */+ suspend fun redispatch(rideId: String): String? =+ postRaw("/v1/rides/redispatch", buildJsonObject { put("ride_id", rideId) }.toString())++ private suspend fun getRaw(path: String): String? {+ val token = accessToken() ?: return null+ val resp = NetworkClient.execute(+ url = "${LyftAuth.BASE}$path",+ method = "GET",+ headers = authHeaders(token),+ )+ Log.d(TAG, "GET $path -> ${resp.status}")+ return if (resp.isSuccess) resp.text.take(4000) else null+ }++ private suspend fun postRaw(path: String, body: String): String? {+ val token = accessToken() ?: return null+ val resp = NetworkClient.execute(+ url = "${LyftAuth.BASE}$path",+ method = "POST",+ headers = authJsonHeaders(token),+ body = body,+ )+ Log.d(TAG, "POST $path -> ${resp.status}")+ return if (resp.isSuccess) resp.text.take(4000) else null+ }++ // ----------------------------------------------------------------------------------------+ // Active-ride / driver-location parsing (PassengerRide, ReadDriverLocationResponse).+ // Field tags mirror the DTOs in api-notes §4; both JSON and binary protobuf are accepted,+ // matching the codec negotiation the rest of this class uses.+ //+ // PassengerRide: ride_id(1), status(2), driver(6), vehicle(8), stops(9 repeated),+ // location(11 = live DriverLocation)+ // DriverLocation: lat(1 double), lng(2 double), bearing(3 double)+ // Driver: first_name(5), last_name(6), image_url(7), phone_number(8), rating(9)+ // RideVehicle: make(1), model(2), license_plate(3), image_url(4), color(6)+ // RideStop: location(2 PlaceDTO), kind(3), completed(4), eta_seconds(6), location_v2(7)+ // PlaceDTO: lat(1 double), lng(2 double), address(3), place_name(5)+ // ----------------------------------------------------------------------------------------++ private fun parseActiveRide(resp: RawResponse): ActiveRide? {+ val contentType = resp.header("Content-Type")?.lowercase().orEmpty()+ val isProto = contentType.contains("protobuf") || contentType.contains("octet-stream")+ fun proto() = runCatching { toActiveRideProto(resp.bytes) }.getOrNull()+ fun asJson() = runCatching { toActiveRideJson(resp.text) }.getOrNull()+ val primary = if (isProto) proto() else asJson()+ if (primary != null && primary.hasContent) return primary+ return (if (isProto) asJson() else proto())?.takeIf { it.hasContent } ?: primary+ }++ private fun toActiveRideJson(raw: String): ActiveRide? {+ val ride = firstRideObject(raw) ?: return null+ val statusRaw = ride.str("status") ?: ride.str("ride_status")+ val driver = (ride["driver"] as? JsonObject)?.let { d ->+ DriverInfo(+ firstName = d.str("first_name") ?: d.str("firstName"),+ lastName = d.str("last_name") ?: d.str("lastName"),+ imageUrl = d.str("image_url") ?: d.str("imageUrl"),+ phoneNumber = d.str("phone_number") ?: d.str("phoneNumber"),+ rating = d.dbl("rating"),+ )+ }+ val vehicle = (ride["vehicle"] as? JsonObject)?.let { v ->+ VehicleInfo(+ make = v.str("make"),+ model = v.str("model"),+ color = v.str("color"),+ licensePlate = v.str("license_plate") ?: v.str("licensePlate"),+ imageUrl = v.str("image_url") ?: v.str("imageUrl"),+ )+ }+ val driverLocation = (ride["location"] as? JsonObject)?.let(::toDriverLocationJson)+ val stops = ride["stops"]?.jsonArray+ ?.mapNotNull { (it as? JsonObject)?.let(::toStopJson) }+ ?: emptyList()+ return ActiveRide(+ rideId = ride.str("ride_id") ?: ride.str("id"),+ status = RideStatus.fromWire(statusRaw),+ statusRaw = statusRaw,+ driver = driver,+ vehicle = vehicle,+ driverLocation = driverLocation,+ stops = stops,+ raw = raw.take(2000),+ )+ }++ private fun toActiveRideProto(bytes: ByteArray): ActiveRide {+ val m = ProtoMessage(bytes, 0, bytes.size)+ val statusRaw = m.string(2)+ val driver = m.message(6)?.let { d ->+ DriverInfo(+ firstName = d.string(5),+ lastName = d.string(6),+ imageUrl = d.string(7),+ phoneNumber = d.string(8),+ rating = d.double(9) ?: d.wrappedDouble(9),+ )+ }+ val vehicle = m.message(8)?.let { v ->+ VehicleInfo(+ make = v.string(1),+ model = v.string(2),+ color = v.string(6),+ licensePlate = v.string(3),+ imageUrl = v.string(4),+ )+ }+ val driverLocation = m.message(11)?.let(::toDriverLocationProto)+ val stops = m.messages(9).map(::toStopProto)+ return ActiveRide(+ rideId = m.string(1),+ status = RideStatus.fromWire(statusRaw),+ statusRaw = statusRaw,+ driver = driver,+ vehicle = vehicle,+ driverLocation = driverLocation,+ stops = stops,+ raw = "<protobuf ${bytes.size} bytes>",+ )+ }++ private fun parseDriverLocation(resp: RawResponse): DriverLocation? {+ val contentType = resp.header("Content-Type")?.lowercase().orEmpty()+ val isProto = contentType.contains("protobuf") || contentType.contains("octet-stream")+ fun proto(): DriverLocation? {+ val root = ProtoMessage(resp.bytes, 0, resp.bytes.size)+ // ReadDriverLocationResponse.location = 1; tolerate a bare DriverLocation too.+ return root.message(1)?.let(::toDriverLocationProto) ?: toDriverLocationProto(root)+ }+ fun asJson(): DriverLocation? {+ val root = runCatching { json.parseToJsonElement(resp.text) as? JsonObject }.getOrNull()+ ?: return null+ val loc = (root["location"] as? JsonObject) ?: root+ return toDriverLocationJson(loc)+ }+ return if (isProto) (proto() ?: asJson()) else (asJson() ?: proto())+ }++ private fun toDriverLocationJson(o: JsonObject): DriverLocation? {+ val lat = o.dbl("lat") ?: o.dbl("latitude") ?: return null+ val lng = o.dbl("lng") ?: o.dbl("longitude") ?: return null+ return DriverLocation(lat, lng, o.dbl("bearing"))+ }++ private fun toDriverLocationProto(m: ProtoMessage): DriverLocation? {+ val lat = m.double(1) ?: return null+ val lng = m.double(2) ?: return null+ return DriverLocation(lat, lng, m.double(3))+ }++ private fun toStopJson(o: JsonObject): RideStopInfo {+ val place = (o["location"] as? JsonObject) ?: (o["location_v2"] as? JsonObject)+ val latLng = place?.let { p ->+ val lat = p.dbl("lat") ?: p.dbl("latitude")+ val lng = p.dbl("lng") ?: p.dbl("longitude")+ if (lat != null && lng != null) LatLng(lat, lng) else null+ }+ return RideStopInfo(+ location = latLng,+ name = place?.str("place_name") ?: place?.str("placeName") ?: place?.str("address"),+ kind = o.str("kind"),+ etaSeconds = o["eta_seconds"]?.jsonPrimitive?.intOrNull+ ?: o["etaSeconds"]?.jsonPrimitive?.intOrNull,+ completed = o["completed"]?.jsonPrimitive?.booleanOrNull ?: false,+ )+ }++ private fun toStopProto(m: ProtoMessage): RideStopInfo {+ val place = m.message(2) ?: m.message(7)+ val latLng = place?.let {+ val lat = it.double(1)+ val lng = it.double(2)+ if (lat != null && lng != null) LatLng(lat, lng) else null+ }+ return RideStopInfo(+ location = latLng,+ name = place?.string(5) ?: place?.string(3),+ kind = m.string(3),+ etaSeconds = m.varint(6)?.toInt(),+ completed = m.varint(4)?.let { it != 0L } ?: false,+ )+ }++ private fun authHeaders(token: String): Map<String, String> =+ LyftAuth.commonHeaders() + mapOf(+ "Authorization" to "Bearer $token",+ "Accept" to "application/json, application/x-protobuf",+ )++ private fun authJsonHeaders(token: String): Map<String, String> =+ authHeaders(token) + mapOf("Content-Type" to "application/json")++ /**+ * Lyft's server deserializes request bodies with a reflection-based proto-JSON codec that is+ * told which proto message to map the JSON onto via a `messageType` Content-Type parameter.+ * The APK builds it in `defpackage/tvu.d`:+ * `application/json;messageType=<proto full name>` (name from `fkh0.a()`, the DTO's+ * super-constructor arg, e.g. `pb.api.endpoints.charge_accounts.Update…Request`).+ * Paths that map to a single message (e.g. `/v2/offerings`) tolerate a bare `application/json`,+ * but `/charge-accounts-multi-provider` is shared by Create (POST) and Update (PUT), so without+ * `messageType` the server can't resolve the body and returns 422. We must send it.+ */+ private fun authProtoJsonHeaders(token: String, messageType: String): Map<String, String> =+ authHeaders(token) + mapOf("Content-Type" to "application/json;messageType=$messageType")++ private fun httpError(resp: RawResponse): String =+ "Lyft returned HTTP ${resp.status}: ${resp.text.take(300)}"++ /**+ * A `LocationV2DTO` for `origin`/`destination` on `/v1/core_trips/create`, recovered from the+ * APK (`kvp`, `LocationV2MapperKt.toLocationV2ForApiRequest`). Coordinates live three levels+ * deep as **integer microdegrees** (degrees × 1e6, sint32) at+ * `portable_location_with_features.portable_location.location.{lat,lng}_microdegrees` — a flat+ * `{latitude, longitude}` is not resolvable by the server (it answers 422 "not available for+ * your specified locations"). The display name/address go under+ * `location_metadata.static_metadata.spot`.+ */+ private fun locationV2(place: Place): JsonObject {+ val latMicro = (place.location.latitude * 1_000_000).roundToInt()+ val lngMicro = (place.location.longitude * 1_000_000).roundToInt()+ val basicLocation = buildJsonObject {+ put("lat_microdegrees", latMicro)+ put("lng_microdegrees", lngMicro)+ }+ return buildJsonObject {+ putJsonObject("portable_location_with_features") {+ putJsonObject("portable_location") {+ put("location", basicLocation)+ }+ }+ putJsonObject("location_metadata") {+ putJsonObject("static_metadata") {+ putJsonObject("spot") {+ put("name", place.name)+ place.address?.let {+ put("display_address", it)+ put("routable_address", it)+ }+ }+ }+ }+ put("source", "user")+ }+ }++ // ----------------------------------------------------------------------------------------+ // Charge-account parsing (ChargeAccountsResponse `u77` → ChargeAccountDTO `c67`)+ // c67: id=1 (StringValue), kind=2, default=3 (BoolValue), label=5, lastFour=10+ // ----------------------------------------------------------------------------------------++ private fun parseChargeAccounts(resp: RawResponse): List<ChargeAccount> {+ val contentType = resp.header("Content-Type")?.lowercase().orEmpty()+ val isProto = contentType.contains("protobuf") || contentType.contains("octet-stream")+ var accounts = runCatching {+ if (isProto) parseChargeAccountsProto(resp.bytes) else parseChargeAccountsJson(resp.text)+ }.getOrDefault(emptyList())+ if (accounts.isEmpty()) {+ accounts = runCatching {+ if (isProto) parseChargeAccountsJson(resp.text) else parseChargeAccountsProto(resp.bytes)+ }.getOrDefault(emptyList())+ }+ return accounts+ }++ private fun parseChargeAccountsJson(raw: String): List<ChargeAccount> {+ val root = json.parseToJsonElement(raw) as? JsonObject ?: return emptyList()+ val arr = root["chargeAccounts"]?.jsonArray+ ?: root["charge_accounts"]?.jsonArray+ ?: return emptyList()+ return arr.mapNotNull { (it as? JsonObject)?.let(::toChargeAccountJson) }+ }++ private fun toChargeAccountJson(o: JsonObject): ChargeAccount? {+ val id = o.str("id") ?: return null+ return ChargeAccount(+ id = id,+ chargeToken = null,+ label = accountLabel(o.str("label"), o.str("kind"), o.str("lastFour") ?: o.str("last_four")),+ isDefault = o["default"]?.jsonPrimitive?.booleanOrNull ?: false,+ )+ }++ private fun parseChargeAccountsProto(bytes: ByteArray): List<ChargeAccount> {+ val root = ProtoMessage(bytes, 0, bytes.size)+ return root.messages(1).mapNotNull { toChargeAccountProto(it) }+ }++ private fun toChargeAccountProto(m: ProtoMessage): ChargeAccount? {+ val id = m.wrappedString(1) ?: return null+ return ChargeAccount(+ id = id,+ chargeToken = null,+ label = accountLabel(m.wrappedString(5), m.wrappedString(2), m.wrappedString(10)),+ isDefault = m.wrappedBool(3) ?: false,+ )+ }++ private fun accountLabel(label: String?, kind: String?, lastFour: String?): String = when {+ !label.isNullOrBlank() -> label+ !kind.isNullOrBlank() && !lastFour.isNullOrBlank() -> "$kind ••$lastFour"+ !lastFour.isNullOrBlank() -> "•• $lastFour"+ !kind.isNullOrBlank() -> kind+ else -> "Card"+ }++ /**+ * Best-effort pick of the ride/trip object out of a create or active-ride response. Exact+ * shapes are unverified (api-notes §4/§6); we look for the common wrappers and fall back to+ * the root so id/status are surfaced when present.+ */+ private fun firstRideObject(raw: String): JsonObject? {+ val root = runCatching { json.parseToJsonElement(raw) }.getOrNull() as? JsonObject+ ?: return null+ return root["ride"]?.jsonObject+ ?: root["trip"]?.jsonObject+ ?: root["active_ride"]?.jsonObject+ ?: root+ }++ private suspend fun accessToken(): String? {+ if (!tokens.isExpired()) return tokens.accessToken()+ val refresh = tokens.refreshToken() ?: return null+ val fresh = LyftAuth.refresh(refresh) ?: return null+ tokens.save(fresh)+ return fresh.accessToken+ }++ /** A single `E6LatLngDTO`: lat/lng in integer micro-degrees (degrees × 1e6). */+ private fun e6(place: Place): String {+ val latE6 = (place.location.latitude * 1_000_000).roundToLong()+ val lngE6 = (place.location.longitude * 1_000_000).roundToLong()+ return """{"latitude_e6":$latE6,"longitude_e6":$lngE6}"""+ }++ // ----------------------------------------------------------------------------------------+ // JSON response+ // ----------------------------------------------------------------------------------------++ /**+ * Parses proto-JSON `ReadOffersV2Response`: `offers.offers_list[]`, each an `OfferDTO` with a+ * `cost_estimate` (price), `ride_type_details` (name + seats) and `ride_travel_details`+ * (pickup ETA). int64 proto-JSON fields may arrive as strings, which the accessors handle.+ * The offers wrapper also carries `purchase_session_id`/`offers_response_id`, reused when+ * booking.+ */+ private fun parseOfferingsJson(raw: String): ParsedOffers {+ val root = json.parseToJsonElement(raw) as? JsonObject ?: return ParsedOffers.EMPTY+ val offers = root["offers"]?.jsonObject ?: return ParsedOffers.EMPTY+ val quotes = offers["offers_list"]?.jsonArray+ ?.mapNotNull { element -> (element as? JsonObject)?.let(::toQuoteJson) }+ ?: emptyList()+ return ParsedOffers(+ quotes = quotes,+ purchaseSessionId = offers.str("purchase_session_id"),+ offersResponseId = offers.str("offers_response_id"),+ )+ }++ private fun toQuoteJson(offer: JsonObject): RideQuote? {+ val cost = offer["cost_estimate"]?.jsonObject+ val rideType = offer["ride_type_details"]?.jsonObject+ val display = rideType?.get("display_properties")?.jsonObject++ val name = display?.str("name")+ ?: cost?.str("ride_type")+ ?: offer.str("offer_product_id")+ ?: return null++ val min = cost?.long("estimated_cost_cents_min")+ val max = cost?.long("estimated_cost_cents_max")+ val upfront = cost?.long("upfront_cost_cents")+ val (low, high) = priceRange(min, max, upfront) ?: return null++ val pickupEtaMs = offer["ride_travel_details"]?.jsonObject+ ?.get("pickup_estimate")?.jsonObject+ ?.get("duration_range")?.jsonObject+ ?.long("duration_ms")++ return RideQuote(+ provider = Provider.LYFT,+ productId = offer.str("offer_product_id") ?: name,+ displayName = name,+ fareLowMinor = low,+ fareHighMinor = high,+ currency = cost?.str("currency") ?: "USD",+ pickupEtaMinutes = pickupEtaMs?.let { (it / 60_000).toInt() },+ tripDurationMinutes = cost?.long("estimated_duration_seconds")?.let { (it / 60).toInt() },+ surgeMultiplier = cost?.get("primetime_multiplier")?.jsonPrimitive?.doubleOrNull,+ capacity = rideType?.get("seats")?.jsonPrimitive?.intOrNull,+ offerId = offer.str("id"),+ // StringValue wrappers serialize to the bare string in proto3-JSON.+ offerToken = offer.str("offer_token"),+ costToken = cost?.str("cost_token"),+ rideType = cost?.str("ride_type"),+ // `cost_token_expiry_time` is an epoch **seconds** value (measured live: ~120s+ // lifetime, shared across all fares); convert to ms so callers can compare to now.+ costTokenExpiryMs = cost?.long("cost_token_expiry_time")?.let { it * 1000 },+ )+ }++ private fun JsonObject.str(key: String) = this[key]?.jsonPrimitive?.contentOrNull++ private fun JsonObject.long(key: String) = this[key]?.jsonPrimitive?.longOrNull++ private fun JsonObject.dbl(key: String) = this[key]?.jsonPrimitive?.doubleOrNull++ // ----------------------------------------------------------------------------------------+ // Protobuf response (binary). Field tags mirror the DTOs decompiled from the APK.+ // ----------------------------------------------------------------------------------------++ /**+ * Parses binary `ReadOffersV2Response`. Message nesting (field numbers):+ * - ReadOffersV2Response.offers = 1 → OffersV2DTO+ * - OffersV2DTO.offers_list = 3 (repeated) → OfferDTO+ * - OfferDTO: offer_product_id=2, cost_estimate=4, ride_type_details=5, ride_travel_details=9+ * - CostEstimate: cents_max=5, cents_min=6, upfront=7, currency=8, primetime_multiplier=12,+ * estimated_duration_seconds=22 (the *_cents / currency / duration are wrapper messages)+ * - RideMode: seats=7, display_properties=10 → name=3+ * - RideTravelDetails.pickup_estimate=1 → duration_range=2 → duration_ms=1 (wrapper)+ */+ private fun parseOfferingsProto(bytes: ByteArray): ParsedOffers {+ val root = ProtoMessage(bytes, 0, bytes.size)+ val offers = root.message(1) ?: return ParsedOffers.EMPTY+ return ParsedOffers(+ quotes = offers.messages(3).mapNotNull { toQuoteProto(it) },+ purchaseSessionId = offers.string(1),+ offersResponseId = offers.string(2),+ )+ }++ private fun toQuoteProto(offer: ProtoMessage): RideQuote? {+ val cost = offer.message(4)+ val rideType = offer.message(5)+ val display = rideType?.message(10)++ val name = display?.string(3)+ ?: cost?.string(4) // ride_type+ ?: offer.string(2) // offer_product_id+ ?: return null++ val min = cost?.wrappedLong(6)+ val max = cost?.wrappedLong(5)+ val upfront = cost?.wrappedLong(7)+ val (low, high) = priceRange(min, max, upfront) ?: return null++ val pickupEtaMs = offer.message(9)?.message(1)?.message(2)?.wrappedLong(1)++ return RideQuote(+ provider = Provider.LYFT,+ productId = offer.string(2) ?: name,+ displayName = name,+ fareLowMinor = low,+ fareHighMinor = high,+ currency = cost?.wrappedString(8) ?: "USD",+ pickupEtaMinutes = pickupEtaMs?.let { (it / 60_000).toInt() },+ tripDurationMinutes = cost?.wrappedLong(22)?.let { (it / 60).toInt() },+ surgeMultiplier = cost?.double(12),+ capacity = rideType?.varint(7)?.toInt(),+ // OfferDTO.id=1, offer_token=3 (StringValue). CostEstimate.cost_token=3,+ // ride_type=4, cost_token_expiry_time=20 (best-effort; type unverified — dry-run+ // surfaces the built request for validation).+ offerId = offer.string(1),+ offerToken = offer.wrappedString(3),+ costToken = cost?.string(3),+ rideType = cost?.string(4),+ // Epoch seconds (see toQuoteJson) -> ms.+ costTokenExpiryMs = (cost?.wrappedLong(20) ?: cost?.varint(20))?.let { it * 1000 },+ )+ }++ private fun priceRange(min: Long?, max: Long?, upfront: Long?): Pair<Long, Long>? = when {+ min != null && max != null -> min to max+ upfront != null -> upfront to upfront+ min != null -> min to min+ max != null -> max to max+ else -> null+ }++ companion object {+ private const val TAG = "LyftProvider"++ /**+ * Master guard for live ride booking. While false, [createRide] builds and returns the+ * request but never sends it. Flip to true only after the dry-run request body has been+ * verified against a real capture.+ *+ * Note: this gates *ride creation* only. Payment-method management and [cancelRide] are+ * sent live regardless, per product decision.+ */+ const val BOOKING_LIVE = true+ }+}++/**+ * The pieces of a `ReadOffersV2Response` the app keeps: the per-product [quotes] plus the+ * offers-wrapper identifiers reused when booking.+ */+private data class ParsedOffers(+ val quotes: List<RideQuote>,+ val purchaseSessionId: String?,+ val offersResponseId: String?,+) {+ companion object {+ val EMPTY = ParsedOffers(emptyList(), null, null)+ }+}++/**+ * Which processor to tokenize a new card with, and that processor's client [key]. For the modern+ * Stripe SetupIntent strategy (`sbe0` tag 22, `uhc0`) the extra SetupIntent fields are carried too.+ */+private data class TokenizerConfig(+ val provider: String,+ val key: String,+ val clientSecret: String? = null,+ val setupIntentId: String? = null,+ val stripeApiVersion: String? = null,+)++/**+ * Outcome of tokenizing a card at the processor: a Stripe [token] or a Braintree [nonce], plus the+ * [version] (`it00`) the server needs to interpret a Stripe token (STRIPE_TOKEN vs+ * STRIPE_SETUP_INTENT); null for processors that don't send one (Braintree).+ */+private sealed interface TokenizeResult {+ data class Ok(+ val provider: String,+ val token: String?,+ val nonce: String?,+ val version: String? = null,+ ) : TokenizeResult++ data class Err(val message: String) : TokenizeResult+}++/**+ * Minimal read-only protobuf message view over a byte range. Supports exactly the wire types the+ * offers response uses: varint (0), 64-bit (1), length-delimited (2). Accessors return the last+ * value for a field number (protobuf "last one wins"), which is all this parser needs.+ */+private class ProtoMessage(private val buf: ByteArray, start: Int, private val end: Int) {+ // fieldNumber -> list of entries. For wire 0/1 the Long is the value; for wire 2 it is the+ // [start, end) byte range packed as start (in `ranges`).+ private val varints = HashMap<Int, MutableList<Long>>()+ private val fixed64 = HashMap<Int, MutableList<Long>>()+ private val ranges = HashMap<Int, MutableList<IntArray>>()++ init {+ var p = start+ loop@ while (p < end) {+ val (tag, afterTag) = readVarint(buf, p)+ p = afterTag+ val field = (tag ushr 3).toInt()+ when ((tag and 7).toInt()) {+ 0 -> {+ val (v, np) = readVarint(buf, p); p = np+ varints.getOrPut(field) { mutableListOf() }.add(v)+ }+ 1 -> {+ var v = 0L+ for (i in 0 until 8) v = v or ((buf[p + i].toLong() and 0xff) shl (8 * i))+ p += 8+ fixed64.getOrPut(field) { mutableListOf() }.add(v)+ }+ 2 -> {+ val (len, np) = readVarint(buf, p); p = np+ val s = p; val e = p + len.toInt()+ ranges.getOrPut(field) { mutableListOf() }.add(intArrayOf(s, e))+ p = e+ }+ 5 -> p += 4+ else -> break@loop // unknown/invalid wire type: stop rather than misread+ }+ }+ }++ fun varint(field: Int): Long? = varints[field]?.lastOrNull()++ fun double(field: Int): Double? = fixed64[field]?.lastOrNull()?.let { Double.fromBits(it) }++ fun string(field: Int): String? = ranges[field]?.lastOrNull()?.let {+ String(buf, it[0], it[1] - it[0], Charsets.UTF_8)+ }++ fun message(field: Int): ProtoMessage? = ranges[field]?.lastOrNull()?.let {+ ProtoMessage(buf, it[0], it[1])+ }++ fun messages(field: Int): List<ProtoMessage> =+ ranges[field]?.map { ProtoMessage(buf, it[0], it[1]) } ?: emptyList()++ /** A google.protobuf.Int64Value/UInt64Value wrapper: a sub-message with field 1 = the value. */+ fun wrappedLong(field: Int): Long? = message(field)?.varint(1)++ /** A google.protobuf.StringValue wrapper: a sub-message with field 1 = the string. */+ fun wrappedString(field: Int): String? = message(field)?.string(1)++ /** A google.protobuf.BoolValue wrapper: a sub-message with field 1 = the bool (varint). */+ fun wrappedBool(field: Int): Boolean? = message(field)?.varint(1)?.let { it != 0L }++ /** A google.protobuf.DoubleValue wrapper: a sub-message with field 1 = the double. */+ fun wrappedDouble(field: Int): Double? = message(field)?.double(1)++ private companion object {+ fun readVarint(buf: ByteArray, from: Int): Pair<Long, Int> {+ var p = from+ var shift = 0+ var result = 0L+ while (true) {+ val b = buf[p++].toInt() and 0xff+ result = result or ((b and 0x7f).toLong() shl shift)+ if (b < 0x80) break+ shift += 7+ }+ return result to p+ }+ }+}
taxi/src/main/java/com/vayunmathur/taxi/lyft/LyftTokenStore.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/lyft/LyftTokenStore.kt b/taxi/src/main/java/com/vayunmathur/taxi/lyft/LyftTokenStore.ktnew file mode 100644index 0000000000..766fdf91ba--- /dev/null+++ b/taxi/src/main/java/com/vayunmathur/taxi/lyft/LyftTokenStore.kt@@ -0,0 +1,46 @@+package com.vayunmathur.taxi.lyft++import android.content.Context+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.longPreferencesKey+import androidx.datastore.preferences.core.stringPreferencesKey+import androidx.datastore.preferences.preferencesDataStore+import kotlinx.coroutines.flow.first++private val Context.lyftDataStore by preferencesDataStore(name = "lyft_session")++class LyftTokenStore(private val context: Context) {+ private val accessKey = stringPreferencesKey("access_token")+ private val refreshKey = stringPreferencesKey("refresh_token")+ private val expiresAtKey = longPreferencesKey("expires_at")+ private val userIdKey = stringPreferencesKey("user_id")++ suspend fun save(token: LyftToken) {+ context.lyftDataStore.edit {+ it[accessKey] = token.accessToken+ if (!token.refreshToken.isNullOrBlank()) it[refreshKey] = token.refreshToken+ it[expiresAtKey] = System.currentTimeMillis() + token.expiresIn * 1000+ if (!token.userId.isNullOrBlank()) it[userIdKey] = token.userId+ }+ }++ suspend fun accessToken(): String? =+ context.lyftDataStore.data.first()[accessKey]?.takeIf { it.isNotBlank() }++ suspend fun refreshToken(): String? =+ context.lyftDataStore.data.first()[refreshKey]?.takeIf { it.isNotBlank() }++ suspend fun userId(): String? = context.lyftDataStore.data.first()[userIdKey]++ /** Treats the token as expired a minute early so a call never races the expiry. */+ suspend fun isExpired(): Boolean {+ val expiresAt = context.lyftDataStore.data.first()[expiresAtKey] ?: return true+ return System.currentTimeMillis() >= expiresAt - 60_000+ }++ suspend fun isSignedIn(): Boolean = accessToken() != null++ suspend fun clear() {+ context.lyftDataStore.edit { it.clear() }+ }+}
taxi/src/main/java/com/vayunmathur/taxi/provider/QuoteRepository.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/provider/QuoteRepository.kt b/taxi/src/main/java/com/vayunmathur/taxi/provider/QuoteRepository.ktnew file mode 100644index 0000000000..000cd0318f--- /dev/null+++ b/taxi/src/main/java/com/vayunmathur/taxi/provider/QuoteRepository.kt@@ -0,0 +1,59 @@+package com.vayunmathur.taxi.provider++import android.content.Context+import com.vayunmathur.taxi.data.Place+import com.vayunmathur.taxi.data.Provider+import com.vayunmathur.taxi.data.QuoteResult+import com.vayunmathur.taxi.lyft.LyftProvider+import kotlinx.coroutines.async+import kotlinx.coroutines.coroutineScope++object QuoteRepository {++ /**+ * Quotes every enabled provider concurrently. One provider failing must not hide another's+ * prices, so every provider always yields a result rather than throwing. Uber is hidden+ * from the UI, so only Lyft is quoted; its module code stays compiled but unreferenced.+ */+ suspend fun quotes(+ context: Context,+ pickup: Place,+ dropoff: Place,+ ): Map<Provider, QuoteResult> = coroutineScope {+ val providers = listOf(+ LyftProvider(context.applicationContext),+ )+ providers+ .map { provider ->+ provider.provider to async {+ runCatching { provider.quotes(pickup, dropoff) }+ .getOrElse { QuoteResult.Failed(it.message ?: "Request failed") }+ }+ }+ .associate { (key, deferred) -> key to deferred.await() }+ }++ /**+ * Re-quotes to refresh cost tokens that are about to expire, reusing the previous offers+ * session so the server returns the same products with fresh tokens. Falls back to a full+ * quote if the update path returns nothing. Lyft only, mirroring [quotes].+ */+ suspend fun refresh(+ context: Context,+ pickup: Place,+ dropoff: Place,+ previous: Map<Provider, QuoteResult>,+ ): Map<Provider, QuoteResult> {+ val lyft = LyftProvider(context.applicationContext)+ val prev = previous[Provider.LYFT] as? QuoteResult.Success+ val updated = runCatching {+ lyft.updateQuotes(pickup, dropoff, prev?.offersResponseId, prev?.purchaseSessionId)+ }.getOrElse { QuoteResult.Failed(it.message ?: "Request failed") }+ val result = if (updated is QuoteResult.Success) {+ updated+ } else {+ runCatching { lyft.quotes(pickup, dropoff) }.getOrElse { updated }+ }+ return mapOf(Provider.LYFT to result)+ }+}
taxi/src/main/java/com/vayunmathur/taxi/provider/RideProvider.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/provider/RideProvider.kt b/taxi/src/main/java/com/vayunmathur/taxi/provider/RideProvider.ktnew file mode 100644index 0000000000..3745bbd9a8--- /dev/null+++ b/taxi/src/main/java/com/vayunmathur/taxi/provider/RideProvider.kt@@ -0,0 +1,80 @@+package com.vayunmathur.taxi.provider++import com.vayunmathur.taxi.data.AddCardResult+import com.vayunmathur.taxi.data.BookingResult+import com.vayunmathur.taxi.data.CancelResult+import com.vayunmathur.taxi.data.ChargeAccount+import com.vayunmathur.taxi.data.DriverLocation+import com.vayunmathur.taxi.data.NewCard+import com.vayunmathur.taxi.data.PaymentActionResult+import com.vayunmathur.taxi.data.PaymentMethodsResult+import com.vayunmathur.taxi.data.Place+import com.vayunmathur.taxi.data.Provider+import com.vayunmathur.taxi.data.QuoteResult+import com.vayunmathur.taxi.data.RideStatusResult+import com.vayunmathur.taxi.data.RideQuote++/**+ * One ride-hailing service. Quotes come from the service's own API; booking either hands off to+ * the official app via [bookingUri] or, where the provider supports it, books in-app through the+ * methods below. In-app booking is opt-in per provider: the defaults report "unsupported" so a+ * provider that only deep-links (and callers that only quote) need no changes.+ */+interface RideProvider {+ val provider: Provider++ suspend fun isSignedIn(): Boolean++ suspend fun quotes(pickup: Place, dropoff: Place): QuoteResult++ /**+ * Deep link that opens the official app with the trip pre-filled. [quote] selects a+ * specific product where the provider supports it.+ */+ fun bookingUri(pickup: Place, dropoff: Place, quote: RideQuote?): String++ // ------------------------------------------------------------------------------------------+ // In-app booking (optional per provider). Defaults report "unsupported".+ // ------------------------------------------------------------------------------------------++ /** Fetches the user's payment methods live; the list is held in memory only, never stored. */+ suspend fun paymentMethods(): PaymentMethodsResult = PaymentMethodsResult.Unsupported++ /** Marks the given charge account as the account's default. Sent live. */+ suspend fun setDefaultPaymentMethod(id: String): PaymentActionResult =+ PaymentActionResult.Unsupported++ /** Removes the given charge account from the user's account. Sent live. */+ suspend fun removePaymentMethod(id: String): PaymentActionResult =+ PaymentActionResult.Unsupported++ /**+ * Adds a new card. The raw card is tokenized by the provider's payment processor first; only+ * the resulting token/nonce is sent on. Sent live. [makeDefault] sets it as the default.+ */+ suspend fun addCard(card: NewCard, makeDefault: Boolean): AddCardResult =+ AddCardResult.Unsupported++ /**+ * Creates a ride against the selected [quote]. When [dryRun] is true the request is built and+ * returned but never sent, so the exact body can be verified before any real charge.+ * [purchaseSessionId] (from the offers response) is reused so a retried create deduplicates.+ */+ suspend fun createRide(+ quote: RideQuote,+ pickup: Place,+ dropoff: Place,+ account: ChargeAccount?,+ purchaseSessionId: String?,+ dryRun: Boolean,+ ): BookingResult = BookingResult.Unsupported++ /** Reads the ride currently in progress, if any. */+ suspend fun activeRide(): RideStatusResult = RideStatusResult.Unsupported++ /** The driver's live position for [rideId], for higher-frequency marker refresh. */+ suspend fun driverLocation(rideId: String): DriverLocation? = null++ /** Cancels the ride with [rideId]. The server response is surfaced verbatim (may carry a fee). */+ suspend fun cancelRide(rideId: String): CancelResult = CancelResult.Unsupported+}
taxi/src/main/java/com/vayunmathur/taxi/uber/UberAuth.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/uber/UberAuth.kt b/taxi/src/main/java/com/vayunmathur/taxi/uber/UberAuth.ktnew file mode 100644index 0000000000..b1a2ac0beb--- /dev/null+++ b/taxi/src/main/java/com/vayunmathur/taxi/uber/UberAuth.kt@@ -0,0 +1,168 @@+package com.vayunmathur.taxi.uber++import android.os.Build+import android.util.Log+import com.vayunmathur.library.network.NetworkClient+import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import java.util.UUID++/**+ * Native Uber sign-in against the "silkscreen" onboarding service.+ *+ * Recovered from `com.uber.model.core.generated.rtapi.services.silkscreen.SilkScreenApi`:+ *+ * ```java+ * @POST("/rt/silk-screen/submit-form")+ * Single<OnboardingFormContainer> submitForm(@Header("x-uber-call-uuid") String, @Body Map);+ * ```+ *+ * The flow is a server-driven form machine: you POST a screen answer, the server replies with+ * the next screen to render, and you repeat until it hands back a session. Screen and field+ * names come from `OnboardingScreenType` / `OnboardingFieldType`, and the request wrapper from+ * `OnboardingFormContainerAnswer` (`inAuthSessionID` + `formAnswer`).+ *+ * Caveat that decides whether this can work at all: `OnboardingFormAnswer` carries a+ * `deviceData` field, which in the official app is produced by the `libse_loader.so` security+ * engine (see `uber-re/api-notes.md` §3). We send it empty. If the server rejects that, native+ * login is not reachable off a Google-attested device and the WebView path stands.+ */+object UberAuth {+ private const val TAG = "UberAuth"+ const val BASE = "https://cn-geo1.uber.com"++ private const val APP_VERSION = "4.641.10000"+ private const val CLIENT_NAME = "client"++ private val json = Json { ignoreUnknownKeys = true; isLenient = true; explicitNulls = false }++ private fun headers() = mapOf(+ "x-uber-call-uuid" to UUID.randomUUID().toString(),+ "x-uber-client-name" to CLIENT_NAME,+ "x-uber-client-version" to APP_VERSION,+ "x-uber-device" to "android",+ "x-uber-device-os" to Build.VERSION.RELEASE,+ "x-uber-app-variant" to "rider",+ "Content-Type" to "application/json",+ "Accept" to "application/json",+ "User-Agent" to "client/$APP_VERSION (Android ${Build.VERSION.RELEASE}; ${Build.MODEL})",+ )++ /** Starts the flow with a phone number; on success Uber texts an OTP. */+ suspend fun startPhoneLogin(countryCode: String, phoneNumber: String): UberAuthResult =+ submit(+ inAuthSessionID = "",+ screen = ScreenAnswer(+ screenType = "PHONE_NUMBER_INITIAL",+ fieldAnswers = listOf(+ FieldAnswer(fieldType = "PHONE_COUNTRY_CODE", phoneCountryCode = countryCode),+ FieldAnswer(fieldType = "PHONE_NUMBER", phoneNumber = phoneNumber),+ ),+ ),+ )++ /** Answers the SMS OTP screen. */+ suspend fun submitSmsOtp(sessionId: String, code: String): UberAuthResult =+ submit(+ inAuthSessionID = sessionId,+ screen = ScreenAnswer(+ screenType = "PHONE_OTP",+ fieldAnswers = listOf(+ FieldAnswer(fieldType = "PHONE_SMS_OTP", phoneSMSOTP = code),+ ),+ ),+ )++ private suspend fun submit(inAuthSessionID: String, screen: ScreenAnswer): UberAuthResult {+ val body = json.encodeToString(+ FormContainerAnswer.serializer(),+ FormContainerAnswer(+ inAuthSessionID = inAuthSessionID,+ formAnswer = FormAnswer(+ flowType = if (inAuthSessionID.isEmpty()) "INITIAL" else "SIGN_IN",+ screenAnswers = listOf(screen),+ deviceData = "",+ standardFlow = true,+ ),+ ),+ )+ val resp = NetworkClient.performRequest(+ url = "$BASE/rt/silk-screen/submit-form",+ method = "POST",+ headers = headers(),+ body = body,+ )+ Log.d(TAG, "POST /rt/silk-screen/submit-form -> ${resp.status}")+ if (!resp.isSuccess) {+ Log.w(TAG, "submit-form ${resp.status}: ${resp.body.take(800)}")+ return UberAuthResult.Failed("HTTP ${resp.status}: ${resp.body.take(300)}")+ }+ Log.d(TAG, "submit-form ok: ${resp.body.take(800)}")+ val container = runCatching {+ json.decodeFromString(FormContainer.serializer(), resp.body)+ }.getOrElse { return UberAuthResult.Failed("Unreadable silkscreen response") }+ return UberAuthResult.NextScreen(+ sessionId = container.inAuthSessionID.orEmpty(),+ screenType = container.form?.screens?.firstOrNull()?.screenType,+ raw = resp.body,+ )+ }+}++sealed interface UberAuthResult {+ /** Server accepted the answer and wants the next screen filled in. */+ data class NextScreen(+ val sessionId: String,+ val screenType: String?,+ val raw: String,+ ) : UberAuthResult++ data class Failed(val message: String) : UberAuthResult+}++@Serializable+private data class FormContainerAnswer(+ val inAuthSessionID: String,+ val formAnswer: FormAnswer,+)++@Serializable+private data class FormAnswer(+ val flowType: String,+ val screenAnswers: List<ScreenAnswer>,+ val deviceData: String,+ val standardFlow: Boolean,+)++@Serializable+private data class ScreenAnswer(+ val screenType: String,+ val fieldAnswers: List<FieldAnswer>,+)++@Serializable+private data class FieldAnswer(+ val fieldType: String,+ val phoneNumber: String? = null,+ val phoneCountryCode: String? = null,+ val phoneSMSOTP: String? = null,+ val emailAddress: String? = null,+ val password: String? = null,+)++@Serializable+private data class FormContainer(+ val inAuthSessionID: String? = null,+ val form: Form? = null,+)++@Serializable+private data class Form(+ val screens: List<Screen> = emptyList(),+)++@Serializable+private data class Screen(+ @SerialName("screenType") val screenType: String? = null,+)
taxi/src/main/java/com/vayunmathur/taxi/uber/UberProvider.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/uber/UberProvider.kt b/taxi/src/main/java/com/vayunmathur/taxi/uber/UberProvider.ktnew file mode 100644index 0000000000..891e18025e--- /dev/null+++ b/taxi/src/main/java/com/vayunmathur/taxi/uber/UberProvider.kt@@ -0,0 +1,37 @@+package com.vayunmathur.taxi.uber++import com.vayunmathur.taxi.data.Place+import com.vayunmathur.taxi.data.Provider+import com.vayunmathur.taxi.data.QuoteResult+import com.vayunmathur.taxi.data.RideQuote+import com.vayunmathur.taxi.deeplink.RideDeepLinks+import com.vayunmathur.taxi.provider.RideProvider++/**+ * Uber fares via the web GraphQL endpoint (`uber-re/api-notes.md` §4).+ *+ * The native `/rt/` API is deliberately not used: it signs requests with `libse_loader.so` and+ * attests with Play Integrity, neither of which is available on a degoogled device.+ *+ * The web endpoint is reachable and cookie-authenticated, but its fare **operation name and+ * variables are not yet known** — Apollo introspection is disabled server-side, so they have to+ * come out of a real session via [UberWebView]'s capture hook. Until that has been run once,+ * this reports honestly rather than guessing at an operation.+ */+class UberProvider(private val context: android.content.Context) : RideProvider {+ override val provider = Provider.UBER++ override suspend fun isSignedIn(): Boolean =+ UberSession(context.applicationContext).isSignedIn()++ override suspend fun quotes(pickup: Place, dropoff: Place): QuoteResult {+ if (!isSignedIn()) return QuoteResult.NotSignedIn+ return QuoteResult.Failed(+ "Signed in, but the fare query hasn't been captured yet — " ++ "open Uber under Settings and request a ride to record it",+ )+ }++ override fun bookingUri(pickup: Place, dropoff: Place, quote: RideQuote?): String =+ RideDeepLinks.webUri(Provider.UBER, pickup, dropoff, quote)+}
taxi/src/main/java/com/vayunmathur/taxi/uber/UberSession.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/uber/UberSession.kt b/taxi/src/main/java/com/vayunmathur/taxi/uber/UberSession.ktnew file mode 100644index 0000000000..93a1de510d--- /dev/null+++ b/taxi/src/main/java/com/vayunmathur/taxi/uber/UberSession.kt@@ -0,0 +1,44 @@+package com.vayunmathur.taxi.uber++import android.content.Context+import androidx.datastore.preferences.core.booleanPreferencesKey+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.preferencesDataStore+import kotlinx.coroutines.flow.first++private val Context.uberDataStore by preferencesDataStore(name = "uber_session")++/**+ * Whether we believe the WebView holds a logged-in Uber session.+ *+ * This is persisted rather than derived from cookies. `m.uber.com` sets `sid`, `csid`,+ * `jwt-session` and others on the *first page load*, before any sign-in, so no cookie-name+ * check can distinguish an anonymous visitor from an authenticated one — an earlier version+ * of this reported "Signed in" before the user had ever logged in.+ *+ * Instead [UberWebView] reports each page it lands on, and we flip the flag when navigation+ * settles somewhere that is not the auth host.+ */+class UberSession(private val context: Context) {+ private val signedInKey = booleanPreferencesKey("signed_in")++ suspend fun isSignedIn(): Boolean =+ context.uberDataStore.data.first()[signedInKey] ?: false++ suspend fun setSignedIn(value: Boolean) {+ context.uberDataStore.edit { it[signedInKey] = value }+ }++ suspend fun clear() {+ context.uberDataStore.edit { it.clear() }+ UberCookies.clear()+ }++ companion object
Diff truncated.