Modern Apps git

← Modern-Apps.git

maps: drop the online MOTIS journey-planning fallback

Commit
e1b01804ba9c9b46427d68622c41791316e1e31d
Author
vayun-mathur <[email protected]>
When
2026-08-21 01:35 UTC (3 months ago)
Parents
015c92c
The on-device RAPTOR planner is now the only transit planner: when no offline pack covers a route, transit routing returns null instead of calling GET /api/v1/plan. Reverts b87a3e301 in effect -- the precision-7 polyline decoder had no other caller, since offline ride legs take their geometry from the pack's baked GTFS shapes.

Diff

maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.ktindex e99c076c32..b5d584ed62 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt@@ -1,17 +1,11 @@ package com.vayunmathur.maps.data.transit  import com.vayunmathur.library.network.NetworkClient-import com.vayunmathur.maps.util.RouteService import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext-import org.maplibre.spatialk.geojson.Position import java.net.URLEncoder import java.time.Instant import java.time.OffsetDateTime-import java.time.format.DateTimeFormatter-import java.util.Locale-import kotlin.math.pow-import kotlin.time.Duration.Companion.seconds  /**  * Online public-transit data source (P10) backed by **Transitous** — a free,@@ -165,135 +159,6 @@ object TransitousDataSource {         resp.stopTimes.mapNotNull { it.toDeparture() }     } -    /**-     * Online transit journey planning (P11d fallback) via MOTIS-     * `GET /api/v1/plan`. Used when no offline `*.transit` index covers the-     * route. Never throws - returns null on any failure so the UI simply shows-     * no transit route. On-device only (needs the network); verified by shape.-     *-     * Per-leg geometry comes from MOTIS's encoded `legGeometry`, so an online-     * journey follows the same real roads and rails the offline planner draws. A-     * leg that carries no geometry falls back to a straight line between its-     * endpoints.-     */-    suspend fun planRoute(-        from: Position,-        to: Position,-    ): RouteService.Route? = withContext(Dispatchers.IO) {-        runCatching {-            val url = "$BASE_URL/api/v1/plan" +-                "?fromPlace=${enc("${from.latitude},${from.longitude}")}" +-                "&toPlace=${enc("${to.latitude},${to.longitude}")}&arriveBy=false"-            val resp: MotisPlanResponse =-                NetworkClient.getJson(url, REQUEST_HEADERS, useSystemTrust = true)-            val itinerary = resp.itineraries.firstOrNull() ?: return@runCatching null--            val polyline = mutableListOf<Position>()-            val steps = mutableListOf<RouteService.Step>()-            var totalDistance = 0.0-            var totalSeconds = 0L--            for (leg in itinerary.legs) {-                val f = leg.from ?: continue-                val t = leg.to ?: continue-                val fp = Position(f.lon, f.lat)-                val tp = Position(t.lon, t.lat)-                val geometry = leg.legGeometry-                    ?.let { decodePolyline(it.points, it.precision) }-                    ?.takeIf { it.size >= 2 }-                    ?: listOf(fp, tp)-                for (p in geometry) {-                    if (polyline.isEmpty() || polyline.last() != p) polyline.add(p)-                }--                val isTransit = !"WALK".equals(leg.mode, ignoreCase = true)-                totalDistance += leg.distance-                totalSeconds += leg.duration--                steps.add(-                    RouteService.Step(-                        distanceMeters = leg.distance,-                        staticDuration = leg.duration.seconds,-                        polyline = geometry,-                        navInstruction = RouteService.API.NavInstruction(-                            if (isTransit) RouteService.API.Maneuver.RIDE-                            else RouteService.API.Maneuver.MANEUVER_UNSPECIFIED,-                            ""-                        ),-                        travelMode = if (isTransit) RouteService.TravelMode.TRANSIT-                        else RouteService.TravelMode.WALK,-                        transitDetails = if (isTransit) RouteService.API.TransitDetails(-                            headsign = leg.headsign ?: "",-                            stopCount = 0,-                            transitLine = RouteService.API.TransitLine(-                                name = leg.routeShortName ?: leg.mode ?: "",-                                color = leg.routeColor?.ifBlank { null }-                                    ?.let { if (it.startsWith("#")) it else "#$it" }-                                    ?: "#FF0000"-                            ),-                            stopDetails = RouteService.API.StopDetails(-                                arrivalTime = formatClock(t.arrival ?: t.scheduledArrival),-                                departureTime = formatClock(f.departure ?: f.scheduledDeparture),-                                arrivalStop = RouteService.API.Stop(t.name ?: ""),-                                departureStop = RouteService.API.Stop(f.name ?: "")-                            ),-                            feedName = null-                        ) else null-                    )-                )-            }-            if (steps.isEmpty()) return@runCatching null-            RouteService.Route(-                duration = totalSeconds.seconds,-                distanceMeters = totalDistance,-                polyline = polyline,-                step = steps,-            )-        }.getOrNull()-    }--    /**-     * Decode an OTP/Google encoded polyline into positions.-     *-     * `precision` must come from the response: MOTIS uses 7 where Google's-     * original format used 5, and decoding one as the other misplaces every point-     * by a factor of 100. Values are zigzag-encoded deltas in chunks of five bits,-     * offset by 63 into printable ASCII. A truncated tail is dropped rather than-     * throwing — a half-decoded line still draws.-     *-     * The accumulator is a [Long] because at precision 7 a zigzagged longitude-     * delta reaches ~2.4e9, which overflows a signed 32-bit int: a whole-degree-     * first delta is routine, and wrapping it silently yields a plausible-looking-     * coordinate on the wrong side of the planet.-     */-    internal fun decodePolyline(encoded: String, precision: Int): List<Position> {-        if (encoded.isEmpty()) return emptyList()-        val scale = 10.0.pow(precision)-        val out = ArrayList<Position>()-        var i = 0-        var lat = 0L-        var lon = 0L-        fun nextDelta(): Long? {-            var shift = 0-            var result = 0L-            while (true) {-                if (i >= encoded.length) return null-                val b = (encoded[i++].code - 63).toLong()-                result = result or ((b and 0x1f) shl shift)-                if (b < 0x20) break-                shift += 5-            }-            // Zigzag: the low bit carries the sign.-            return if (result and 1L != 0L) (result shr 1).inv() else result shr 1-        }-        while (i < encoded.length) {-            lat += nextDelta() ?: break-            lon += nextDelta() ?: break-            out.add(Position(lon / scale, lat / scale))-        }-        return out-    }-     /** Map a MOTIS stoptime → app [Departure]; drop entries with no usable      *  departure time. Delay is realtime − scheduled in whole minutes. */     private fun MotisStopTime.toDeparture(): Departure? {@@ -325,18 +190,6 @@ object TransitousDataSource {             .getOrNull()     } -    /**-     * A MOTIS ISO-8601 timestamp as a wall clock `HH:mm` in its own zone offset,-     * matching what the offline planner puts in `StopDetails` so the directions-     * UI can render either source without knowing which produced it.-     */-    private fun formatClock(iso: String?): String {-        if (iso.isNullOrBlank()) return ""-        return runCatching {-            OffsetDateTime.parse(iso).format(DateTimeFormatter.ofPattern("HH:mm", Locale.ROOT))-        }.getOrDefault("")-    }-     private fun round3(v: Double): Double = Math.round(v * 1000.0) / 1000.0     private fun enc(s: String): String = URLEncoder.encode(s, "UTF-8") }
maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.kt b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.ktindex 50055245ac..5a440df6f4 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.kt@@ -97,65 +97,3 @@ data class MotisPlace(     val track: String? = null,     @SerialName("scheduledTrack") val scheduledTrack: String? = null, )--// --- MOTIS v1 journey planning (`GET /api/v1/plan`) — P11d online fallback -----/** Response of `GET /api/v1/plan`: a list of candidate itineraries. */-@Serializable-data class MotisPlanResponse(-    val itineraries: List<MotisItinerary> = emptyList(),-)--/** One end-to-end itinerary; `duration` is whole seconds. */-@Serializable-data class MotisItinerary(-    val duration: Long = 0,-    val legs: List<MotisLeg> = emptyList(),-)--/**- * One leg of an itinerary. `mode` is `WALK` for walking legs, otherwise a- * transit mode (`BUS`, `TRAM`, `SUBWAY`, `RAIL`, …). `duration` is whole- * seconds and `distance` is metres.- */-@Serializable-data class MotisLeg(-    val mode: String? = null,-    val from: MotisPlanPlace? = null,-    val to: MotisPlanPlace? = null,-    val duration: Long = 0,-    val distance: Double = 0.0,-    val routeShortName: String? = null,-    val routeColor: String? = null,-    val headsign: String? = null,-    val tripId: String? = null,-    val legGeometry: MotisLegGeometry? = null,-)--/**- * A leg's real path, as an OTP/Google encoded polyline.- *- * `precision` is the number of decimal places the integer deltas are scaled by,- * and MOTIS sends **7** — not the 5 that Google's format popularised. It is read- * from the response rather than assumed because decoding precision-7 data as- * precision-5 puts every point 100x out. The default matches what- * `api.transitous.org` actually sends, for the case where the field is absent.- */-@Serializable-data class MotisLegGeometry(-    val points: String = "",-    val precision: Int = 7,-)--/** A leg endpoint in a plan response (position + name + ISO-8601 times). */-@Serializable-data class MotisPlanPlace(-    val name: String? = null,-    val stopId: String? = null,-    val lat: Double = 0.0,-    val lon: Double = 0.0,-    val arrival: String? = null,-    val departure: String? = null,-    @SerialName("scheduledArrival") val scheduledArrival: String? = null,-    @SerialName("scheduledDeparture") val scheduledDeparture: String? = null,-)
maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.ktindex 87b45f60d0..bffdc49826 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt@@ -354,7 +354,8 @@ object OfflineRouter {      /**      * Plan a route for any [mode]. TRANSIT goes to the on-device RAPTOR planner-     * (falling back to the online MOTIS planner); every other mode goes to the+     * and nowhere else — there is no online routing fallback, so a journey the+     * pack cannot plan yields no transit route. Every other mode goes to the      * road graph via [getRouteMulti].      *      * This is the **only** correct entry point for a caller whose mode is not a@@ -376,11 +377,6 @@ object OfflineRouter {         val start = positions.first()         val end = positions.last()         getTransitRouteOffline(context, start, end)-                ?: if (ConnectivityMonitor.isOnline(context)) {-                    TransitousDataSource.planRoute(start, end)-                } else {-                    null-                }     }      /**
maps/src/test/java/com/vayunmathur/maps/data/transit/TransitousPolylineTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/data/transit/TransitousPolylineTest.kt b/maps/src/test/java/com/vayunmathur/maps/data/transit/TransitousPolylineTest.ktdeleted file mode 100644index 2839ef31a7..0000000000--- a/maps/src/test/java/com/vayunmathur/maps/data/transit/TransitousPolylineTest.kt+++ /dev/null@@ -1,84 +0,0 @@-package com.vayunmathur.maps.data.transit--import kotlin.math.abs-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertTrue--/**- * MOTIS encodes each leg's real path as an OTP/Google polyline at **precision 7**,- * not the 5 the format is usually seen with. Getting that wrong does not fail- * loudly — it silently draws every route 100x away from where it belongs — so the- * decoder is pinned here against a payload captured from `api.transitous.org`.- */-class TransitousPolylineTest {--    /**-     * The first leg of a real 2026 `GET /api/v1/plan` response for San Francisco →-     * Oakland, verbatim. `precision` was 7 and `length` was 29. Note the `??`-     * runs: those are zero deltas, i.e. repeated points, which a decoder must-     * carry through rather than choke on.-     */-    private val sfLeg =-        "sz}noUrsz}}gAgIqH??q[ed@??_i@gv@??oRsW??eKmM??iIqK??iM}T??yJuO??kKoW??u[ei@mm@my@coBuuB??cV{[??wK{N??hMmRrJaN"--    @Test-    fun `decodes a captured MOTIS leg at precision 7`() {-        val points = TransitousDataSource.decodePolyline(sfLeg, precision = 7)-        assertEquals(29, points.size, "the response declared length 29")-        // The leg starts at the requested origin in San Francisco.-        val first = points.first()-        assertTrue(-            abs(first.latitude - 37.7749) < 0.01 && abs(first.longitude - -122.4194) < 0.01,-            "first point should be the SF origin, was $first",-        )-        // Every point stays in the Bay Area, which is the assertion that actually-        // catches a precision mix-up.-        for (p in points) {-            assertTrue(-                p.latitude in 37.0..38.5 && p.longitude in -123.0..-121.5,-                "point outside the Bay Area: $p",-            )-        }-    }--    @Test-    fun `decoding at the wrong precision moves the route off the planet`() {-        // Guards the reason `precision` is read from the response instead of being-        // a constant: precision 5 on precision-7 data is off by 100x.-        val wrong = TransitousDataSource.decodePolyline(sfLeg, precision = 5).first()-        assertTrue(-            abs(wrong.latitude) > 90.0,-            "precision 5 should produce a nonsense latitude, got $wrong",-        )-    }--    @Test-    fun `a whole degree delta does not overflow`() {-        // At precision 7 the zigzagged longitude delta of the first point reaches-        // ~2.4e9, past Int.MAX_VALUE. Accumulating in an Int wraps it into a-        // plausible-looking coordinate on the wrong side of the planet instead of-        // failing, so pin the real longitude.-        val first = TransitousDataSource.decodePolyline(sfLeg, precision = 7).first()-        assertEquals(-122.4193866, first.longitude, 1e-7)-        assertEquals(37.7748922, first.latitude, 1e-7)-    }--    @Test-    fun `decodes a known two point line`() {-        // The canonical Google example, at its native precision 5.-        val points = TransitousDataSource.decodePolyline("_p~iF~ps|U_ulLnnqC", precision = 5)-        assertEquals(2, points.size)-        assertEquals(38.5, points[0].latitude, 1e-6)-        assertEquals(-120.2, points[0].longitude, 1e-6)-        assertEquals(40.7, points[1].latitude, 1e-6)-        assertEquals(-120.95, points[1].longitude, 1e-6)-    }--    @Test-    fun `an empty or truncated polyline yields no crash`() {-        assertTrue(TransitousDataSource.decodePolyline("", precision = 7).isEmpty())-        // A lone latitude delta with no matching longitude is dropped.-        assertTrue(TransitousDataSource.decodePolyline("_p~iF", precision = 5).isEmpty())-    }-}