From f78b40c86691f90f9df8b914f8b05dccdc16f9c4 Mon Sep 17 00:00:00 2001 From: zakaria5729 Date: Mon, 26 Oct 2026 20:31:41 +0600 Subject: [PATCH 1/8] feat(network): let a completion observer see finished requests Adds NetworkTransactionRecorder.withCompletionObserver(...). The observer gets every completed request with its raw body and status before capture rules and redaction run, so a feature can react to traffic the capture rules exclude. Provisional streaming records are skipped so a request is only reported once. --- sdk/network/api/network.api | 5 +++ .../io/devconsole/network/NetworkCapture.kt | 19 ++++++++- .../network/NetworkTransactionRecorderTest.kt | 42 +++++++++++++++++++ 3 files changed, 64 insertions(+), 2 deletions(-) diff --git a/sdk/network/api/network.api b/sdk/network/api/network.api index 0f08c88..f22f3fe 100644 --- a/sdk/network/api/network.api +++ b/sdk/network/api/network.api @@ -299,6 +299,10 @@ public final class io/devconsole/network/NetworkCaptureLimits { public final class io/devconsole/network/NetworkCaptureLimits$Companion { } +public abstract interface class io/devconsole/network/NetworkCompletionObserver { + public abstract fun onCompleted (Lio/devconsole/network/NetworkRequestInput;Lio/devconsole/network/NetworkResponseInput;)V +} + public final class io/devconsole/network/NetworkCursorCodec { public fun ([B)V public final fun decode (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Integer; @@ -544,6 +548,7 @@ public final class io/devconsole/network/NetworkTransactionRecorder { public final fun record (Lio/devconsole/network/NetworkRequestInput;Lio/devconsole/network/NetworkResponseInput;JLjava/lang/Long;Ljava/lang/String;)V public final fun withAttachmentSink (Lio/devconsole/network/NetworkAttachmentSink;)Lio/devconsole/network/NetworkTransactionRecorder; public final fun withCaptureGate (Lio/devconsole/network/NetworkCaptureGate;)Lio/devconsole/network/NetworkTransactionRecorder; + public final fun withCompletionObserver (Lio/devconsole/network/NetworkCompletionObserver;)Lio/devconsole/network/NetworkTransactionRecorder; public final fun withSessionIdProvider (Lkotlin/jvm/functions/Function0;)Lio/devconsole/network/NetworkTransactionRecorder; } diff --git a/sdk/network/src/main/kotlin/io/devconsole/network/NetworkCapture.kt b/sdk/network/src/main/kotlin/io/devconsole/network/NetworkCapture.kt index c72974a..a5e5217 100644 --- a/sdk/network/src/main/kotlin/io/devconsole/network/NetworkCapture.kt +++ b/sdk/network/src/main/kotlin/io/devconsole/network/NetworkCapture.kt @@ -645,6 +645,13 @@ fun interface NetworkCaptureGate { ): Boolean } +fun interface NetworkCompletionObserver { + fun onCompleted( + request: NetworkRequestInput, + response: NetworkResponseInput?, + ) +} + /** * Bridges redacted capture to the bounded transaction store without affecting host behavior. * When [enabled] is false, [record] returns immediately without building a capture or touching @@ -680,6 +687,8 @@ class NetworkTransactionRecorder( @Volatile private var captureGate: NetworkCaptureGate? = null + @Volatile private var completionObserver: NetworkCompletionObserver? = null + /** Lazy so a disabled recorder never allocates the buffer; [record] returns before touching it. */ private val queue: LinkedBlockingQueue by lazy { LinkedBlockingQueue(maxQueueSize) } @@ -699,6 +708,9 @@ class NetworkTransactionRecorder( /** Installs the capture-exclusion gate; without one every enabled recording is captured. */ fun withCaptureGate(gate: NetworkCaptureGate): NetworkTransactionRecorder = apply { captureGate = gate } + fun withCompletionObserver(observer: NetworkCompletionObserver): NetworkTransactionRecorder = + apply { completionObserver = observer } + fun record( request: NetworkRequestInput, response: NetworkResponseInput?, @@ -727,10 +739,13 @@ class NetworkTransactionRecorder( transactionId: String?, ) { val gate = captureGate + if (!enabled) return + if (completedAtEpochMs != null) { + completionObserver?.let { observer -> runCatching { observer.onCompleted(request, response) } } + } // A gate failure must never suppress capture silently, so an exception means "capture". val allowed = - enabled && - (gate == null || runCatching { gate.allowsCapture(request.method, request.url) }.getOrDefault(true)) + gate == null || runCatching { gate.allowsCapture(request.method, request.url) }.getOrDefault(true) if (!allowed) return val item = PendingRecord( diff --git a/sdk/network/src/test/kotlin/io/devconsole/network/NetworkTransactionRecorderTest.kt b/sdk/network/src/test/kotlin/io/devconsole/network/NetworkTransactionRecorderTest.kt index 0ea6467..d5ca520 100644 --- a/sdk/network/src/test/kotlin/io/devconsole/network/NetworkTransactionRecorderTest.kt +++ b/sdk/network/src/test/kotlin/io/devconsole/network/NetworkTransactionRecorderTest.kt @@ -225,6 +225,48 @@ class NetworkTransactionRecorderTest { assertEquals("attachment-response", transaction.capture.response?.attachmentId) } + @Test + fun `completion observer sees raw completed requests even when the capture gate excludes them`() { + val observed = CopyOnWriteArrayList>() + val recorder = + NetworkTransactionRecorder( + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + store = InMemoryNetworkTransactionStore(NetworkCursorCodec("network-cursor-key".encodeToByteArray())), + ).withCaptureGate { _, _ -> false } + .withCompletionObserver { request, response -> observed += request.url to response?.statusCode } + + recorder.record( + NetworkRequestInput("POST", "https://api.test/pings?token=raw"), + NetworkResponseInput(201), + 100, + 125, + ) + recorder.record( + NetworkRequestInput("POST", "https://api.test/streaming"), + NetworkResponseInput(200), + 100, + null, + "tx", + ) + + assertEquals(listOf("https://api.test/pings?token=raw" to 201), observed.toList()) + } + + @Test + fun `completion observer is not called by a disabled recorder`() { + val observed = CopyOnWriteArrayList() + val recorder = + NetworkTransactionRecorder( + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + store = InMemoryNetworkTransactionStore(NetworkCursorCodec("network-cursor-key".encodeToByteArray())), + enabled = false, + ).withCompletionObserver { request, _ -> observed += request.url } + + recorder.record(NetworkRequestInput("POST", "https://api.test/pings"), NetworkResponseInput(201), 100, 125) + + assertTrue(observed.isEmpty()) + } + private fun awaitTransaction( store: NetworkTransactionStore, id: String, From c64034b92299ed505c27851c634e57a5a8249a35 Mon Sep 17 00:00:00 2001 From: zakaria5729 Date: Mon, 26 Oct 2026 20:31:41 +0600 Subject: [PATCH 2/8] feat: add location-ping module for recording ping requests New sdk:location-ping module. The host describes its ping endpoints (LocationPingStream) and the body shape (LocationPingSchema), and LocationPingStore appends matching request bodies as JSON lines, one file per stream, group id and day. It enforces a storage cap, rejects path traversal in stream and file names, and reads a track back as points ordered by device time with device and fix time gaps. Pings can be answered, dropped on device or never sent, and each outcome is kept with the ping. --- sdk/location-ping/api/location-ping.api | 250 ++++++++++++++ sdk/location-ping/build.gradle.kts | 5 + .../locationping/LocationPingOutcome.kt | 50 +++ .../locationping/LocationPingStore.kt | 273 +++++++++++++++ .../locationping/LocationPingTrack.kt | 74 ++++ .../locationping/LocationPingTrackReader.kt | 122 +++++++ .../locationping/LocationPingTracking.kt | 68 ++++ .../io/devconsole/locationping/PingJson.kt | 247 ++++++++++++++ .../locationping/LocationPingStoreTest.kt | 319 ++++++++++++++++++ settings.gradle.kts | 1 + 10 files changed, 1409 insertions(+) create mode 100644 sdk/location-ping/api/location-ping.api create mode 100644 sdk/location-ping/build.gradle.kts create mode 100644 sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingOutcome.kt create mode 100644 sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingStore.kt create mode 100644 sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingTrack.kt create mode 100644 sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingTrackReader.kt create mode 100644 sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingTracking.kt create mode 100644 sdk/location-ping/src/main/kotlin/io/devconsole/locationping/PingJson.kt create mode 100644 sdk/location-ping/src/test/kotlin/io/devconsole/locationping/LocationPingStoreTest.kt diff --git a/sdk/location-ping/api/location-ping.api b/sdk/location-ping/api/location-ping.api new file mode 100644 index 0000000..7a36a10 --- /dev/null +++ b/sdk/location-ping/api/location-ping.api @@ -0,0 +1,250 @@ +public final class io/devconsole/locationping/InMemoryLocationPingSwitches : io/devconsole/locationping/LocationPingSwitches { + public fun ()V + public fun isEnabled (Ljava/lang/String;)Z + public fun setEnabled (Ljava/lang/String;Z)V +} + +public final class io/devconsole/locationping/LocationPingDeleteResult { + public fun (II)V + public final fun component1 ()I + public final fun component2 ()I + public final fun copy (II)Lio/devconsole/locationping/LocationPingDeleteResult; + public static synthetic fun copy$default (Lio/devconsole/locationping/LocationPingDeleteResult;IIILjava/lang/Object;)Lio/devconsole/locationping/LocationPingDeleteResult; + public fun equals (Ljava/lang/Object;)Z + public final fun getFilesDeleted ()I + public final fun getFilesLeft ()I + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public abstract interface class io/devconsole/locationping/LocationPingOutcome { + public static final field Companion Lio/devconsole/locationping/LocationPingOutcome$Companion; + public static fun answered (I)Lio/devconsole/locationping/LocationPingOutcome; + public static fun droppedOnDevice ()Lio/devconsole/locationping/LocationPingOutcome; + public static fun noConnection ()Lio/devconsole/locationping/LocationPingOutcome; +} + +public final class io/devconsole/locationping/LocationPingOutcome$Answered : io/devconsole/locationping/LocationPingOutcome { + public fun (I)V + public final fun component1 ()I + public final fun copy (I)Lio/devconsole/locationping/LocationPingOutcome$Answered; + public static synthetic fun copy$default (Lio/devconsole/locationping/LocationPingOutcome$Answered;IILjava/lang/Object;)Lio/devconsole/locationping/LocationPingOutcome$Answered; + public fun equals (Ljava/lang/Object;)Z + public final fun getStatusCode ()I + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/locationping/LocationPingOutcome$Companion { + public final fun answered (I)Lio/devconsole/locationping/LocationPingOutcome; + public final fun droppedOnDevice ()Lio/devconsole/locationping/LocationPingOutcome; + public final fun noConnection ()Lio/devconsole/locationping/LocationPingOutcome; +} + +public final class io/devconsole/locationping/LocationPingOutcome$DroppedOnDevice : io/devconsole/locationping/LocationPingOutcome { + public static final field INSTANCE Lio/devconsole/locationping/LocationPingOutcome$DroppedOnDevice; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/locationping/LocationPingOutcome$NoConnection : io/devconsole/locationping/LocationPingOutcome { + public static final field INSTANCE Lio/devconsole/locationping/LocationPingOutcome$NoConnection; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/locationping/LocationPingPoint { + public fun (IDDJDLjava/lang/Long;Ljava/lang/Double;Lio/devconsole/locationping/LocationPingOutcome;Ljava/lang/String;Ljava/util/Map;)V + public final fun component1 ()I + public final fun component10 ()Ljava/util/Map; + public final fun component2 ()D + public final fun component3 ()D + public final fun component4 ()J + public final fun component5 ()D + public final fun component6 ()Ljava/lang/Long; + public final fun component7 ()Ljava/lang/Double; + public final fun component8 ()Lio/devconsole/locationping/LocationPingOutcome; + public final fun component9 ()Ljava/lang/String; + public final fun copy (IDDJDLjava/lang/Long;Ljava/lang/Double;Lio/devconsole/locationping/LocationPingOutcome;Ljava/lang/String;Ljava/util/Map;)Lio/devconsole/locationping/LocationPingPoint; + public static synthetic fun copy$default (Lio/devconsole/locationping/LocationPingPoint;IDDJDLjava/lang/Long;Ljava/lang/Double;Lio/devconsole/locationping/LocationPingOutcome;Ljava/lang/String;Ljava/util/Map;ILjava/lang/Object;)Lio/devconsole/locationping/LocationPingPoint; + public fun equals (Ljava/lang/Object;)Z + public final fun getAppState ()Ljava/lang/String; + public final fun getDeviceTimeEpochMs ()J + public final fun getDeviceTimeGapSeconds ()D + public final fun getFields ()Ljava/util/Map; + public final fun getFixTimeEpochMs ()Ljava/lang/Long; + public final fun getFixTimeGapSeconds ()Ljava/lang/Double; + public final fun getIndex ()I + public final fun getLatitude ()D + public final fun getLongitude ()D + public final fun getOutcome ()Lio/devconsole/locationping/LocationPingOutcome; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/locationping/LocationPingSchema { + public fun ()V + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Ljava/lang/String; + public final fun component4 ()Ljava/lang/String; + public final fun component5 ()Ljava/lang/String; + public final fun component6 ()Ljava/lang/String; + public final fun component7 ()Ljava/lang/String; + public final fun component8 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/locationping/LocationPingSchema; + public static synthetic fun copy$default (Lio/devconsole/locationping/LocationPingSchema;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lio/devconsole/locationping/LocationPingSchema; + public fun equals (Ljava/lang/Object;)Z + public final fun getAppStateKey ()Ljava/lang/String; + public final fun getDeviceTimeKey ()Ljava/lang/String; + public final fun getFixTimeKey ()Ljava/lang/String; + public final fun getGroupIdKey ()Ljava/lang/String; + public final fun getGroupLabel ()Ljava/lang/String; + public final fun getLatitudeKey ()Ljava/lang/String; + public final fun getLongitudeKey ()Ljava/lang/String; + public final fun getPingListKey ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/locationping/LocationPingStorage { + public fun (JJLjava/lang/String;)V + public final fun component1 ()J + public final fun component2 ()J + public final fun component3 ()Ljava/lang/String; + public final fun copy (JJLjava/lang/String;)Lio/devconsole/locationping/LocationPingStorage; + public static synthetic fun copy$default (Lio/devconsole/locationping/LocationPingStorage;JJLjava/lang/String;ILjava/lang/Object;)Lio/devconsole/locationping/LocationPingStorage; + public fun equals (Ljava/lang/Object;)Z + public final fun getLastError ()Ljava/lang/String; + public final fun getMaxBytes ()J + public final fun getUsedBytes ()J + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/locationping/LocationPingStore { + public static final field FILE_DATE_PATTERN Ljava/lang/String; + public static final field MAX_GROUP_ID_LENGTH I + public static final field MAX_POINTS_PER_TRACK I + public static final field TRACK_FILE_EXTENSION Ljava/lang/String; + public fun (Ljava/io/File;)V + public fun (Ljava/io/File;Lio/devconsole/locationping/LocationPingSwitches;)V + public fun (Ljava/io/File;Lio/devconsole/locationping/LocationPingSwitches;Lkotlin/jvm/functions/Function1;)V + public fun (Ljava/io/File;Lio/devconsole/locationping/LocationPingSwitches;Lkotlin/jvm/functions/Function1;Ljava/util/concurrent/Executor;)V + public fun (Ljava/io/File;Lio/devconsole/locationping/LocationPingSwitches;Lkotlin/jvm/functions/Function1;Ljava/util/concurrent/Executor;Lkotlin/jvm/functions/Function0;)V + public fun (Ljava/io/File;Lio/devconsole/locationping/LocationPingSwitches;Lkotlin/jvm/functions/Function1;Ljava/util/concurrent/Executor;Lkotlin/jvm/functions/Function0;Ljava/util/TimeZone;)V + public synthetic fun (Ljava/io/File;Lio/devconsole/locationping/LocationPingSwitches;Lkotlin/jvm/functions/Function1;Ljava/util/concurrent/Executor;Lkotlin/jvm/functions/Function0;Ljava/util/TimeZone;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun configure (Lio/devconsole/locationping/LocationPingTracking;)V + public final fun delete (Ljava/util/Set;)Lio/devconsole/locationping/LocationPingDeleteResult; + public static synthetic fun delete$default (Lio/devconsole/locationping/LocationPingStore;Ljava/util/Set;ILjava/lang/Object;)Lio/devconsole/locationping/LocationPingDeleteResult; + public final fun deleteTrack (Ljava/lang/String;Ljava/lang/String;)Z + public final fun getTracking ()Lio/devconsole/locationping/LocationPingTracking; + public final fun isEnabled (Ljava/lang/String;)Z + public static synthetic fun isEnabled$default (Lio/devconsole/locationping/LocationPingStore;Ljava/lang/String;ILjava/lang/Object;)Z + public final fun record (Ljava/lang/String;Ljava/lang/String;Lio/devconsole/locationping/LocationPingOutcome;)Z + public final fun recordNetworkPing (Ljava/lang/String;[BLjava/lang/Integer;)V + public final fun setEnabled (Ljava/lang/String;Z)Z + public final fun storage ()Lio/devconsole/locationping/LocationPingStorage; + public final fun streams ()Ljava/util/List; + public final fun track (Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/locationping/LocationPingTrackDetail; + public final fun tracks ()Ljava/util/List; +} + +public final class io/devconsole/locationping/LocationPingStream { + public fun (Ljava/lang/String;Ljava/lang/String;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/locationping/LocationPingStream; + public static synthetic fun copy$default (Lio/devconsole/locationping/LocationPingStream;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lio/devconsole/locationping/LocationPingStream; + public fun equals (Ljava/lang/Object;)Z + public final fun getName ()Ljava/lang/String; + public final fun getPath ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/locationping/LocationPingStreamStatus { + public fun (Ljava/lang/String;Ljava/lang/String;Z)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Z + public final fun copy (Ljava/lang/String;Ljava/lang/String;Z)Lio/devconsole/locationping/LocationPingStreamStatus; + public static synthetic fun copy$default (Lio/devconsole/locationping/LocationPingStreamStatus;Ljava/lang/String;Ljava/lang/String;ZILjava/lang/Object;)Lio/devconsole/locationping/LocationPingStreamStatus; + public fun equals (Ljava/lang/Object;)Z + public final fun getEnabled ()Z + public final fun getName ()Ljava/lang/String; + public final fun getPath ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public abstract interface class io/devconsole/locationping/LocationPingSwitches { + public abstract fun isEnabled (Ljava/lang/String;)Z + public abstract fun setEnabled (Ljava/lang/String;Z)V +} + +public final class io/devconsole/locationping/LocationPingTrack { + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JJ)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Ljava/lang/String; + public final fun component4 ()Ljava/lang/String; + public final fun component5 ()J + public final fun component6 ()J + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JJ)Lio/devconsole/locationping/LocationPingTrack; + public static synthetic fun copy$default (Lio/devconsole/locationping/LocationPingTrack;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JJILjava/lang/Object;)Lio/devconsole/locationping/LocationPingTrack; + public fun equals (Ljava/lang/Object;)Z + public final fun getCapturedDate ()Ljava/lang/String; + public final fun getFile ()Ljava/lang/String; + public final fun getGroupId ()Ljava/lang/String; + public final fun getLastModifiedEpochMs ()J + public final fun getSizeBytes ()J + public final fun getStream ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/locationping/LocationPingTrackDetail { + public fun (Lio/devconsole/locationping/LocationPingTrack;Ljava/util/List;Z)V + public final fun component1 ()Lio/devconsole/locationping/LocationPingTrack; + public final fun component2 ()Ljava/util/List; + public final fun component3 ()Z + public final fun copy (Lio/devconsole/locationping/LocationPingTrack;Ljava/util/List;Z)Lio/devconsole/locationping/LocationPingTrackDetail; + public static synthetic fun copy$default (Lio/devconsole/locationping/LocationPingTrackDetail;Lio/devconsole/locationping/LocationPingTrack;Ljava/util/List;ZILjava/lang/Object;)Lio/devconsole/locationping/LocationPingTrackDetail; + public fun equals (Ljava/lang/Object;)Z + public final fun getPoints ()Ljava/util/List; + public final fun getTrack ()Lio/devconsole/locationping/LocationPingTrack; + public final fun getTruncated ()Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/locationping/LocationPingTracking { + public static final field Companion Lio/devconsole/locationping/LocationPingTracking$Companion; + public static final field DEFAULT_MAX_STORAGE_BYTES J + public fun ()V + public fun (Ljava/util/List;Lio/devconsole/locationping/LocationPingSchema;J)V + public synthetic fun (Ljava/util/List;Lio/devconsole/locationping/LocationPingSchema;JILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/util/List; + public final fun component2 ()Lio/devconsole/locationping/LocationPingSchema; + public final fun component3 ()J + public final fun copy (Ljava/util/List;Lio/devconsole/locationping/LocationPingSchema;J)Lio/devconsole/locationping/LocationPingTracking; + public static synthetic fun copy$default (Lio/devconsole/locationping/LocationPingTracking;Ljava/util/List;Lio/devconsole/locationping/LocationPingSchema;JILjava/lang/Object;)Lio/devconsole/locationping/LocationPingTracking; + public fun equals (Ljava/lang/Object;)Z + public final fun getMaxStorageBytes ()J + public final fun getSchema ()Lio/devconsole/locationping/LocationPingSchema; + public final fun getStreams ()Ljava/util/List; + public fun hashCode ()I + public final fun isConfigured ()Z + public final fun stream (Ljava/lang/String;)Lio/devconsole/locationping/LocationPingStream; + public final fun streamFor (Ljava/lang/String;)Lio/devconsole/locationping/LocationPingStream; + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/locationping/LocationPingTracking$Companion { +} + diff --git a/sdk/location-ping/build.gradle.kts b/sdk/location-ping/build.gradle.kts new file mode 100644 index 0000000..7b77444 --- /dev/null +++ b/sdk/location-ping/build.gradle.kts @@ -0,0 +1,5 @@ +plugins { + id("devconsole.kotlin.jvm") + id("devconsole.quality") + id("devconsole.publishing") +} diff --git a/sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingOutcome.kt b/sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingOutcome.kt new file mode 100644 index 0000000..fb5f01f --- /dev/null +++ b/sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingOutcome.kt @@ -0,0 +1,50 @@ +/** + * @author Zakaria + * @since 26/10/26 + */ +package io.devconsole.locationping + +sealed interface LocationPingOutcome { + data class Answered( + val statusCode: Int, + ) : LocationPingOutcome { + init { + require(statusCode in HTTP_STATUS_RANGE) { "statusCode must be an HTTP status, was $statusCode" } + } + } + + data object DroppedOnDevice : LocationPingOutcome + + data object NoConnection : LocationPingOutcome + + companion object { + @JvmStatic + fun answered(statusCode: Int): LocationPingOutcome = Answered(statusCode) + + @JvmStatic + fun droppedOnDevice(): LocationPingOutcome = DroppedOnDevice + + @JvmStatic + fun noConnection(): LocationPingOutcome = NoConnection + } +} + +internal const val DROPPED_ON_DEVICE_STATUS = 0 +internal const val NO_CONNECTION_STATUS = -1 +private const val LOWEST_HTTP_STATUS = 100 +private const val HIGHEST_HTTP_STATUS = 599 +internal val HTTP_STATUS_RANGE = LOWEST_HTTP_STATUS..HIGHEST_HTTP_STATUS + +internal fun LocationPingOutcome.storedStatus(): Int = + when (this) { + is LocationPingOutcome.Answered -> statusCode + LocationPingOutcome.DroppedOnDevice -> DROPPED_ON_DEVICE_STATUS + LocationPingOutcome.NoConnection -> NO_CONNECTION_STATUS + } + +internal fun outcomeOfStoredStatus(status: Int): LocationPingOutcome = + when { + status == DROPPED_ON_DEVICE_STATUS -> LocationPingOutcome.DroppedOnDevice + status in HTTP_STATUS_RANGE -> LocationPingOutcome.Answered(status) + else -> LocationPingOutcome.NoConnection + } diff --git a/sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingStore.kt b/sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingStore.kt new file mode 100644 index 0000000..a64f2b9 --- /dev/null +++ b/sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingStore.kt @@ -0,0 +1,273 @@ +/** + * @author Zakaria + * @since 26/10/26 + */ +package io.devconsole.locationping + +import java.io.File +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale +import java.util.TimeZone +import java.util.concurrent.Executor +import java.util.concurrent.Executors + +@Suppress("TooManyFunctions") +class LocationPingStore + @JvmOverloads + constructor( + private val rootDirectory: File, + private val switches: LocationPingSwitches = InMemoryLocationPingSwitches(), + private val redactFields: (Map) -> Map = { it }, + private val writer: Executor = sharedWriter, + private val clock: () -> Long = System::currentTimeMillis, + private val timeZone: TimeZone = TimeZone.getDefault(), + ) { + @Volatile + var tracking: LocationPingTracking = LocationPingTracking() + private set + + @Volatile + private var lastStorageError: String? = null + + private val fileLock = Any() + private var knownUsedBytes: Long? = null + + fun configure(tracking: LocationPingTracking) { + this.tracking = tracking + } + + fun streams(): List = + tracking.streams.map { LocationPingStreamStatus(it.name, it.path, switches.isEnabled(it.name)) } + + fun isEnabled(streamName: String? = null): Boolean { + val configured = tracking.streams + return if (streamName == null) { + configured.any { switches.isEnabled(it.name) } + } else { + configured.any { it.name == streamName } && switches.isEnabled(streamName) + } + } + + fun setEnabled( + streamName: String, + enabled: Boolean, + ): Boolean { + if (tracking.stream(streamName) == null) return false + switches.setEnabled(streamName, enabled) + return true + } + + fun recordNetworkPing( + url: String, + body: ByteArray?, + statusCode: Int?, + ) { + if (body == null || body.isEmpty()) return + val outcome = + statusCode?.takeIf { it in HTTP_STATUS_RANGE }?.let(LocationPingOutcome::Answered) + ?: LocationPingOutcome.NoConnection + enqueue(url, outcome) { body.decodeToString() } + } + + fun record( + url: String, + body: String, + outcome: LocationPingOutcome, + ): Boolean = enqueue(url, outcome) { body } + + private fun enqueue( + url: String, + outcome: LocationPingOutcome, + body: () -> String, + ): Boolean { + val stream = tracking.streamFor(url)?.takeIf { switches.isEnabled(it.name) } ?: return false + val schema = tracking.schema + val recordedAt = clock() + writer.execute { writeSafely(stream, schema, body, outcome, recordedAt) } + return true + } + + fun storage(): LocationPingStorage = + LocationPingStorage( + usedBytes = synchronized(fileLock) { usedBytesLocked() }, + maxBytes = tracking.maxStorageBytes, + lastError = lastStorageError, + ) + + fun tracks(): List = + streamDirectories() + .flatMap { directory -> directory.listFiles().orEmpty().mapNotNull { trackOf(directory.name, it) } } + .sortedByDescending { it.lastModifiedEpochMs } + + fun track( + streamName: String, + fileName: String, + ): LocationPingTrackDetail? { + val file = trackFile(streamName, fileName) ?: return null + val reader = LocationPingTrackReader(tracking.schema, redactFields, MAX_POINTS_PER_TRACK) + return trackOf(streamName, file)?.let { track -> reader.read(track, file) } + } + + fun deleteTrack( + streamName: String, + fileName: String, + ): Boolean = + synchronized(fileLock) { + val file = trackFile(streamName, fileName) ?: return false + val deleted = file.delete() + knownUsedBytes = null + deleted + } + + fun delete(streamNames: Set? = null): LocationPingDeleteResult = + synchronized(fileLock) { + val directories = streamDirectories().filter { streamNames == null || it.name in streamNames } + val files = directories.flatMap { it.listFiles().orEmpty().filter(File::isFile) } + val deleted = files.count(File::delete) + directories.forEach(File::delete) + knownUsedBytes = null + if (deleted == files.size) lastStorageError = null + LocationPingDeleteResult(filesDeleted = deleted, filesLeft = files.size - deleted) + } + + private fun writeSafely( + stream: LocationPingStream, + schema: LocationPingSchema, + body: () -> String, + outcome: LocationPingOutcome, + recordedAt: Long, + ) { + runCatching { write(stream, schema, body(), outcome, recordedAt) } + .onFailure { lastStorageError = "Writing a ${stream.name} ping failed: ${it.readableMessage()}" } + } + + private fun write( + stream: LocationPingStream, + schema: LocationPingSchema, + body: String, + outcome: LocationPingOutcome, + recordedAt: Long, + ) { + val parsedBody = PingJson.parseOrNull(body) as? PingJson.Obj ?: return + val line = recordLine(parsedBody, outcome, recordedAt) + val lineBytes = line.toByteArray(Charsets.UTF_8) + synchronized(fileLock) { + val used = usedBytesLocked() + if (used + lineBytes.size > tracking.maxStorageBytes) { + lastStorageError = "Location ping storage is full (${tracking.maxStorageBytes} bytes). " + + "Delete captured pings to keep recording." + return + } + val directory = File(rootDirectory, stream.name) + check(directory.isDirectory || directory.mkdirs()) { "Could not create ${directory.path}" } + File(directory, trackFileName(groupIdOf(parsedBody, schema) ?: stream.name, recordedAt)) + .appendBytes(lineBytes) + knownUsedBytes = used + lineBytes.size + } + } + + private fun recordLine( + body: PingJson.Obj, + outcome: LocationPingOutcome, + recordedAt: Long, + ): String { + val record = + PingJson.Obj( + linkedMapOf( + RECORD_STATUS to PingJson.Num(outcome.storedStatus().toString()), + RECORD_RECORDED_AT to PingJson.Num(recordedAt.toString()), + RECORD_BODY to body, + ), + ) + return record.toCompactJson() + "\n" + } + + private fun groupIdOf( + body: PingJson.Obj, + schema: LocationPingSchema, + ): String? { + val value = schema.groupIdKey?.let { body[it] ?: firstPingOf(body, schema)?.get(it) } ?: return null + val text = + when (value) { + is PingJson.Arr -> value.items.map { it.asReadableText() }.firstOrNull(String::isNotBlank) + else -> value.asReadableText() + } + return text + ?.replace(UNSAFE_FILE_NAME_CHARS, "_") + ?.take(MAX_GROUP_ID_LENGTH) + ?.takeIf { it.isNotBlank() && LocationPingStream.STREAM_NAME.matches(it) } + } + + private fun firstPingOf( + body: PingJson.Obj, + schema: LocationPingSchema, + ): PingJson.Obj? = + schema.pingListKey + ?.let { (body[it] as? PingJson.Arr)?.items?.firstOrNull() as? PingJson.Obj } + + private fun trackFileName( + groupId: String, + recordedAt: Long, + ): String { + val dateFormat = + SimpleDateFormat(FILE_DATE_PATTERN, Locale.US).apply { + timeZone = + this@LocationPingStore.timeZone + } + return "$groupId-${dateFormat.format(Date(recordedAt))}$TRACK_FILE_EXTENSION" + } + + private fun usedBytesLocked(): Long = + knownUsedBytes ?: rootDirectory + .walkTopDown() + .filter(File::isFile) + .sumOf(File::length) + .also { knownUsedBytes = it } + + private fun streamDirectories(): List = + rootDirectory + .listFiles() + .orEmpty() + .filter { it.isDirectory && LocationPingStream.STREAM_NAME.matches(it.name) } + + private fun trackFile( + streamName: String, + fileName: String, + ): File? { + if (!LocationPingStream.STREAM_NAME.matches(streamName) || !TRACK_FILE_NAME.matches(fileName)) return null + return File(File(rootDirectory, streamName), fileName).takeIf(File::isFile) + } + + private fun trackOf( + streamName: String, + file: File, + ): LocationPingTrack? { + val match = TRACK_FILE_NAME.matchEntire(file.name)?.takeIf { file.isFile } ?: return null + return LocationPingTrack( + stream = streamName, + file = file.name, + groupId = match.groupValues[1], + capturedDate = match.groupValues[2], + sizeBytes = file.length(), + lastModifiedEpochMs = file.lastModified(), + ) + } + + private fun Throwable.readableMessage(): String = message?.takeIf(String::isNotBlank) ?: javaClass.simpleName + + private companion object { + const val MAX_POINTS_PER_TRACK = 20_000 + const val MAX_GROUP_ID_LENGTH = 64 + const val FILE_DATE_PATTERN = "yyyy-MM-dd" + const val TRACK_FILE_EXTENSION = ".jsonl" + val UNSAFE_FILE_NAME_CHARS = Regex("[^A-Za-z0-9._-]") + val TRACK_FILE_NAME = Regex("([A-Za-z0-9._-]{1,64})-(\\d{4}-\\d{2}-\\d{2})\\.jsonl") + + val sharedWriter: Executor by lazy { + Executors.newSingleThreadExecutor { runnable -> + Thread(runnable, "devconsole-location-pings").apply { isDaemon = true } + } + } + } + } diff --git a/sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingTrack.kt b/sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingTrack.kt new file mode 100644 index 0000000..dc2a668 --- /dev/null +++ b/sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingTrack.kt @@ -0,0 +1,74 @@ +/** + * @author Zakaria + * @since 26/10/26 + */ +package io.devconsole.locationping + +data class LocationPingStreamStatus( + val name: String, + val path: String, + val enabled: Boolean, +) + +data class LocationPingTrack( + val stream: String, + val file: String, + val groupId: String, + val capturedDate: String, + val sizeBytes: Long, + val lastModifiedEpochMs: Long, +) + +data class LocationPingPoint( + val index: Int, + val latitude: Double, + val longitude: Double, + val deviceTimeEpochMs: Long, + val deviceTimeGapSeconds: Double, + val fixTimeEpochMs: Long?, + val fixTimeGapSeconds: Double?, + val outcome: LocationPingOutcome, + val appState: String?, + val fields: Map, +) + +data class LocationPingTrackDetail( + val track: LocationPingTrack, + val points: List, + val truncated: Boolean, +) + +data class LocationPingStorage( + val usedBytes: Long, + val maxBytes: Long, + val lastError: String?, +) + +data class LocationPingDeleteResult( + val filesDeleted: Int, + val filesLeft: Int, +) + +interface LocationPingSwitches { + fun isEnabled(streamName: String): Boolean + + fun setEnabled( + streamName: String, + enabled: Boolean, + ) +} + +class InMemoryLocationPingSwitches : LocationPingSwitches { + private val enabledStreams = + java.util.concurrent.ConcurrentHashMap + .newKeySet() + + override fun isEnabled(streamName: String): Boolean = streamName in enabledStreams + + override fun setEnabled( + streamName: String, + enabled: Boolean, + ) { + if (enabled) enabledStreams += streamName else enabledStreams -= streamName + } +} diff --git a/sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingTrackReader.kt b/sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingTrackReader.kt new file mode 100644 index 0000000..b3a4f57 --- /dev/null +++ b/sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingTrackReader.kt @@ -0,0 +1,122 @@ +/** + * @author Zakaria + * @since 26/10/26 + */ +package io.devconsole.locationping + +import java.io.File + +internal class LocationPingTrackReader( + private val schema: LocationPingSchema, + private val redactFields: (Map) -> Map, + private val maxPoints: Int, +) { + fun read( + track: LocationPingTrack, + file: File, + ): LocationPingTrackDetail { + val points = ArrayList() + var truncated = false + file.useLines { lines -> + for (line in lines) { + if (points.size >= maxPoints) { + truncated = true + break + } + pointsOfLine(line).forEach { if (points.size < maxPoints) points += it else truncated = true } + } + } + return LocationPingTrackDetail(track, inDeviceTimeOrderWithGaps(points), truncated) + } + + private fun pointsOfLine(line: String): List { + val record = PingJson.parseOrNull(line) as? PingJson.Obj + val body = record?.get(RECORD_BODY) as? PingJson.Obj ?: return emptyList() + val status = record[RECORD_STATUS]?.asDouble()?.toInt() ?: NO_CONNECTION_STATUS + val pingObjects = + when (val listKey = schema.pingListKey) { + null -> listOf(body) + else -> (body[listKey] as? PingJson.Arr)?.items?.filterIsInstance().orEmpty() + } + return pingObjects.mapNotNull { ping -> pointOrNull(ping, body, outcomeOfStoredStatus(status)) } + } + + private fun pointOrNull( + ping: PingJson.Obj, + body: PingJson.Obj, + outcome: LocationPingOutcome, + ): LocationPingPoint? { + val latitude = ping.lookup(schema.latitudeKey, body)?.asDouble()?.takeIf { it in -MAX_LATITUDE..MAX_LATITUDE } + val longitude = + ping + .lookup( + schema.longitudeKey, + body, + )?.asDouble() + ?.takeIf { it in -MAX_LONGITUDE..MAX_LONGITUDE } + val deviceTime = ping.lookup(schema.deviceTimeKey, body)?.asEpochMillis() + if (latitude == null || longitude == null || deviceTime == null) return null + return LocationPingPoint( + index = 0, + latitude = latitude, + longitude = longitude, + deviceTimeEpochMs = deviceTime, + deviceTimeGapSeconds = 0.0, + fixTimeEpochMs = schema.fixTimeKey?.let { ping.lookup(it, body)?.asEpochMillis() }, + fixTimeGapSeconds = null, + outcome = outcome, + appState = schema.appStateKey?.let { ping.lookup(it, body)?.asReadableText() }?.takeIf(String::isNotBlank), + fields = redactFields(readableFieldsOf(ping, body)), + ) + } + + private fun readableFieldsOf( + ping: PingJson.Obj, + body: PingJson.Obj, + ): Map { + val shownElsewhere = + setOfNotNull(schema.pingListKey, schema.latitudeKey, schema.longitudeKey, schema.deviceTimeKey) + val fields = LinkedHashMap() + ping.fields.forEach { (key, value) -> if (key !in shownElsewhere) fields[key] = value.asReadableText() } + body.fields.forEach { (key, value) -> + if (key !in shownElsewhere && + key !in fields + ) { + fields[key] = value.asReadableText() + } + } + return fields + } + + private fun inDeviceTimeOrderWithGaps(points: List): List { + var previousDeviceTime: Long? = null + var previousFixTime: Long? = null + return points.sortedBy { it.deviceTimeEpochMs }.mapIndexed { index, point -> + val deviceGap = previousDeviceTime?.let { (point.deviceTimeEpochMs - it) / MILLIS_PER_SECOND } ?: 0.0 + val fixGap = point.fixTimeEpochMs?.let { fix -> previousFixTime?.let { (fix - it) / MILLIS_PER_SECOND } } + previousDeviceTime = point.deviceTimeEpochMs + point.fixTimeEpochMs?.let { previousFixTime = it } + point.copy(index = index, deviceTimeGapSeconds = deviceGap, fixTimeGapSeconds = fixGap) + } + } +} + +internal const val RECORD_STATUS = "status" +internal const val RECORD_RECORDED_AT = "recordedAt" +internal const val RECORD_BODY = "body" + +private const val MILLIS_PER_SECOND = 1000.0 +private const val SMALLEST_EPOCH_MILLIS = 100_000_000_000.0 +private const val MILLIS_PER_SECOND_LONG = 1000L +private const val MAX_LATITUDE = 90.0 +private const val MAX_LONGITUDE = 180.0 + +private fun PingJson.Obj.lookup( + key: String, + body: PingJson.Obj, +): PingJson? = this[key] ?: body[key] + +private fun PingJson.asEpochMillis(): Long? { + val value = asDouble()?.takeIf { it > 0 } ?: return null + return if (value < SMALLEST_EPOCH_MILLIS) (value * MILLIS_PER_SECOND_LONG).toLong() else value.toLong() +} diff --git a/sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingTracking.kt b/sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingTracking.kt new file mode 100644 index 0000000..656d69c --- /dev/null +++ b/sdk/location-ping/src/main/kotlin/io/devconsole/locationping/LocationPingTracking.kt @@ -0,0 +1,68 @@ +/** + * @author Zakaria + * @since 26/10/26 + */ +package io.devconsole.locationping + +import java.net.URI + +data class LocationPingStream( + val name: String, + val path: String, +) { + init { + require(STREAM_NAME.matches(name)) { "Stream name must be 1-64 letters, digits, '.', '_' or '-': $name" } + require(comparablePathOf(path).length > 1) { "Stream path must name an endpoint, e.g. /v1/pings: $path" } + } + + internal val comparablePath: String get() = comparablePathOf(path) + + internal companion object { + val STREAM_NAME = Regex("(?!\\.+$)[A-Za-z0-9._-]{1,64}") + } +} + +data class LocationPingSchema( + val pingListKey: String? = null, + val latitudeKey: String = "latitude", + val longitudeKey: String = "longitude", + val deviceTimeKey: String = "timestamp", + val fixTimeKey: String? = null, + val groupIdKey: String? = null, + val appStateKey: String? = null, + val groupLabel: String = "Group", +) + +data class LocationPingTracking( + val streams: List = emptyList(), + val schema: LocationPingSchema = LocationPingSchema(), + val maxStorageBytes: Long = DEFAULT_MAX_STORAGE_BYTES, +) { + init { + require(streams.distinctBy { it.name }.size == streams.size) { "Location ping stream names must be unique" } + require(maxStorageBytes > 0) { "maxStorageBytes must be positive" } + } + + val isConfigured: Boolean get() = streams.isNotEmpty() + + fun stream(name: String): LocationPingStream? = streams.firstOrNull { it.name == name } + + fun streamFor(url: String): LocationPingStream? { + val requestPath = comparablePathOf(url) + if (requestPath.length <= 1) return null + return streams + .sortedByDescending { it.comparablePath.length } + .firstOrNull { requestPath == it.comparablePath || requestPath.endsWith(it.comparablePath) } + } + + companion object { + const val DEFAULT_MAX_STORAGE_BYTES: Long = 64L * 1024L * 1024L + } +} + +private fun comparablePathOf(urlOrPath: String): String { + val withoutQuery = urlOrPath.substringBefore('#').substringBefore('?').trim() + val path = runCatching { URI(withoutQuery).path }.getOrNull() ?: withoutQuery + val trimmed = path.trimEnd('/') + return if (trimmed.startsWith('/')) trimmed else "/$trimmed" +} diff --git a/sdk/location-ping/src/main/kotlin/io/devconsole/locationping/PingJson.kt b/sdk/location-ping/src/main/kotlin/io/devconsole/locationping/PingJson.kt new file mode 100644 index 0000000..aa52759 --- /dev/null +++ b/sdk/location-ping/src/main/kotlin/io/devconsole/locationping/PingJson.kt @@ -0,0 +1,247 @@ +/** + * @author Zakaria + * @since 26/10/26 + */ +package io.devconsole.locationping + +internal sealed interface PingJson { + data class Obj( + val fields: Map, + ) : PingJson { + operator fun get(key: String): PingJson? = fields[key] + } + + data class Arr( + val items: List, + ) : PingJson + + data class Str( + val value: String, + ) : PingJson + + data class Num( + val raw: String, + ) : PingJson + + data class Bool( + val value: Boolean, + ) : PingJson + + data object Null : PingJson + + companion object { + fun parseOrNull(text: String): PingJson? = runCatching { PingJsonReader(text).readDocument() }.getOrNull() + } +} + +internal fun PingJson.toCompactJson(): String = StringBuilder().also { appendCompactJson(it) }.toString() + +internal fun PingJson.asDouble(): Double? = + when (this) { + is PingJson.Num -> raw.toDoubleOrNull() + is PingJson.Str -> value.trim().toDoubleOrNull() + else -> null + } + +internal fun PingJson.asReadableText(): String = + when (this) { + is PingJson.Str -> value + is PingJson.Num -> raw + is PingJson.Bool -> value.toString() + PingJson.Null -> "" + is PingJson.Arr -> items.joinToString(", ") { it.asReadableText() } + is PingJson.Obj -> toCompactJson() + } + +private fun PingJson.appendCompactJson(out: StringBuilder) { + when (this) { + is PingJson.Obj -> { + out.append('{') + fields.entries.forEachIndexed { index, (key, value) -> + if (index > 0) out.append(',') + appendQuoted(key, out) + out.append(':') + value.appendCompactJson(out) + } + out.append('}') + } + is PingJson.Arr -> { + out.append('[') + items.forEachIndexed { index, item -> + if (index > 0) out.append(',') + item.appendCompactJson(out) + } + out.append(']') + } + is PingJson.Str -> appendQuoted(value, out) + is PingJson.Num -> out.append(raw) + is PingJson.Bool -> out.append(value) + PingJson.Null -> out.append("null") + } +} + +private fun appendQuoted( + text: String, + out: StringBuilder, +) { + out.append('"') + text.forEach { char -> + when (char) { + '"' -> out.append("\\\"") + '\\' -> out.append("\\\\") + '\n' -> out.append("\\n") + '\r' -> out.append("\\r") + '\t' -> out.append("\\t") + '\b' -> out.append("\\b") + '\u000C' -> out.append("\\f") + else -> + if (char < ' ') { + out.append("\\u").append(char.code.toString(HEX_RADIX).padStart(UNICODE_ESCAPE_DIGITS, '0')) + } else { + out.append(char) + } + } + } + out.append('"') +} + +private class PingJsonReader( + private val text: String, +) { + private var position = 0 + private var depth = 0 + + fun readDocument(): PingJson { + val value = readValue() + skipWhitespace() + check(position == text.length) { "Trailing characters at $position" } + return value + } + + private fun readValue(): PingJson { + skipWhitespace() + check(position < text.length) { "Unexpected end of JSON" } + return when (val char = text[position]) { + '{', '[' -> { + depth += 1 + check(depth <= MAX_DEPTH) { "JSON nests deeper than $MAX_DEPTH levels" } + val container = if (char == '{') readObject() else readArray() + depth -= 1 + container + } + '"' -> PingJson.Str(readString()) + 't', 'f', 'n' -> { + val (keyword, value) = KEYWORDS.getValue(char) + check(text.startsWith(keyword, position)) { "Expected $keyword at $position" } + position += keyword.length + value + } + else -> if (char == '-' || char.isDigit()) readNumber() else error("Unexpected '$char' at $position") + } + } + + private fun readObject(): PingJson { + position += 1 + val fields = LinkedHashMap() + skipWhitespace() + if (peek() == '}') { + position += 1 + return PingJson.Obj(fields) + } + while (true) { + skipWhitespace() + val key = readString() + skipWhitespace() + expect(':') + fields[key] = readValue() + skipWhitespace() + if (peek() == ',') { + position += 1 + } else { + expect('}') + return PingJson.Obj(fields) + } + } + } + + private fun readArray(): PingJson { + position += 1 + val items = ArrayList() + skipWhitespace() + if (peek() == ']') { + position += 1 + return PingJson.Arr(items) + } + while (true) { + items += readValue() + skipWhitespace() + if (peek() == ',') { + position += 1 + } else { + expect(']') + return PingJson.Arr(items) + } + } + } + + private fun readString(): String { + expect('"') + val out = StringBuilder() + while (true) { + check(position < text.length) { "Unterminated string" } + when (val char = text[position++]) { + '"' -> return out.toString() + '\\' -> out.append(readEscape()) + else -> out.append(char) + } + } + } + + private fun readEscape(): Char { + check(position < text.length) { "Unterminated escape" } + return when (val escaped = text[position++]) { + 'n' -> '\n' + 'r' -> '\r' + 't' -> '\t' + 'b' -> '\b' + 'f' -> '\u000C' + 'u' -> { + check(position + UNICODE_ESCAPE_DIGITS <= text.length) { "Short unicode escape" } + val code = text.substring(position, position + UNICODE_ESCAPE_DIGITS).toInt(HEX_RADIX) + position += UNICODE_ESCAPE_DIGITS + code.toChar() + } + else -> escaped + } + } + + private fun readNumber(): PingJson { + val start = position + while (position < text.length && text[position] in NUMBER_CHARS) position += 1 + val raw = text.substring(start, position) + checkNotNull(raw.toDoubleOrNull()) { "Malformed number '$raw'" } + return PingJson.Num(raw) + } + + private fun expect(char: Char) { + check(peek() == char) { "Expected '$char' at $position" } + position += 1 + } + + private fun peek(): Char? = text.getOrNull(position) + + private fun skipWhitespace() { + while (position < text.length && text[position].isWhitespace()) position += 1 + } +} + +private const val MAX_DEPTH = 64 +private val KEYWORDS = + mapOf( + 't' to ("true" to PingJson.Bool(true)), + 'f' to ("false" to PingJson.Bool(false)), + 'n' to ("null" to PingJson.Null), + ) +private const val HEX_RADIX = 16 +private const val UNICODE_ESCAPE_DIGITS = 4 +private val NUMBER_CHARS = "0123456789+-.eE".toSet() diff --git a/sdk/location-ping/src/test/kotlin/io/devconsole/locationping/LocationPingStoreTest.kt b/sdk/location-ping/src/test/kotlin/io/devconsole/locationping/LocationPingStoreTest.kt new file mode 100644 index 0000000..aba523a --- /dev/null +++ b/sdk/location-ping/src/test/kotlin/io/devconsole/locationping/LocationPingStoreTest.kt @@ -0,0 +1,319 @@ +/** + * @author Zakaria + * @since 26/10/26 + */ +package io.devconsole.locationping + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.util.TimeZone + +class LocationPingStoreTest { + @get:Rule + val folder = TemporaryFolder() + + private val ridePings = LocationPingStream("ride", "/v2/trips/locations") + private val idlePings = LocationPingStream("idle", "/v2/driver/locations") + private val batchSchema = + LocationPingSchema( + pingListKey = "pings", + latitudeKey = "lat", + longitudeKey = "lng", + deviceTimeKey = "device_time", + fixTimeKey = "fix_time", + groupIdKey = "trip_ids", + appStateKey = "process", + ) + + @Test + fun `a stream matches on the request path whatever the host or query`() { + val tracking = LocationPingTracking(listOf(idlePings, ridePings)) + + assertEquals(idlePings, tracking.streamFor("https://staging.example.com/v2/driver/locations?qa=1")) + assertEquals(ridePings, tracking.streamFor("http://10.0.2.2:8080/api/v2/trips/locations/")) + assertNull(tracking.streamFor("https://example.com/v2/driver/profile")) + } + + @Test + fun `nothing is written while the stream switch is off`() { + val store = store() + + val accepted = + store.record( + "https://api.test/v2/trips/locations", + ridePing(1_000), + LocationPingOutcome.Answered(200), + ) + + assertFalse(accepted) + assertTrue(store.tracks().isEmpty()) + } + + @Test + fun `an enabled stream writes one file per group and day`() { + val store = store().also { it.setEnabled("ride", true) } + + store.record( + "https://api.test/v2/trips/locations", + ridePing(1_000, orderId = "order-7"), + LocationPingOutcome.Answered(200), + ) + store.record( + "https://api.test/v2/trips/locations", + ridePing(2_000, orderId = "order-7"), + LocationPingOutcome.Answered(200), + ) + store.record( + "https://api.test/v2/trips/locations", + ridePing(3_000, orderId = "order 9/x"), + LocationPingOutcome.Answered(200), + ) + + val files = store.tracks().map { it.file }.sorted() + assertEquals(listOf("order-7-2026-10-26.jsonl", "order_9_x-2026-10-26.jsonl"), files) + assertEquals("order-7", store.tracks().first { it.file.startsWith("order-7") }.groupId) + } + + @Test + fun `a ping without a group id is filed under the stream name`() { + val store = store().also { it.setEnabled("idle", true) } + + store.record( + "https://api.test/v2/driver/locations", + ridePing(1_000, orderId = null), + LocationPingOutcome.Answered(200), + ) + + assertEquals(listOf("idle-2026-10-26.jsonl"), store.tracks().map { it.file }) + } + + @Test + fun `network pings map a missing or failed response to no connection`() { + val store = store().also { it.setEnabled("ride", true) } + + store.recordNetworkPing("https://api.test/v2/trips/locations", ridePing(1_000).toByteArray(), 503) + store.recordNetworkPing("https://api.test/v2/trips/locations", ridePing(2_000).toByteArray(), 0) + store.recordNetworkPing("https://api.test/v2/trips/locations", ridePing(3_000).toByteArray(), null) + + val outcomes = store.onlyTrack().points.map { it.outcome } + assertEquals( + listOf( + LocationPingOutcome.Answered(503), + LocationPingOutcome.NoConnection, + LocationPingOutcome.NoConnection, + ), + outcomes, + ) + } + + @Test + fun `points come back in device time order with gaps since the previous point`() { + val store = store().also { it.setEnabled("ride", true) } + + store.record( + "https://api.test/v2/trips/locations", + ridePing(5_000, fixTime = 4_000), + LocationPingOutcome.DroppedOnDevice, + ) + store.record( + "https://api.test/v2/trips/locations", + ridePing(1_000, fixTime = 500), + LocationPingOutcome.Answered(200), + ) + store.record( + "https://api.test/v2/trips/locations", + ridePing(2_500, fixTime = 2_000), + LocationPingOutcome.NoConnection, + ) + + val points = store.onlyTrack().points + assertEquals(listOf(1_000L, 2_500L, 5_000L), points.map { it.deviceTimeEpochMs - OCTOBER_26_2026_NOON_UTC }) + assertEquals(listOf(0.0, 1.5, 2.5), points.map { it.deviceTimeGapSeconds }) + assertEquals(listOf(null, 1.5, 2.0), points.map { it.fixTimeGapSeconds }) + assertEquals(LocationPingOutcome.DroppedOnDevice, points.last().outcome) + assertEquals("FOREGROUND", points.first().appState) + } + + @Test + fun `every ping in a batch becomes its own point and shares the body fields`() { + val store = store().also { it.setEnabled("ride", true) } + val body = + """ + {"trip_ids":["o1"],"battery":81,"pings":[ + {"lat":23.79,"lng":90.41,"device_time":1000}, + {"lat":"23.80","lng":"90.42","device_time":2000,"speed":"4.2"}, + {"lat":123.0,"lng":90.42,"device_time":3000} + ]} + """.trimIndent() + + store.record("https://api.test/v2/trips/locations", body, LocationPingOutcome.Answered(200)) + + val points = store.onlyTrack().points + assertEquals(2, points.size) + assertEquals(23.80, points[1].latitude, 0.0) + assertEquals("81", points[1].fields["battery"]) + assertEquals("4.2", points[1].fields["speed"]) + assertFalse(points[1].fields.containsKey("lat")) + } + + @Test + fun `a schema without a ping list treats the body as one ping and accepts seconds`() { + val store = store(LocationPingSchema()).also { it.setEnabled("idle", true) } + + store.record( + "https://api.test/v2/driver/locations", + """{"latitude":1.5,"longitude":2.5,"timestamp":1793022273}""", + LocationPingOutcome.Answered(204), + ) + + val point = store.onlyTrack().points.single() + assertEquals(1_793_022_273_000L, point.deviceTimeEpochMs) + } + + @Test + fun `fields pass through the redactor before they are returned`() { + val store = + store(redact = { fields -> + fields.mapValues { (key, value) -> + if (key == + "token" + ) { + "" + } else { + value + } + } + }) + .also { it.setEnabled("ride", true) } + + store.record( + "https://api.test/v2/trips/locations", + ridePing(1_000, extra = ""","token":"secret""""), + LocationPingOutcome.Answered(200), + ) + + assertEquals( + "", + store + .onlyTrack() + .points + .single() + .fields["token"], + ) + } + + @Test + fun `a body that is not a JSON object is skipped`() { + val store = store().also { it.setEnabled("ride", true) } + + store.record("https://api.test/v2/trips/locations", "lat=1&lng=2", LocationPingOutcome.Answered(200)) + + assertTrue(store.tracks().isEmpty()) + } + + @Test + fun `recording stops at the storage cap and reports why`() { + val store = store(maxStorageBytes = 400).also { it.setEnabled("ride", true) } + + repeat(10) { + store.record( + "https://api.test/v2/trips/locations", + ridePing(1_000L + it), + LocationPingOutcome.Answered(200), + ) + } + + val storage = store.storage() + assertTrue(storage.usedBytes <= 400) + assertNotNull(storage.lastError) + assertTrue(storage.lastError!!.contains("full")) + } + + @Test + fun `track lookups refuse names that could leave the stream folder`() { + val store = store().also { it.setEnabled("ride", true) } + store.record("https://api.test/v2/trips/locations", ridePing(1_000), LocationPingOutcome.Answered(200)) + + assertNull(store.track("..", "order-1-2026-10-26.jsonl")) + assertNull(store.track("ride", "../idle/order-1-2026-10-26.jsonl")) + assertNull(store.track("ride", "notes.txt")) + assertNotNull(store.track("ride", "order-1-2026-10-26.jsonl")) + } + + @Test + fun `deleting a stream leaves the other streams alone`() { + val store = + store().also { + it.setEnabled("ride", true) + it.setEnabled("idle", true) + } + store.record("https://api.test/v2/trips/locations", ridePing(1_000), LocationPingOutcome.Answered(200)) + store.record( + "https://api.test/v2/driver/locations", + ridePing(1_000, orderId = null), + LocationPingOutcome.Answered(200), + ) + + val result = store.delete(setOf("ride")) + + assertEquals(1, result.filesDeleted) + assertEquals(listOf("idle"), store.tracks().map { it.stream }) + assertEquals(store.tracks().sumOf { it.sizeBytes }, store.storage().usedBytes) + } + + @Test + fun `switches only apply to configured streams`() { + val store = store() + + assertFalse(store.setEnabled("unknown", true)) + assertTrue(store.setEnabled("idle", true)) + assertTrue(store.isEnabled()) + assertTrue(store.isEnabled("idle")) + assertFalse(store.isEnabled("ride")) + } + + @Test(expected = IllegalArgumentException::class) + fun `a stream name that is only dots is rejected`() { + LocationPingStream("..", "/v1/pings") + } + + private fun store( + schema: LocationPingSchema = batchSchema, + maxStorageBytes: Long = LocationPingTracking.DEFAULT_MAX_STORAGE_BYTES, + redact: (Map) -> Map = { it }, + ): LocationPingStore = + LocationPingStore( + rootDirectory = folder.newFolder("pings"), + redactFields = redact, + writer = { it.run() }, + clock = { OCTOBER_26_2026_NOON_UTC }, + timeZone = TimeZone.getTimeZone("UTC"), + ).also { it.configure(LocationPingTracking(listOf(idlePings, ridePings), schema, maxStorageBytes)) } + + private fun LocationPingStore.onlyTrack(): LocationPingTrackDetail { + val track = tracks().single() + return checkNotNull(track(track.stream, track.file)) + } + + private fun ridePing( + deviceTime: Long, + orderId: String? = "order-1", + fixTime: Long = deviceTime - 100, + extra: String = "", + ): String { + val orders = orderId?.let { """"trip_ids":["$it"],""" }.orEmpty() + val deviceTimeField = """"device_time":${OCTOBER_26_2026_NOON_UTC + deviceTime}""" + val times = """$deviceTimeField,"fix_time":${OCTOBER_26_2026_NOON_UTC + fixTime}""" + return """{$orders"process":"FOREGROUND"$extra,"pings":[{"lat":23.79,"lng":90.41,$times}]}""" + } + + private companion object { + const val OCTOBER_26_2026_NOON_UTC = 1_793_016_000_000L + } +} diff --git a/settings.gradle.kts b/settings.gradle.kts index 095808e..038c0fa 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -48,6 +48,7 @@ include(":sdk:push-firebase") include(":sdk:push-firebase-noop") include(":sdk:state") include(":sdk:remote-config") +include(":sdk:location-ping") include(":sdk:remote-config-firebase") include(":sdk:remote-config-firebase-noop") include(":sdk:ui-views") From e1f1542e4f05445e4d82ac01a58345bf67c7f4c7 Mon Sep 17 00:00:00 2001 From: zakaria5729 Date: Mon, 26 Oct 2026 20:31:53 +0600 Subject: [PATCH 3/8] feat(server): serve recorded location pings over the dashboard API GET /api/v1/location-pings lists streams, schema hints, storage use and recorded tracks. GET /api/v1/location-pings/track returns one track's points with a status the map can colour (sent, failed, dropped, offline). PUT /streams/{name} switches a stream on or off, and the DELETE routes remove a track or everything. Mutations need the CSRF token and are written to the audit log, and all routes sit behind the network capture category. The engine takes the store through withLocationPings so its constructor ABI is unchanged. --- sdk/server-ktor/api/server-ktor.api | 3 + sdk/server-ktor/build.gradle.kts | 1 + .../server/ktor/DevConsoleKtorModule.kt | 178 ++++++++++++ .../server/ktor/LocationPingRoutesTest.kt | 258 ++++++++++++++++++ 4 files changed, 440 insertions(+) create mode 100644 sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/LocationPingRoutesTest.kt diff --git a/sdk/server-ktor/api/server-ktor.api b/sdk/server-ktor/api/server-ktor.api index 59355fa..7fe3b73 100644 --- a/sdk/server-ktor/api/server-ktor.api +++ b/sdk/server-ktor/api/server-ktor.api @@ -27,6 +27,7 @@ public final class io/devconsole/server/ktor/DevConsoleModuleConfig { public final fun getFeatureFlagsEditable ()Z public final fun getFileInspector ()Lio/devconsole/server/api/FileInspector; public final fun getFilesEditable ()Z + public final fun getLocationPings ()Lkotlin/jvm/functions/Function0; public final fun getMetadata ()Lio/devconsole/server/api/ServerMetadata; public final fun getMockEngine ()Lio/devconsole/mocks/MockEngine; public final fun getMocksEditable ()Z @@ -69,6 +70,7 @@ public final class io/devconsole/server/ktor/DevConsoleModuleConfig { public final fun setFeatureFlagsEditable (Z)V public final fun setFileInspector (Lio/devconsole/server/api/FileInspector;)V public final fun setFilesEditable (Z)V + public final fun setLocationPings (Lkotlin/jvm/functions/Function0;)V public final fun setMetadata (Lio/devconsole/server/api/ServerMetadata;)V public final fun setMockEngine (Lio/devconsole/mocks/MockEngine;)V public final fun setMocksEditable (Z)V @@ -118,6 +120,7 @@ public final class io/devconsole/server/ktor/KtorLocalServerEngine : io/devconso public final fun withAttachmentMetadataReader (Lkotlin/jvm/functions/Function2;)Lio/devconsole/server/ktor/KtorLocalServerEngine; public final fun withAttachmentReader (Lkotlin/jvm/functions/Function2;)Lio/devconsole/server/ktor/KtorLocalServerEngine; public final fun withBrowserSecurity (Lio/devconsole/api/BrowserSecurity;)Lio/devconsole/server/ktor/KtorLocalServerEngine; + public final fun withLocationPings (Lkotlin/jvm/functions/Function0;)Lio/devconsole/server/ktor/KtorLocalServerEngine; public final fun withRetainedCaptures (Lio/devconsole/storage/api/RetainedCaptureQuery;)Lio/devconsole/server/ktor/KtorLocalServerEngine; } diff --git a/sdk/server-ktor/build.gradle.kts b/sdk/server-ktor/build.gradle.kts index 9afa7af..9844987 100644 --- a/sdk/server-ktor/build.gradle.kts +++ b/sdk/server-ktor/build.gradle.kts @@ -22,6 +22,7 @@ dependencies { implementation(project(":sdk:push")) implementation(project(":sdk:state")) implementation(project(":sdk:remote-config")) + implementation(project(":sdk:location-ping")) implementation(project(":sdk:export")) implementation(project(":sdk:storage-api")) implementation("io.ktor:ktor-server-core:3.0.3") diff --git a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt index dce61ec..1e20508 100644 --- a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt +++ b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt @@ -24,6 +24,11 @@ import io.devconsole.export.EvidenceBundleContent import io.devconsole.export.ExportRequest import io.devconsole.export.ExportResult import io.devconsole.export.ExportScope +import io.devconsole.locationping.LocationPingOutcome +import io.devconsole.locationping.LocationPingPoint +import io.devconsole.locationping.LocationPingStore +import io.devconsole.locationping.LocationPingTrack +import io.devconsole.locationping.LocationPingTrackDetail import io.devconsole.mocks.MockAction import io.devconsole.mocks.MockEngine import io.devconsole.mocks.MockRule @@ -231,6 +236,8 @@ class DevConsoleModuleConfig { */ var remoteConfigSnapshots: () -> List = { emptyList() } + var locationPings: () -> LocationPingStore? = { null } + /** Reads (file/entry listing) always work; [preferencesEditable] mirrors `EditingCapabilities.preferences`. */ var preferencesInspector: PreferencesInspector? = null var preferencesEditable: Boolean = false @@ -357,6 +364,7 @@ fun Application.devConsoleModule( val sessionSnapshotProvider = config.sessionSnapshotProvider val sessionsProvider = config.sessionsProvider val screenshotCapture = config.screenshotCapture + val locationPings = config.locationPings val metadata = config.metadata val sdkHealth = config.sdkHealth val boundEndpoint = config.boundEndpoint @@ -1258,6 +1266,114 @@ fun Application.devConsoleModule( commandAuditLog.recordControlSuccess(session.id, "network.clear", "transactions") call.respondText("{\"status\":\"cleared\"}", contentType = io.ktor.http.ContentType.Application.Json) } + get("/api/v1/location-pings") { + if (sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) == null) { + call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) + return@get + } + if (!categoryEnabled("network")) { + call.respondCategoryDisabled("network") + return@get + } + call.respondText( + locationPingOverviewJson(locationPings()), + contentType = io.ktor.http.ContentType.Application.Json, + ) + } + get("/api/v1/location-pings/track") { + if (sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) == null) { + call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) + return@get + } + if (!categoryEnabled("network")) { + call.respondCategoryDisabled("network") + return@get + } + val stream = call.request.queryParameters["stream"].orEmpty() + val file = call.request.queryParameters["file"].orEmpty() + val detail = locationPings()?.track(stream, file) + if (detail == null) { + call.respondText("{\"code\":\"NOT_FOUND\"}", status = HttpStatusCode.NotFound) + return@get + } + call.respondText(detail.json(), contentType = io.ktor.http.ContentType.Application.Json) + } + put("/api/v1/location-pings/streams/{name}") { + val name = call.parameters["name"].orEmpty() + val session = + call.captureControlSession(sessionAuthority, commandAuditLog, "location-pings.toggle", name) + ?: return@put + if (!categoryEnabled("network")) { + commandAuditLog.recordControlFailure(session.id, "location-pings.toggle", name) + call.respondCategoryDisabled("network") + return@put + } + val enabled = + call + .receiveText() + .trim() + .trim('"') + .toBooleanStrictOrNull() + val updated = enabled != null && locationPings()?.setEnabled(name, enabled) == true + if (!updated) { + commandAuditLog.recordControlFailure(session.id, "location-pings.toggle", name) + call.respondText("{\"code\":\"VALIDATION_FAILED\"}", status = HttpStatusCode.BadRequest) + return@put + } + commandAuditLog.recordControlSuccess( + session.id, + "location-pings.toggle", + name, + mapOf( + "enabled" to "$enabled", + ), + ) + call.respondText( + "{\"status\":\"updated\",\"enabled\":$enabled}", + contentType = io.ktor.http.ContentType.Application.Json, + ) + } + delete("/api/v1/location-pings/track") { + val stream = call.request.queryParameters["stream"].orEmpty() + val file = call.request.queryParameters["file"].orEmpty() + val session = + call.captureControlSession(sessionAuthority, commandAuditLog, "location-pings.delete", "$stream/$file") + ?: return@delete + if (!categoryEnabled("network")) { + commandAuditLog.recordControlFailure(session.id, "location-pings.delete", "$stream/$file") + call.respondCategoryDisabled("network") + return@delete + } + if (locationPings()?.deleteTrack(stream, file) != true) { + commandAuditLog.recordControlFailure(session.id, "location-pings.delete", "$stream/$file") + call.respondText("{\"code\":\"NOT_FOUND\"}", status = HttpStatusCode.NotFound) + return@delete + } + commandAuditLog.recordControlSuccess(session.id, "location-pings.delete", "$stream/$file") + call.respondText("{\"status\":\"deleted\"}", contentType = io.ktor.http.ContentType.Application.Json) + } + delete("/api/v1/location-pings") { + val streams = + call.request.queryParameters + .getAll("stream") + ?.filter(String::isNotBlank) + ?.toSet() + val target = streams?.sorted()?.joinToString(",") ?: "all" + val session = + call.captureControlSession(sessionAuthority, commandAuditLog, "location-pings.delete", target) + ?: return@delete + if (!categoryEnabled("network")) { + commandAuditLog.recordControlFailure(session.id, "location-pings.delete", target) + call.respondCategoryDisabled("network") + return@delete + } + val result = locationPings()?.delete(streams) + commandAuditLog.recordControlSuccess(session.id, "location-pings.delete", target) + call.respondText( + "{\"filesDeleted\":${result?.filesDeleted ?: 0},\"filesLeft\":${result?.filesLeft ?: 0}}", + contentType = io.ktor.http.ContentType.Application.Json, + ) + } get("/api/v1/retained-events") { if (sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) == null) { call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) @@ -3538,6 +3654,11 @@ class KtorLocalServerEngine( retainedCaptures = query } + @Volatile + private var locationPings: () -> LocationPingStore? = { null } + + fun withLocationPings(store: () -> LocationPingStore?): KtorLocalServerEngine = apply { locationPings = store } + /** Sets the browser authentication policy used by the next server start. */ fun withBrowserSecurity(value: BrowserSecurity): KtorLocalServerEngine = apply { @@ -3694,6 +3815,7 @@ class KtorLocalServerEngine( this.sessionSnapshotProvider = this@KtorLocalServerEngine.sessionSnapshotProvider this.sessionsProvider = this@KtorLocalServerEngine.sessionsProvider this.screenshotCapture = this@KtorLocalServerEngine.screenshotCapture + this.locationPings = this@KtorLocalServerEngine.locationPings boundEndpoint = { currentEndpoint } } }.start(wait = false) @@ -4637,6 +4759,62 @@ private fun pruneStaleExports( private const val STALE_EXPORT_MAX_AGE_MS = 60L * 60L * 1000L +private fun locationPingOverviewJson(store: LocationPingStore?): String { + if (store == null) return "{\"configured\":false,\"streams\":[],\"tracks\":[]}" + val tracking = store.tracking + val streams = + store.streams().joinToString(",") { stream -> + "{\"name\":\"${stream.name.escapeJson()}\",\"path\":\"${stream.path.escapeJson()}\"," + + "\"enabled\":${stream.enabled}}" + } + val schema = tracking.schema + val storage = store.storage() + val lastError = storage.lastError?.let { "\"${it.escapeJson()}\"" } ?: "null" + return "{\"configured\":${tracking.isConfigured},\"streams\":[$streams]," + + "\"schema\":{\"groupLabel\":\"${schema.groupLabel.escapeJson()}\"," + + "\"hasFixTime\":${schema.fixTimeKey != null},\"hasAppState\":${schema.appStateKey != null}}," + + "\"storage\":{\"usedBytes\":${storage.usedBytes},\"maxBytes\":${storage.maxBytes},\"lastError\":$lastError}," + + "\"tracks\":[${store.tracks().joinToString(",") { it.json() }}]}" +} + +private fun LocationPingTrack.json(): String = + "{\"stream\":\"${stream.escapeJson()}\",\"file\":\"${file.escapeJson()}\"," + + "\"groupId\":\"${groupId.escapeJson()}\",\"capturedDate\":\"${capturedDate.escapeJson()}\"," + + "\"sizeBytes\":$sizeBytes,\"lastModifiedEpochMs\":$lastModifiedEpochMs}" + +private fun LocationPingTrackDetail.json(): String = + "{\"track\":${track.json()},\"truncated\":$truncated,\"points\":[${points.joinToString(",") { it.json() }}]}" + +private fun LocationPingPoint.json(): String { + val statusCode = (outcome as? LocationPingOutcome.Answered)?.statusCode + val fieldsJson = + fields.entries.joinToString( + ",", + ) { (key, value) -> "\"${key.escapeJson()}\":\"${value.escapeJson()}\"" } + return "{\"index\":$index,\"lat\":$latitude,\"lng\":$longitude," + + "\"deviceTime\":$deviceTimeEpochMs,\"deviceGapSeconds\":$deviceTimeGapSeconds," + + "\"fixTime\":${fixTimeEpochMs ?: "null"},\"fixGapSeconds\":${fixTimeGapSeconds ?: "null"}," + + "\"status\":\"${outcome.wireName()}\",\"statusCode\":${statusCode ?: "null"}," + + "\"appState\":${appState?.let { "\"${it.escapeJson()}\"" } ?: "null"},\"fields\":{$fieldsJson}}" +} + +private fun LocationPingOutcome.wireName(): String = + when (this) { + is LocationPingOutcome.Answered -> + if (statusCode / HTTP_STATUS_CLASS_SIZE == + HTTP_SUCCESS_CLASS + ) { + "sent" + } else { + "failed" + } + LocationPingOutcome.DroppedOnDevice -> "dropped" + LocationPingOutcome.NoConnection -> "offline" + } + +private const val HTTP_STATUS_CLASS_SIZE = 100 +private const val HTTP_SUCCESS_CLASS = 2 + private fun String.escapeJson(): String = buildString(length + 16) { for (char in this@escapeJson) { diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/LocationPingRoutesTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/LocationPingRoutesTest.kt new file mode 100644 index 0000000..f25701e --- /dev/null +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/LocationPingRoutesTest.kt @@ -0,0 +1,258 @@ +/** + * @author Zakaria + * @since 26/10/26 + */ +package io.devconsole.server.ktor + +import io.devconsole.locationping.LocationPingOutcome +import io.devconsole.locationping.LocationPingSchema +import io.devconsole.locationping.LocationPingStore +import io.devconsole.locationping.LocationPingStream +import io.devconsole.locationping.LocationPingTracking +import io.devconsole.server.api.BrowserSession +import io.devconsole.server.api.CommandAuditResult +import io.devconsole.server.api.InMemoryCommandAuditLog +import io.devconsole.server.api.ServerMetadata +import io.devconsole.server.api.SessionAuthority +import io.devconsole.server.api.SessionCodeAuthority +import io.ktor.client.request.HttpRequestBuilder +import io.ktor.client.request.delete +import io.ktor.client.request.get +import io.ktor.client.request.header +import io.ktor.client.request.post +import io.ktor.client.request.put +import io.ktor.client.request.setBody +import io.ktor.client.statement.bodyAsText +import io.ktor.http.ContentType +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.server.testing.ApplicationTestBuilder +import io.ktor.server.testing.testApplication +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class LocationPingRoutesTest { + @get:Rule + val folder = TemporaryFolder() + + @Test + fun `the overview requires an authenticated session`() = + testApplication { + val store = storeWithOneRidePing() + application { devConsoleModule(SessionAuthority()) { locationPings = { store } } } + + val response = client.get("/api/v1/location-pings") { header(HttpHeaders.Host, "localhost") } + + assertEquals(HttpStatusCode.Unauthorized, response.status) + } + + @Test + fun `the overview lists streams, schema, storage and captured tracks`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val store = storeWithOneRidePing() + application { devConsoleModule(sessions, sessionCodes) { locationPings = { store } } } + val session = approvedSession(sessions, sessionCodes) + + val body = client.get("/api/v1/location-pings") { authHeaders(session) }.bodyAsText() + + assertTrue(body.contains("\"configured\":true")) + assertTrue(body.contains("{\"name\":\"ride\",\"path\":\"/v1/rides/pings\",\"enabled\":true}")) + assertTrue(body.contains("\"groupLabel\":\"Order\"")) + assertTrue(body.contains("\"hasFixTime\":false")) + assertTrue(body.contains("\"groupId\":\"order-1\"")) + } + + @Test + fun `an unconfigured runtime reports that rather than failing`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + application { devConsoleModule(sessions, sessionCodes) } + val session = approvedSession(sessions, sessionCodes) + + val response = client.get("/api/v1/location-pings") { authHeaders(session) } + + assertEquals(HttpStatusCode.OK, response.status) + assertTrue(response.bodyAsText().contains("\"configured\":false")) + } + + @Test + fun `a track returns its points with a status the map can colour`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val store = storeWithOneRidePing() + application { devConsoleModule(sessions, sessionCodes) { locationPings = { store } } } + val session = approvedSession(sessions, sessionCodes) + val file = store.tracks().single().file + + val body = + client + .get( + "/api/v1/location-pings/track?stream=ride&file=$file", + ) { authHeaders(session) } + .bodyAsText() + + assertTrue(body.contains("\"lat\":23.79,\"lng\":90.41")) + assertTrue(body.contains("\"status\":\"failed\",\"statusCode\":401")) + assertTrue(body.contains("\"fields\":{\"order_id\":\"order-1\"}")) + } + + @Test + fun `an unknown track is not found`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val store = storeWithOneRidePing() + application { devConsoleModule(sessions, sessionCodes) { locationPings = { store } } } + val session = approvedSession(sessions, sessionCodes) + + val response = + client.get( + "/api/v1/location-pings/track?stream=ride&file=../x.jsonl", + ) { authHeaders(session) } + + assertEquals(HttpStatusCode.NotFound, response.status) + } + + @Test + fun `toggling a stream needs csrf and is audited`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val audit = InMemoryCommandAuditLog() + val store = storeWithOneRidePing() + application { + devConsoleModule(sessions, sessionCodes) { + locationPings = { store } + commandAuditLog = audit + } + } + val session = approvedSession(sessions, sessionCodes) + + val withoutCsrf = + client.put("/api/v1/location-pings/streams/ride") { + authHeaders(session) + setBody("false") + } + val withCsrf = + client.put("/api/v1/location-pings/streams/ride") { + controlHeaders(session) + setBody("false") + } + + assertEquals(HttpStatusCode.Forbidden, withoutCsrf.status) + assertEquals(HttpStatusCode.OK, withCsrf.status) + assertFalse(store.isEnabled("ride")) + assertTrue( + audit.events().any { + it.commandType == "location-pings.toggle" && + it.result == CommandAuditResult.SUCCESS + }, + ) + } + + @Test + fun `toggling an unknown stream is a validation failure`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val store = storeWithOneRidePing() + application { devConsoleModule(sessions, sessionCodes) { locationPings = { store } } } + val session = approvedSession(sessions, sessionCodes) + + val response = + client.put("/api/v1/location-pings/streams/idle") { + controlHeaders(session) + setBody("true") + } + + assertEquals(HttpStatusCode.BadRequest, response.status) + } + + @Test + fun `deleting removes the captured files`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val store = storeWithOneRidePing() + application { devConsoleModule(sessions, sessionCodes) { locationPings = { store } } } + val session = approvedSession(sessions, sessionCodes) + + val body = client.delete("/api/v1/location-pings?stream=ride") { controlHeaders(session) }.bodyAsText() + + assertEquals("{\"filesDeleted\":1,\"filesLeft\":0}", body) + assertTrue(store.tracks().isEmpty()) + } + + @Test + fun `every location ping route is refused while network capture is disabled`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val store = storeWithOneRidePing() + application { + devConsoleModule(sessions, sessionCodes) { + locationPings = { store } + metadata = ServerMetadata(captureCategories = listOf("logs")) + } + } + val session = approvedSession(sessions, sessionCodes) + + val read = client.get("/api/v1/location-pings") { authHeaders(session) } + val delete = client.delete("/api/v1/location-pings") { controlHeaders(session) } + + assertEquals(HttpStatusCode.Forbidden, read.status) + assertEquals(HttpStatusCode.Forbidden, delete.status) + assertEquals(1, store.tracks().size) + } + + private fun storeWithOneRidePing(): LocationPingStore = + LocationPingStore(folder.newFolder(), writer = { it.run() }).apply { + configure( + LocationPingTracking( + streams = listOf(LocationPingStream("ride", "/v1/rides/pings")), + schema = LocationPingSchema(groupIdKey = "order_id", groupLabel = "Order"), + ), + ) + setEnabled("ride", true) + record( + "https://api.test/v1/rides/pings", + """{"latitude":23.79,"longitude":90.41,"timestamp":1793016000000,"order_id":"order-1"}""", + LocationPingOutcome.Answered(401), + ) + } +} + +private fun HttpRequestBuilder.controlHeaders(session: BrowserSession) { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Authorization, "Bearer ${session.token}") + header(HttpHeaders.Origin, "http://localhost") + header("X-DevConsole-CSRF", session.csrfToken) +} + +private fun HttpRequestBuilder.authHeaders(session: BrowserSession) { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Authorization, "Bearer ${session.token}") +} + +private suspend fun ApplicationTestBuilder.approvedSession( + sessions: SessionAuthority, + sessionCodes: SessionCodeAuthority, +): BrowserSession { + val code = sessionCodes.issueCode().code + val response = + client.post("/api/v1/auth/session-code/exchange") { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("code=$code") + } + val token = Regex("\"accessToken\":\"([^\"]+)\"").find(response.bodyAsText())!!.groupValues[1] + return sessions.sessionForToken(token)!! +} From d3e931e0dd8a125efd8a84e63cdba8d5d425937c Mon Sep 17 00:00:00 2001 From: zakaria5729 Date: Mon, 26 Oct 2026 20:34:28 +0600 Subject: [PATCH 4/8] feat(dashboard): add a Location pings view with a map Replays a recorded track on an OpenStreetMap map. Each ping is a dot coloured by its outcome, the route runs through them in device-time order, and the first and last pings are ringed. The view has recording switches per stream, status and app-state filters, device and fix time gap labels, a ping list, a details dialog with copy as JSON, a route summary, auto-refresh, and delete track / delete all. Leaflet 1.9.4 ships with the dashboard (BSD-2, licence alongside). The CSP allows images from tile.openstreetmap.org and nothing else, and the OSM credit sits in the map legend. --- sdk/server-ktor/build.gradle.kts | 2 +- .../devconsole/server/ktor/DashboardAssets.kt | 6 + .../server/ktor/DevConsoleKtorModule.kt | 15 +- .../resources/devconsole-web/dashboard.css | 80 +++ .../resources/devconsole-web/dashboard.js | 21 +- .../main/resources/devconsole-web/index.html | 74 ++ .../devconsole-web/leaflet-LICENSE.txt | 26 + .../main/resources/devconsole-web/leaflet.css | 661 ++++++++++++++++++ .../main/resources/devconsole-web/leaflet.js | 6 + .../devconsole-web/location-pings.js | 548 +++++++++++++++ 10 files changed, 1436 insertions(+), 3 deletions(-) create mode 100644 sdk/server-ktor/src/main/resources/devconsole-web/leaflet-LICENSE.txt create mode 100644 sdk/server-ktor/src/main/resources/devconsole-web/leaflet.css create mode 100644 sdk/server-ktor/src/main/resources/devconsole-web/leaflet.js create mode 100644 sdk/server-ktor/src/main/resources/devconsole-web/location-pings.js diff --git a/sdk/server-ktor/build.gradle.kts b/sdk/server-ktor/build.gradle.kts index 9844987..f7f8d67 100644 --- a/sdk/server-ktor/build.gradle.kts +++ b/sdk/server-ktor/build.gradle.kts @@ -33,7 +33,7 @@ dependencies { } val dashboardAssetFiles: List = - listOf("index.html", "dashboard.css", "dashboard.js") + listOf("index.html", "dashboard.css", "dashboard.js", "location-pings.js", "leaflet.js", "leaflet.css") .map { name -> layout.projectDirectory.file("src/main/resources/devconsole-web/$name").asFile } val dashboardManifest = layout.buildDirectory.file("generated/devconsole-web/asset-manifest.json") diff --git a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DashboardAssets.kt b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DashboardAssets.kt index 467eb05..4917cda 100644 --- a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DashboardAssets.kt +++ b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DashboardAssets.kt @@ -7,6 +7,12 @@ internal object DashboardAssets { fun js(): String = resource("/devconsole-web/dashboard.js") + fun locationPingsJs(): String = resource("/devconsole-web/location-pings.js") + + fun leafletJs(): String = resource("/devconsole-web/leaflet.js") + + fun leafletCss(): String = resource("/devconsole-web/leaflet.css") + /** The DevConsole mark, served as the dashboard's favicon. Read as bytes -- it is not text. */ fun favicon(): ByteArray = binaryResource("/devconsole-web/favicon.webp") diff --git a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt index 1e20508..afa1e59 100644 --- a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt +++ b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt @@ -467,7 +467,8 @@ fun Application.devConsoleModule( // the dashboard has no
elements and never submits one natively (see // dashboard.js/index.html -- every mutation goes through fetch()). "default-src 'self'; script-src 'self'; " + - "style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src $webSocketSource; " + + "style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: $MAP_TILE_SOURCE; " + + "connect-src $webSocketSource; " + "base-uri 'self'; frame-ancestors 'none'; form-action 'none'", ) call.response.headers.append(HttpHeaders.CacheControl, "no-store") @@ -614,6 +615,16 @@ fun Application.devConsoleModule( call.response.headers.append(HttpHeaders.CacheControl, "no-store") call.respondText(DashboardAssets.js(), contentType = io.ktor.http.ContentType.Text.JavaScript) } + get("/assets/location-pings.js") { + call.response.headers.append(HttpHeaders.CacheControl, "no-store") + call.respondText(DashboardAssets.locationPingsJs(), contentType = io.ktor.http.ContentType.Text.JavaScript) + } + get("/assets/leaflet.js") { + call.respondText(DashboardAssets.leafletJs(), contentType = io.ktor.http.ContentType.Text.JavaScript) + } + get("/assets/leaflet.css") { + call.respondText(DashboardAssets.leafletCss(), contentType = io.ktor.http.ContentType.Text.CSS) + } // Browsers request the favicon before -- and independently of -- any session, so it is // unauthenticated for the same reason the two assets above are. get("/assets/favicon.webp") { @@ -4759,6 +4770,8 @@ private fun pruneStaleExports( private const val STALE_EXPORT_MAX_AGE_MS = 60L * 60L * 1000L +private const val MAP_TILE_SOURCE = "https://tile.openstreetmap.org" + private fun locationPingOverviewJson(store: LocationPingStore?): String { if (store == null) return "{\"configured\":false,\"streams\":[],\"tracks\":[]}" val tracking = store.tracking diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css index 1bcd2f2..0936ee5 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css +++ b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css @@ -1622,3 +1622,83 @@ body.mode-simple .shortcut-row.adv-only .shortcut-adv-note { display: inline; } .crumb.crumb-sev-error { border-left-color: var(--error); } .crumb.crumb-sev-warn { border-left-color: var(--warn); } .crumb-empty { font-size: 11.5px; color: var(--muted); padding: 4px 0 8px; } + +#locationPingsView.active { flex: 1 1 0%; min-height: 0; display: flex; flex-direction: column; } +.tone-text-success { color: var(--success); } +.lp-streams { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; } +.lp-streams:empty { display: none; } +.lp-stream { + display: inline-flex; align-items: center; gap: 8px; height: 32px; padding: 0 12px 0 10px; + border: 1px solid var(--line); border-radius: 8px; background: var(--panel); cursor: pointer; font-size: 12px; +} +.lp-stream:hover { border-color: var(--border-strong); } +.lp-stream.on { border-color: var(--success); background: var(--success-soft); } +.lp-stream input, .lp-check input { width: auto; margin: 0; padding: 0; accent-color: var(--signal); } +.lp-stream-name { font-weight: 600; color: var(--ink); } +.lp-stream-path { font-family: var(--font-mono); font-size: 11px; color: var(--muted); } +.lp-check { + display: inline-flex; align-items: center; gap: 7px; height: 32px; padding: 0 11px 0 9px; + border: 1px solid var(--line); border-radius: 8px; color: var(--muted); font-size: 12px; cursor: pointer; user-select: none; +} +.lp-check:hover { color: var(--ink); border-color: var(--border-strong); } +.lp-check[hidden] { display: none; } +#lpStream { min-width: 140px; height: 32px; padding-top: 0; padding-bottom: 0; } +.lp-track-field select { min-width: 220px; max-width: 360px; height: 32px; padding-top: 0; padding-bottom: 0; } +.lp-note { margin-bottom: 10px; padding: 8px 12px; border: 1px solid var(--warn); border-radius: 8px; background: var(--warn-soft); color: var(--warn); font-size: 12px; } +#lpMetrics { margin-bottom: 12px; } +.lp-body { flex: 1 1 auto; min-height: 420px; display: flex; border: 1px solid var(--line); border-radius: 8px; overflow: hidden; } +.lp-map-wrap { position: relative; flex: 1 1 auto; min-width: 0; } +.lp-map { position: absolute; inset: 0; background: var(--surface-3); } +.lp-empty { position: absolute; inset: 0; z-index: 500; display: flex; align-items: center; justify-content: center; padding: 24px; background: color-mix(in srgb, var(--ground) 82%, transparent); } +.lp-empty[hidden] { display: none; } +.lp-legend { + position: absolute; top: 10px; right: 10px; z-index: 450; display: flex; flex-wrap: wrap; gap: 12px; + padding: 6px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); font-size: 11.5px; color: var(--muted); +} +.lp-legend span { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; } +.lp-dot { display: inline-block; width: 9px; height: 9px; flex: 0 0 9px; border-radius: 50%; vertical-align: middle; } +.lp-sent { background: var(--success); } +.lp-failed { background: var(--error); } +.lp-dropped { background: var(--warn); } +.lp-offline { background: var(--muted); } +.lp-text-sent { color: var(--success); } +.lp-text-failed { color: var(--error); } +.lp-text-dropped { color: var(--warn); } +.lp-text-offline { color: var(--muted); } +.lp-list { flex: 0 0 360px; display: flex; flex-direction: column; min-height: 0; border-left: 1px solid var(--line); background: var(--panel); } +.lp-list-head, .lp-row { display: grid; grid-template-columns: 10ch 1fr 1fr 9ch; gap: 8px; align-items: center; padding: 7px 12px; } +.lp-list-head { border-bottom: 1px solid var(--line); background: var(--surface-2); font-size: 10.5px; font-weight: 600; color: var(--text-3); text-transform: uppercase; letter-spacing: 0.04em; } +.lp-list-head [hidden], .lp-row [hidden] { display: none; } +.lp-list-body { flex: 1 1 auto; overflow-y: auto; } +.lp-row { + width: 100%; border: 0; border-bottom: 1px solid var(--line); border-radius: 0; background: transparent; + font-family: var(--font-mono); font-size: 11.5px; color: var(--muted); text-align: left; +} +.lp-row:hover { background: var(--surface-2); color: var(--ink); border-color: var(--line); } +.lp-row.selected { background: var(--signal-soft); color: var(--ink); box-shadow: inset 3px 0 0 var(--signal); } +.lp-row-index { display: inline-flex; align-items: center; gap: 6px; color: var(--ink); font-weight: 600; } +.lp-row-app { color: var(--text-3); font-weight: 400; } +.lp-row-status { text-align: right; } +.lp-list-more { padding: 12px; font-size: 11.5px; color: var(--muted); text-align: center; } +.lp-gap-label.leaflet-tooltip { + padding: 1px 5px; border: 0; border-radius: 4px; box-shadow: none; + background: rgba(0, 0, 0, 0.72); color: #fff; font: 600 10.5px var(--font-mono); +} +.lp-gap-label.leaflet-tooltip::before { display: none; } +.lp-ping-rows { display: grid; max-height: 60vh; overflow-y: auto; margin-bottom: 12px; } +.lp-ping-row { display: grid; grid-template-columns: 160px 1fr; gap: 12px; padding: 7px 0; border-bottom: 1px solid var(--line); font: 12px var(--font-mono); } +.lp-ping-label { color: var(--text-3); } +.lp-ping-value { color: var(--ink); word-break: break-word; display: inline-flex; align-items: center; gap: 6px; } +#locationPingsView .leaflet-container { font-family: var(--font-ui); background: var(--surface-3); } +#locationPingsView .leaflet-bar a { background: var(--panel); color: var(--ink); border-bottom-color: var(--line); } +#locationPingsView .leaflet-bar a:hover { background: var(--surface-2); color: var(--signal); } +.lp-map-credit { padding-left: 12px; border-left: 1px solid var(--line); color: var(--text-3); text-decoration: none; white-space: nowrap; } +.lp-map-credit:hover { color: var(--signal); } +:root:not([data-theme="light"]) #locationPingsView .leaflet-tile { filter: invert(1) hue-rotate(180deg) brightness(0.9) contrast(0.9) saturate(0.7); } +@media (max-width: 900px) { + .lp-body { flex-direction: column; min-height: 0; } + .lp-map-wrap { flex: 0 0 auto; height: 55vh; min-height: 320px; } + .lp-list { flex: 0 0 auto; max-height: 50vh; border-left: 0; border-top: 1px solid var(--line); } + .lp-track-field select { min-width: 0; max-width: 100%; } + .lp-legend { left: 10px; right: auto; top: auto; bottom: 28px; } +} diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js index 53bcc1e..dd9b3d4 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js +++ b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js @@ -1185,7 +1185,7 @@ // (see applyCaptureCategoryGating and the Sockets protocol-chip logic in renderSocketChips). // ================================================================ const CATEGORY_RAIL = { - network: { ids: ['viewNetwork'], views: ['network'] }, + network: { ids: ['viewNetwork', 'viewLocationPings'], views: ['network', 'locationPings'] }, socket: { ids: ['viewSockets'], views: ['socket'] }, mqtt: { ids: ['viewSockets'], views: ['socket'] }, push: { ids: ['viewPush'], views: ['push'] }, @@ -4788,6 +4788,21 @@ let remoteConfigQuery = ''; let remoteConfigSourceFilter = 'all'; const REMOTE_CONFIG_SOURCE_TONE = { remote: 'signal', override: 'warn', default: 'muted', static: 'muted', unknown: 'muted' }; + function loadLocationPings() { + if (!window.DevConsoleLocationPings) return undefined; + return window.DevConsoleLocationPings.load({ + hasSession, + auth, + controlHeaders, + toast, + openConfirm, + esc, + copyToClipboard, + isVisible: () => currentView === 'locationPings', + setNavCount: (count) => setNavCount('navCountLocationPings', count), + }); + } + async function loadRemoteConfig() { if (!token) return; const r = await fetch('/api/v1/remote-config', { headers: auth() }); @@ -7665,6 +7680,7 @@ timeline: 'timelineView', network: 'networkView', socket: 'socketView', + locationPings: 'locationPingsView', state: 'stateView', remoteConfig: 'remoteConfigView', preferences: 'preferencesView', @@ -7688,6 +7704,7 @@ timeline: 'viewTimeline', network: 'viewNetwork', socket: 'viewSockets', + locationPings: 'viewLocationPings', state: 'viewState', remoteConfig: 'viewRemoteConfig', preferences: 'viewPreferences', @@ -7723,6 +7740,7 @@ timeline: load, network: loadNetwork, socket: loadSockets, + locationPings: loadLocationPings, state: loadState, remoteConfig: loadRemoteConfig, preferences: loadPreferences, @@ -7957,6 +7975,7 @@ $('viewTimeline').onclick = () => show('timeline'); $('viewNetwork').onclick = () => show('network'); $('viewSockets').onclick = () => show('socket'); + $('viewLocationPings').onclick = () => show('locationPings'); $('viewState').onclick = () => show('state'); $('viewRemoteConfig').onclick = () => show('remoteConfig'); $('viewPush').onclick = () => show('push'); diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/index.html b/sdk/server-ktor/src/main/resources/devconsole-web/index.html index f2070ff..5e62066 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/index.html +++ b/sdk/server-ktor/src/main/resources/devconsole-web/index.html @@ -6,6 +6,7 @@ DevConsole + +
+
+

Location pings

+

Location-ping requests recorded to the device and replayed on a map. Each dot is one ping, coloured by what happened to it; the gaps show how long the device waited between pings.

+
+
+ +
+ + +
+ Status +
+ + + + + +
+
+ + + + + + + +
+ +
+
+
+
+ + + + + © OpenStreetMap +
+
Not connected yet
Open DevConsole on the device → More → scan the QR or paste the code in Overview to see recorded location pings.
+
+ +
+
+
@@ -771,7 +830,22 @@
+ +
+ + diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/leaflet-LICENSE.txt b/sdk/server-ktor/src/main/resources/devconsole-web/leaflet-LICENSE.txt new file mode 100644 index 0000000..7b41f20 --- /dev/null +++ b/sdk/server-ktor/src/main/resources/devconsole-web/leaflet-LICENSE.txt @@ -0,0 +1,26 @@ +BSD 2-Clause License + +Copyright (c) 2010-2023, Volodymyr Agafonkin +Copyright (c) 2010-2011, CloudMade +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/leaflet.css b/sdk/server-ktor/src/main/resources/devconsole-web/leaflet.css new file mode 100644 index 0000000..9ade8dc --- /dev/null +++ b/sdk/server-ktor/src/main/resources/devconsole-web/leaflet.css @@ -0,0 +1,661 @@ +/* required styles */ + +.leaflet-pane, +.leaflet-tile, +.leaflet-marker-icon, +.leaflet-marker-shadow, +.leaflet-tile-container, +.leaflet-pane > svg, +.leaflet-pane > canvas, +.leaflet-zoom-box, +.leaflet-image-layer, +.leaflet-layer { + position: absolute; + left: 0; + top: 0; + } +.leaflet-container { + overflow: hidden; + } +.leaflet-tile, +.leaflet-marker-icon, +.leaflet-marker-shadow { + -webkit-user-select: none; + -moz-user-select: none; + user-select: none; + -webkit-user-drag: none; + } +/* Prevents IE11 from highlighting tiles in blue */ +.leaflet-tile::selection { + background: transparent; +} +/* Safari renders non-retina tile on retina better with this, but Chrome is worse */ +.leaflet-safari .leaflet-tile { + image-rendering: -webkit-optimize-contrast; + } +/* hack that prevents hw layers "stretching" when loading new tiles */ +.leaflet-safari .leaflet-tile-container { + width: 1600px; + height: 1600px; + -webkit-transform-origin: 0 0; + } +.leaflet-marker-icon, +.leaflet-marker-shadow { + display: block; + } +/* .leaflet-container svg: reset svg max-width decleration shipped in Joomla! (joomla.org) 3.x */ +/* .leaflet-container img: map is broken in FF if you have max-width: 100% on tiles */ +.leaflet-container .leaflet-overlay-pane svg { + max-width: none !important; + max-height: none !important; + } +.leaflet-container .leaflet-marker-pane img, +.leaflet-container .leaflet-shadow-pane img, +.leaflet-container .leaflet-tile-pane img, +.leaflet-container img.leaflet-image-layer, +.leaflet-container .leaflet-tile { + max-width: none !important; + max-height: none !important; + width: auto; + padding: 0; + } + +.leaflet-container img.leaflet-tile { + /* See: https://bugs.chromium.org/p/chromium/issues/detail?id=600120 */ + mix-blend-mode: plus-lighter; +} + +.leaflet-container.leaflet-touch-zoom { + -ms-touch-action: pan-x pan-y; + touch-action: pan-x pan-y; + } +.leaflet-container.leaflet-touch-drag { + -ms-touch-action: pinch-zoom; + /* Fallback for FF which doesn't support pinch-zoom */ + touch-action: none; + touch-action: pinch-zoom; +} +.leaflet-container.leaflet-touch-drag.leaflet-touch-zoom { + -ms-touch-action: none; + touch-action: none; +} +.leaflet-container { + -webkit-tap-highlight-color: transparent; +} +.leaflet-container a { + -webkit-tap-highlight-color: rgba(51, 181, 229, 0.4); +} +.leaflet-tile { + filter: inherit; + visibility: hidden; + } +.leaflet-tile-loaded { + visibility: inherit; + } +.leaflet-zoom-box { + width: 0; + height: 0; + -moz-box-sizing: border-box; + box-sizing: border-box; + z-index: 800; + } +/* workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=888319 */ +.leaflet-overlay-pane svg { + -moz-user-select: none; + } + +.leaflet-pane { z-index: 400; } + +.leaflet-tile-pane { z-index: 200; } +.leaflet-overlay-pane { z-index: 400; } +.leaflet-shadow-pane { z-index: 500; } +.leaflet-marker-pane { z-index: 600; } +.leaflet-tooltip-pane { z-index: 650; } +.leaflet-popup-pane { z-index: 700; } + +.leaflet-map-pane canvas { z-index: 100; } +.leaflet-map-pane svg { z-index: 200; } + +.leaflet-vml-shape { + width: 1px; + height: 1px; + } +.lvml { + behavior: url(#default#VML); + display: inline-block; + position: absolute; + } + + +/* control positioning */ + +.leaflet-control { + position: relative; + z-index: 800; + pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */ + pointer-events: auto; + } +.leaflet-top, +.leaflet-bottom { + position: absolute; + z-index: 1000; + pointer-events: none; + } +.leaflet-top { + top: 0; + } +.leaflet-right { + right: 0; + } +.leaflet-bottom { + bottom: 0; + } +.leaflet-left { + left: 0; + } +.leaflet-control { + float: left; + clear: both; + } +.leaflet-right .leaflet-control { + float: right; + } +.leaflet-top .leaflet-control { + margin-top: 10px; + } +.leaflet-bottom .leaflet-control { + margin-bottom: 10px; + } +.leaflet-left .leaflet-control { + margin-left: 10px; + } +.leaflet-right .leaflet-control { + margin-right: 10px; + } + + +/* zoom and fade animations */ + +.leaflet-fade-anim .leaflet-popup { + opacity: 0; + -webkit-transition: opacity 0.2s linear; + -moz-transition: opacity 0.2s linear; + transition: opacity 0.2s linear; + } +.leaflet-fade-anim .leaflet-map-pane .leaflet-popup { + opacity: 1; + } +.leaflet-zoom-animated { + -webkit-transform-origin: 0 0; + -ms-transform-origin: 0 0; + transform-origin: 0 0; + } +svg.leaflet-zoom-animated { + will-change: transform; +} + +.leaflet-zoom-anim .leaflet-zoom-animated { + -webkit-transition: -webkit-transform 0.25s cubic-bezier(0,0,0.25,1); + -moz-transition: -moz-transform 0.25s cubic-bezier(0,0,0.25,1); + transition: transform 0.25s cubic-bezier(0,0,0.25,1); + } +.leaflet-zoom-anim .leaflet-tile, +.leaflet-pan-anim .leaflet-tile { + -webkit-transition: none; + -moz-transition: none; + transition: none; + } + +.leaflet-zoom-anim .leaflet-zoom-hide { + visibility: hidden; + } + + +/* cursors */ + +.leaflet-interactive { + cursor: pointer; + } +.leaflet-grab { + cursor: -webkit-grab; + cursor: -moz-grab; + cursor: grab; + } +.leaflet-crosshair, +.leaflet-crosshair .leaflet-interactive { + cursor: crosshair; + } +.leaflet-popup-pane, +.leaflet-control { + cursor: auto; + } +.leaflet-dragging .leaflet-grab, +.leaflet-dragging .leaflet-grab .leaflet-interactive, +.leaflet-dragging .leaflet-marker-draggable { + cursor: move; + cursor: -webkit-grabbing; + cursor: -moz-grabbing; + cursor: grabbing; + } + +/* marker & overlays interactivity */ +.leaflet-marker-icon, +.leaflet-marker-shadow, +.leaflet-image-layer, +.leaflet-pane > svg path, +.leaflet-tile-container { + pointer-events: none; + } + +.leaflet-marker-icon.leaflet-interactive, +.leaflet-image-layer.leaflet-interactive, +.leaflet-pane > svg path.leaflet-interactive, +svg.leaflet-image-layer.leaflet-interactive path { + pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */ + pointer-events: auto; + } + +/* visual tweaks */ + +.leaflet-container { + background: #ddd; + outline-offset: 1px; + } +.leaflet-container a { + color: #0078A8; + } +.leaflet-zoom-box { + border: 2px dotted #38f; + background: rgba(255,255,255,0.5); + } + + +/* general typography */ +.leaflet-container { + font-family: "Helvetica Neue", Arial, Helvetica, sans-serif; + font-size: 12px; + font-size: 0.75rem; + line-height: 1.5; + } + + +/* general toolbar styles */ + +.leaflet-bar { + box-shadow: 0 1px 5px rgba(0,0,0,0.65); + border-radius: 4px; + } +.leaflet-bar a { + background-color: #fff; + border-bottom: 1px solid #ccc; + width: 26px; + height: 26px; + line-height: 26px; + display: block; + text-align: center; + text-decoration: none; + color: black; + } +.leaflet-bar a, +.leaflet-control-layers-toggle { + background-position: 50% 50%; + background-repeat: no-repeat; + display: block; + } +.leaflet-bar a:hover, +.leaflet-bar a:focus { + background-color: #f4f4f4; + } +.leaflet-bar a:first-child { + border-top-left-radius: 4px; + border-top-right-radius: 4px; + } +.leaflet-bar a:last-child { + border-bottom-left-radius: 4px; + border-bottom-right-radius: 4px; + border-bottom: none; + } +.leaflet-bar a.leaflet-disabled { + cursor: default; + background-color: #f4f4f4; + color: #bbb; + } + +.leaflet-touch .leaflet-bar a { + width: 30px; + height: 30px; + line-height: 30px; + } +.leaflet-touch .leaflet-bar a:first-child { + border-top-left-radius: 2px; + border-top-right-radius: 2px; + } +.leaflet-touch .leaflet-bar a:last-child { + border-bottom-left-radius: 2px; + border-bottom-right-radius: 2px; + } + +/* zoom control */ + +.leaflet-control-zoom-in, +.leaflet-control-zoom-out { + font: bold 18px 'Lucida Console', Monaco, monospace; + text-indent: 1px; + } + +.leaflet-touch .leaflet-control-zoom-in, .leaflet-touch .leaflet-control-zoom-out { + font-size: 22px; + } + + +/* layers control */ + +.leaflet-control-layers { + box-shadow: 0 1px 5px rgba(0,0,0,0.4); + background: #fff; + border-radius: 5px; + } +.leaflet-control-layers-toggle { + background-image: url(images/layers.png); + width: 36px; + height: 36px; + } +.leaflet-retina .leaflet-control-layers-toggle { + background-image: url(images/layers-2x.png); + background-size: 26px 26px; + } +.leaflet-touch .leaflet-control-layers-toggle { + width: 44px; + height: 44px; + } +.leaflet-control-layers .leaflet-control-layers-list, +.leaflet-control-layers-expanded .leaflet-control-layers-toggle { + display: none; + } +.leaflet-control-layers-expanded .leaflet-control-layers-list { + display: block; + position: relative; + } +.leaflet-control-layers-expanded { + padding: 6px 10px 6px 6px; + color: #333; + background: #fff; + } +.leaflet-control-layers-scrollbar { + overflow-y: scroll; + overflow-x: hidden; + padding-right: 5px; + } +.leaflet-control-layers-selector { + margin-top: 2px; + position: relative; + top: 1px; + } +.leaflet-control-layers label { + display: block; + font-size: 13px; + font-size: 1.08333em; + } +.leaflet-control-layers-separator { + height: 0; + border-top: 1px solid #ddd; + margin: 5px -10px 5px -6px; + } + +/* Default icon URLs */ +.leaflet-default-icon-path { /* used only in path-guessing heuristic, see L.Icon.Default */ + background-image: url(images/marker-icon.png); + } + + +/* attribution and scale controls */ + +.leaflet-container .leaflet-control-attribution { + background: #fff; + background: rgba(255, 255, 255, 0.8); + margin: 0; + } +.leaflet-control-attribution, +.leaflet-control-scale-line { + padding: 0 5px; + color: #333; + line-height: 1.4; + } +.leaflet-control-attribution a { + text-decoration: none; + } +.leaflet-control-attribution a:hover, +.leaflet-control-attribution a:focus { + text-decoration: underline; + } +.leaflet-attribution-flag { + display: inline !important; + vertical-align: baseline !important; + width: 1em; + height: 0.6669em; + } +.leaflet-left .leaflet-control-scale { + margin-left: 5px; + } +.leaflet-bottom .leaflet-control-scale { + margin-bottom: 5px; + } +.leaflet-control-scale-line { + border: 2px solid #777; + border-top: none; + line-height: 1.1; + padding: 2px 5px 1px; + white-space: nowrap; + -moz-box-sizing: border-box; + box-sizing: border-box; + background: rgba(255, 255, 255, 0.8); + text-shadow: 1px 1px #fff; + } +.leaflet-control-scale-line:not(:first-child) { + border-top: 2px solid #777; + border-bottom: none; + margin-top: -2px; + } +.leaflet-control-scale-line:not(:first-child):not(:last-child) { + border-bottom: 2px solid #777; + } + +.leaflet-touch .leaflet-control-attribution, +.leaflet-touch .leaflet-control-layers, +.leaflet-touch .leaflet-bar { + box-shadow: none; + } +.leaflet-touch .leaflet-control-layers, +.leaflet-touch .leaflet-bar { + border: 2px solid rgba(0,0,0,0.2); + background-clip: padding-box; + } + + +/* popup */ + +.leaflet-popup { + position: absolute; + text-align: center; + margin-bottom: 20px; + } +.leaflet-popup-content-wrapper { + padding: 1px; + text-align: left; + border-radius: 12px; + } +.leaflet-popup-content { + margin: 13px 24px 13px 20px; + line-height: 1.3; + font-size: 13px; + font-size: 1.08333em; + min-height: 1px; + } +.leaflet-popup-content p { + margin: 17px 0; + margin: 1.3em 0; + } +.leaflet-popup-tip-container { + width: 40px; + height: 20px; + position: absolute; + left: 50%; + margin-top: -1px; + margin-left: -20px; + overflow: hidden; + pointer-events: none; + } +.leaflet-popup-tip { + width: 17px; + height: 17px; + padding: 1px; + + margin: -10px auto 0; + pointer-events: auto; + + -webkit-transform: rotate(45deg); + -moz-transform: rotate(45deg); + -ms-transform: rotate(45deg); + transform: rotate(45deg); + } +.leaflet-popup-content-wrapper, +.leaflet-popup-tip { + background: white; + color: #333; + box-shadow: 0 3px 14px rgba(0,0,0,0.4); + } +.leaflet-container a.leaflet-popup-close-button { + position: absolute; + top: 0; + right: 0; + border: none; + text-align: center; + width: 24px; + height: 24px; + font: 16px/24px Tahoma, Verdana, sans-serif; + color: #757575; + text-decoration: none; + background: transparent; + } +.leaflet-container a.leaflet-popup-close-button:hover, +.leaflet-container a.leaflet-popup-close-button:focus { + color: #585858; + } +.leaflet-popup-scrolled { + overflow: auto; + } + +.leaflet-oldie .leaflet-popup-content-wrapper { + -ms-zoom: 1; + } +.leaflet-oldie .leaflet-popup-tip { + width: 24px; + margin: 0 auto; + + -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)"; + filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678); + } + +.leaflet-oldie .leaflet-control-zoom, +.leaflet-oldie .leaflet-control-layers, +.leaflet-oldie .leaflet-popup-content-wrapper, +.leaflet-oldie .leaflet-popup-tip { + border: 1px solid #999; + } + + +/* div icon */ + +.leaflet-div-icon { + background: #fff; + border: 1px solid #666; + } + + +/* Tooltip */ +/* Base styles for the element that has a tooltip */ +.leaflet-tooltip { + position: absolute; + padding: 6px; + background-color: #fff; + border: 1px solid #fff; + border-radius: 3px; + color: #222; + white-space: nowrap; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + pointer-events: none; + box-shadow: 0 1px 3px rgba(0,0,0,0.4); + } +.leaflet-tooltip.leaflet-interactive { + cursor: pointer; + pointer-events: auto; + } +.leaflet-tooltip-top:before, +.leaflet-tooltip-bottom:before, +.leaflet-tooltip-left:before, +.leaflet-tooltip-right:before { + position: absolute; + pointer-events: none; + border: 6px solid transparent; + background: transparent; + content: ""; + } + +/* Directions */ + +.leaflet-tooltip-bottom { + margin-top: 6px; +} +.leaflet-tooltip-top { + margin-top: -6px; +} +.leaflet-tooltip-bottom:before, +.leaflet-tooltip-top:before { + left: 50%; + margin-left: -6px; + } +.leaflet-tooltip-top:before { + bottom: 0; + margin-bottom: -12px; + border-top-color: #fff; + } +.leaflet-tooltip-bottom:before { + top: 0; + margin-top: -12px; + margin-left: -6px; + border-bottom-color: #fff; + } +.leaflet-tooltip-left { + margin-left: -6px; +} +.leaflet-tooltip-right { + margin-left: 6px; +} +.leaflet-tooltip-left:before, +.leaflet-tooltip-right:before { + top: 50%; + margin-top: -6px; + } +.leaflet-tooltip-left:before { + right: 0; + margin-right: -12px; + border-left-color: #fff; + } +.leaflet-tooltip-right:before { + left: 0; + margin-left: -12px; + border-right-color: #fff; + } + +/* Printing */ + +@media print { + /* Prevent printers from removing background-images of controls. */ + .leaflet-control { + -webkit-print-color-adjust: exact; + print-color-adjust: exact; + } + } diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/leaflet.js b/sdk/server-ktor/src/main/resources/devconsole-web/leaflet.js new file mode 100644 index 0000000..a3bf693 --- /dev/null +++ b/sdk/server-ktor/src/main/resources/devconsole-web/leaflet.js @@ -0,0 +1,6 @@ +/* @preserve + * Leaflet 1.9.4, a JS library for interactive maps. https://leafletjs.com + * (c) 2010-2023 Vladimir Agafonkin, (c) 2010-2011 CloudMade + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).leaflet={})}(this,function(t){"use strict";function l(t){for(var e,i,n=1,o=arguments.length;n=this.min.x&&i.x<=this.max.x&&e.y>=this.min.y&&i.y<=this.max.y},intersects:function(t){t=_(t);var e=this.min,i=this.max,n=t.min,t=t.max,o=t.x>=e.x&&n.x<=i.x,t=t.y>=e.y&&n.y<=i.y;return o&&t},overlaps:function(t){t=_(t);var e=this.min,i=this.max,n=t.min,t=t.max,o=t.x>e.x&&n.xe.y&&n.y=n.lat&&i.lat<=o.lat&&e.lng>=n.lng&&i.lng<=o.lng},intersects:function(t){t=g(t);var e=this._southWest,i=this._northEast,n=t.getSouthWest(),t=t.getNorthEast(),o=t.lat>=e.lat&&n.lat<=i.lat,t=t.lng>=e.lng&&n.lng<=i.lng;return o&&t},overlaps:function(t){t=g(t);var e=this._southWest,i=this._northEast,n=t.getSouthWest(),t=t.getNorthEast(),o=t.lat>e.lat&&n.late.lng&&n.lng","http://www.w3.org/2000/svg"===(Wt.firstChild&&Wt.firstChild.namespaceURI));function y(t){return 0<=navigator.userAgent.toLowerCase().indexOf(t)}var b={ie:pt,ielt9:mt,edge:n,webkit:ft,android:gt,android23:vt,androidStock:yt,opera:xt,chrome:wt,gecko:bt,safari:Pt,phantom:Lt,opera12:o,win:Tt,ie3d:Mt,webkit3d:zt,gecko3d:_t,any3d:Ct,mobile:Zt,mobileWebkit:St,mobileWebkit3d:Et,msPointer:kt,pointer:Ot,touch:Bt,touchNative:At,mobileOpera:It,mobileGecko:Rt,retina:Nt,passiveEvents:Dt,canvas:jt,svg:Ht,vml:!Ht&&function(){try{var t=document.createElement("div"),e=(t.innerHTML='',t.firstChild);return e.style.behavior="url(#default#VML)",e&&"object"==typeof e.adj}catch(t){return!1}}(),inlineSvg:Wt,mac:0===navigator.platform.indexOf("Mac"),linux:0===navigator.platform.indexOf("Linux")},Ft=b.msPointer?"MSPointerDown":"pointerdown",Ut=b.msPointer?"MSPointerMove":"pointermove",Vt=b.msPointer?"MSPointerUp":"pointerup",qt=b.msPointer?"MSPointerCancel":"pointercancel",Gt={touchstart:Ft,touchmove:Ut,touchend:Vt,touchcancel:qt},Kt={touchstart:function(t,e){e.MSPOINTER_TYPE_TOUCH&&e.pointerType===e.MSPOINTER_TYPE_TOUCH&&O(e);ee(t,e)},touchmove:ee,touchend:ee,touchcancel:ee},Yt={},Xt=!1;function Jt(t,e,i){return"touchstart"!==e||Xt||(document.addEventListener(Ft,$t,!0),document.addEventListener(Ut,Qt,!0),document.addEventListener(Vt,te,!0),document.addEventListener(qt,te,!0),Xt=!0),Kt[e]?(i=Kt[e].bind(this,i),t.addEventListener(Gt[e],i,!1),i):(console.warn("wrong event specified:",e),u)}function $t(t){Yt[t.pointerId]=t}function Qt(t){Yt[t.pointerId]&&(Yt[t.pointerId]=t)}function te(t){delete Yt[t.pointerId]}function ee(t,e){if(e.pointerType!==(e.MSPOINTER_TYPE_MOUSE||"mouse")){for(var i in e.touches=[],Yt)e.touches.push(Yt[i]);e.changedTouches=[e],t(e)}}var ie=200;function ne(t,i){t.addEventListener("dblclick",i);var n,o=0;function e(t){var e;1!==t.detail?n=t.detail:"mouse"===t.pointerType||t.sourceCapabilities&&!t.sourceCapabilities.firesTouchEvents||((e=Ne(t)).some(function(t){return t instanceof HTMLLabelElement&&t.attributes.for})&&!e.some(function(t){return t instanceof HTMLInputElement||t instanceof HTMLSelectElement})||((e=Date.now())-o<=ie?2===++n&&i(function(t){var e,i,n={};for(i in t)e=t[i],n[i]=e&&e.bind?e.bind(t):e;return(t=n).type="dblclick",n.detail=2,n.isTrusted=!1,n._simulated=!0,n}(t)):n=1,o=e))}return t.addEventListener("click",e),{dblclick:i,simDblclick:e}}var oe,se,re,ae,he,le,ue=we(["transform","webkitTransform","OTransform","MozTransform","msTransform"]),ce=we(["webkitTransition","transition","OTransition","MozTransition","msTransition"]),de="webkitTransition"===ce||"OTransition"===ce?ce+"End":"transitionend";function _e(t){return"string"==typeof t?document.getElementById(t):t}function pe(t,e){var i=t.style[e]||t.currentStyle&&t.currentStyle[e];return"auto"===(i=i&&"auto"!==i||!document.defaultView?i:(t=document.defaultView.getComputedStyle(t,null))?t[e]:null)?null:i}function P(t,e,i){t=document.createElement(t);return t.className=e||"",i&&i.appendChild(t),t}function T(t){var e=t.parentNode;e&&e.removeChild(t)}function me(t){for(;t.firstChild;)t.removeChild(t.firstChild)}function fe(t){var e=t.parentNode;e&&e.lastChild!==t&&e.appendChild(t)}function ge(t){var e=t.parentNode;e&&e.firstChild!==t&&e.insertBefore(t,e.firstChild)}function ve(t,e){return void 0!==t.classList?t.classList.contains(e):0<(t=xe(t)).length&&new RegExp("(^|\\s)"+e+"(\\s|$)").test(t)}function M(t,e){var i;if(void 0!==t.classList)for(var n=F(e),o=0,s=n.length;othis.options.maxZoom)?this.setZoom(t):this},panInsideBounds:function(t,e){this._enforcingBounds=!0;var i=this.getCenter(),t=this._limitCenter(i,this._zoom,g(t));return i.equals(t)||this.panTo(t,e),this._enforcingBounds=!1,this},panInside:function(t,e){var i=m((e=e||{}).paddingTopLeft||e.padding||[0,0]),n=m(e.paddingBottomRight||e.padding||[0,0]),o=this.project(this.getCenter()),t=this.project(t),s=this.getPixelBounds(),i=_([s.min.add(i),s.max.subtract(n)]),s=i.getSize();return i.contains(t)||(this._enforcingBounds=!0,n=t.subtract(i.getCenter()),i=i.extend(t).getSize().subtract(s),o.x+=n.x<0?-i.x:i.x,o.y+=n.y<0?-i.y:i.y,this.panTo(this.unproject(o),e),this._enforcingBounds=!1),this},invalidateSize:function(t){if(!this._loaded)return this;t=l({animate:!1,pan:!0},!0===t?{animate:!0}:t);var e=this.getSize(),i=(this._sizeChanged=!0,this._lastCenter=null,this.getSize()),n=e.divideBy(2).round(),o=i.divideBy(2).round(),n=n.subtract(o);return n.x||n.y?(t.animate&&t.pan?this.panBy(n):(t.pan&&this._rawPanBy(n),this.fire("move"),t.debounceMoveend?(clearTimeout(this._sizeTimer),this._sizeTimer=setTimeout(a(this.fire,this,"moveend"),200)):this.fire("moveend")),this.fire("resize",{oldSize:e,newSize:i})):this},stop:function(){return this.setZoom(this._limitZoom(this._zoom)),this.options.zoomSnap||this.fire("viewreset"),this._stop()},locate:function(t){var e,i;return t=this._locateOptions=l({timeout:1e4,watch:!1},t),"geolocation"in navigator?(e=a(this._handleGeolocationResponse,this),i=a(this._handleGeolocationError,this),t.watch?this._locationWatchId=navigator.geolocation.watchPosition(e,i,t):navigator.geolocation.getCurrentPosition(e,i,t)):this._handleGeolocationError({code:0,message:"Geolocation not supported."}),this},stopLocate:function(){return navigator.geolocation&&navigator.geolocation.clearWatch&&navigator.geolocation.clearWatch(this._locationWatchId),this._locateOptions&&(this._locateOptions.setView=!1),this},_handleGeolocationError:function(t){var e;this._container._leaflet_id&&(e=t.code,t=t.message||(1===e?"permission denied":2===e?"position unavailable":"timeout"),this._locateOptions.setView&&!this._loaded&&this.fitWorld(),this.fire("locationerror",{code:e,message:"Geolocation error: "+t+"."}))},_handleGeolocationResponse:function(t){if(this._container._leaflet_id){var e,i,n=new v(t.coords.latitude,t.coords.longitude),o=n.toBounds(2*t.coords.accuracy),s=this._locateOptions,r=(s.setView&&(e=this.getBoundsZoom(o),this.setView(n,s.maxZoom?Math.min(e,s.maxZoom):e)),{latlng:n,bounds:o,timestamp:t.timestamp});for(i in t.coords)"number"==typeof t.coords[i]&&(r[i]=t.coords[i]);this.fire("locationfound",r)}},addHandler:function(t,e){return e&&(e=this[t]=new e(this),this._handlers.push(e),this.options[t]&&e.enable()),this},remove:function(){if(this._initEvents(!0),this.options.maxBounds&&this.off("moveend",this._panInsideMaxBounds),this._containerId!==this._container._leaflet_id)throw new Error("Map container is being reused by another instance");try{delete this._container._leaflet_id,delete this._containerId}catch(t){this._container._leaflet_id=void 0,this._containerId=void 0}for(var t in void 0!==this._locationWatchId&&this.stopLocate(),this._stop(),T(this._mapPane),this._clearControlPos&&this._clearControlPos(),this._resizeRequest&&(r(this._resizeRequest),this._resizeRequest=null),this._clearHandlers(),this._loaded&&this.fire("unload"),this._layers)this._layers[t].remove();for(t in this._panes)T(this._panes[t]);return this._layers=[],this._panes=[],delete this._mapPane,delete this._renderer,this},createPane:function(t,e){e=P("div","leaflet-pane"+(t?" leaflet-"+t.replace("Pane","")+"-pane":""),e||this._mapPane);return t&&(this._panes[t]=e),e},getCenter:function(){return this._checkIfLoaded(),this._lastCenter&&!this._moved()?this._lastCenter.clone():this.layerPointToLatLng(this._getCenterLayerPoint())},getZoom:function(){return this._zoom},getBounds:function(){var t=this.getPixelBounds();return new s(this.unproject(t.getBottomLeft()),this.unproject(t.getTopRight()))},getMinZoom:function(){return void 0===this.options.minZoom?this._layersMinZoom||0:this.options.minZoom},getMaxZoom:function(){return void 0===this.options.maxZoom?void 0===this._layersMaxZoom?1/0:this._layersMaxZoom:this.options.maxZoom},getBoundsZoom:function(t,e,i){t=g(t),i=m(i||[0,0]);var n=this.getZoom()||0,o=this.getMinZoom(),s=this.getMaxZoom(),r=t.getNorthWest(),t=t.getSouthEast(),i=this.getSize().subtract(i),t=_(this.project(t,n),this.project(r,n)).getSize(),r=b.any3d?this.options.zoomSnap:1,a=i.x/t.x,i=i.y/t.y,t=e?Math.max(a,i):Math.min(a,i),n=this.getScaleZoom(t,n);return r&&(n=Math.round(n/(r/100))*(r/100),n=e?Math.ceil(n/r)*r:Math.floor(n/r)*r),Math.max(o,Math.min(s,n))},getSize:function(){return this._size&&!this._sizeChanged||(this._size=new p(this._container.clientWidth||0,this._container.clientHeight||0),this._sizeChanged=!1),this._size.clone()},getPixelBounds:function(t,e){t=this._getTopLeftPoint(t,e);return new f(t,t.add(this.getSize()))},getPixelOrigin:function(){return this._checkIfLoaded(),this._pixelOrigin},getPixelWorldBounds:function(t){return this.options.crs.getProjectedBounds(void 0===t?this.getZoom():t)},getPane:function(t){return"string"==typeof t?this._panes[t]:t},getPanes:function(){return this._panes},getContainer:function(){return this._container},getZoomScale:function(t,e){var i=this.options.crs;return e=void 0===e?this._zoom:e,i.scale(t)/i.scale(e)},getScaleZoom:function(t,e){var i=this.options.crs,t=(e=void 0===e?this._zoom:e,i.zoom(t*i.scale(e)));return isNaN(t)?1/0:t},project:function(t,e){return e=void 0===e?this._zoom:e,this.options.crs.latLngToPoint(w(t),e)},unproject:function(t,e){return e=void 0===e?this._zoom:e,this.options.crs.pointToLatLng(m(t),e)},layerPointToLatLng:function(t){t=m(t).add(this.getPixelOrigin());return this.unproject(t)},latLngToLayerPoint:function(t){return this.project(w(t))._round()._subtract(this.getPixelOrigin())},wrapLatLng:function(t){return this.options.crs.wrapLatLng(w(t))},wrapLatLngBounds:function(t){return this.options.crs.wrapLatLngBounds(g(t))},distance:function(t,e){return this.options.crs.distance(w(t),w(e))},containerPointToLayerPoint:function(t){return m(t).subtract(this._getMapPanePos())},layerPointToContainerPoint:function(t){return m(t).add(this._getMapPanePos())},containerPointToLatLng:function(t){t=this.containerPointToLayerPoint(m(t));return this.layerPointToLatLng(t)},latLngToContainerPoint:function(t){return this.layerPointToContainerPoint(this.latLngToLayerPoint(w(t)))},mouseEventToContainerPoint:function(t){return De(t,this._container)},mouseEventToLayerPoint:function(t){return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(t))},mouseEventToLatLng:function(t){return this.layerPointToLatLng(this.mouseEventToLayerPoint(t))},_initContainer:function(t){t=this._container=_e(t);if(!t)throw new Error("Map container not found.");if(t._leaflet_id)throw new Error("Map container is already initialized.");S(t,"scroll",this._onScroll,this),this._containerId=h(t)},_initLayout:function(){var t=this._container,e=(this._fadeAnimated=this.options.fadeAnimation&&b.any3d,M(t,"leaflet-container"+(b.touch?" leaflet-touch":"")+(b.retina?" leaflet-retina":"")+(b.ielt9?" leaflet-oldie":"")+(b.safari?" leaflet-safari":"")+(this._fadeAnimated?" leaflet-fade-anim":"")),pe(t,"position"));"absolute"!==e&&"relative"!==e&&"fixed"!==e&&"sticky"!==e&&(t.style.position="relative"),this._initPanes(),this._initControlPos&&this._initControlPos()},_initPanes:function(){var t=this._panes={};this._paneRenderers={},this._mapPane=this.createPane("mapPane",this._container),Z(this._mapPane,new p(0,0)),this.createPane("tilePane"),this.createPane("overlayPane"),this.createPane("shadowPane"),this.createPane("markerPane"),this.createPane("tooltipPane"),this.createPane("popupPane"),this.options.markerZoomAnimation||(M(t.markerPane,"leaflet-zoom-hide"),M(t.shadowPane,"leaflet-zoom-hide"))},_resetView:function(t,e,i){Z(this._mapPane,new p(0,0));var n=!this._loaded,o=(this._loaded=!0,e=this._limitZoom(e),this.fire("viewprereset"),this._zoom!==e);this._moveStart(o,i)._move(t,e)._moveEnd(o),this.fire("viewreset"),n&&this.fire("load")},_moveStart:function(t,e){return t&&this.fire("zoomstart"),e||this.fire("movestart"),this},_move:function(t,e,i,n){void 0===e&&(e=this._zoom);var o=this._zoom!==e;return this._zoom=e,this._lastCenter=t,this._pixelOrigin=this._getNewPixelOrigin(t),n?i&&i.pinch&&this.fire("zoom",i):((o||i&&i.pinch)&&this.fire("zoom",i),this.fire("move",i)),this},_moveEnd:function(t){return t&&this.fire("zoomend"),this.fire("moveend")},_stop:function(){return r(this._flyToFrame),this._panAnim&&this._panAnim.stop(),this},_rawPanBy:function(t){Z(this._mapPane,this._getMapPanePos().subtract(t))},_getZoomSpan:function(){return this.getMaxZoom()-this.getMinZoom()},_panInsideMaxBounds:function(){this._enforcingBounds||this.panInsideBounds(this.options.maxBounds)},_checkIfLoaded:function(){if(!this._loaded)throw new Error("Set map center and zoom first.")},_initEvents:function(t){this._targets={};var e=t?k:S;e((this._targets[h(this._container)]=this)._container,"click dblclick mousedown mouseup mouseover mouseout mousemove contextmenu keypress keydown keyup",this._handleDOMEvent,this),this.options.trackResize&&e(window,"resize",this._onResize,this),b.any3d&&this.options.transform3DLimit&&(t?this.off:this.on).call(this,"moveend",this._onMoveEnd)},_onResize:function(){r(this._resizeRequest),this._resizeRequest=x(function(){this.invalidateSize({debounceMoveend:!0})},this)},_onScroll:function(){this._container.scrollTop=0,this._container.scrollLeft=0},_onMoveEnd:function(){var t=this._getMapPanePos();Math.max(Math.abs(t.x),Math.abs(t.y))>=this.options.transform3DLimit&&this._resetView(this.getCenter(),this.getZoom())},_findEventTargets:function(t,e){for(var i,n=[],o="mouseout"===e||"mouseover"===e,s=t.target||t.srcElement,r=!1;s;){if((i=this._targets[h(s)])&&("click"===e||"preclick"===e)&&this._draggableMoved(i)){r=!0;break}if(i&&i.listens(e,!0)){if(o&&!We(s,t))break;if(n.push(i),o)break}if(s===this._container)break;s=s.parentNode}return n=n.length||r||o||!this.listens(e,!0)?n:[this]},_isClickDisabled:function(t){for(;t&&t!==this._container;){if(t._leaflet_disable_click)return!0;t=t.parentNode}},_handleDOMEvent:function(t){var e,i=t.target||t.srcElement;!this._loaded||i._leaflet_disable_events||"click"===t.type&&this._isClickDisabled(i)||("mousedown"===(e=t.type)&&Me(i),this._fireDOMEvent(t,e))},_mouseEvents:["click","dblclick","mouseover","mouseout","contextmenu"],_fireDOMEvent:function(t,e,i){"click"===t.type&&((a=l({},t)).type="preclick",this._fireDOMEvent(a,a.type,i));var n=this._findEventTargets(t,e);if(i){for(var o=[],s=0;sthis.options.zoomAnimationThreshold)return!1;var n=this.getZoomScale(e),n=this._getCenterOffset(t)._divideBy(1-1/n);if(!0!==i.animate&&!this.getSize().contains(n))return!1;x(function(){this._moveStart(!0,i.noMoveStart||!1)._animateZoom(t,e,!0)},this)}return!0},_animateZoom:function(t,e,i,n){this._mapPane&&(i&&(this._animatingZoom=!0,this._animateToCenter=t,this._animateToZoom=e,M(this._mapPane,"leaflet-zoom-anim")),this.fire("zoomanim",{center:t,zoom:e,noUpdate:n}),this._tempFireZoomEvent||(this._tempFireZoomEvent=this._zoom!==this._animateToZoom),this._move(this._animateToCenter,this._animateToZoom,void 0,!0),setTimeout(a(this._onZoomTransitionEnd,this),250))},_onZoomTransitionEnd:function(){this._animatingZoom&&(this._mapPane&&z(this._mapPane,"leaflet-zoom-anim"),this._animatingZoom=!1,this._move(this._animateToCenter,this._animateToZoom,void 0,!0),this._tempFireZoomEvent&&this.fire("zoom"),delete this._tempFireZoomEvent,this.fire("move"),this._moveEnd(!0))}});function Ue(t){return new B(t)}var B=et.extend({options:{position:"topright"},initialize:function(t){c(this,t)},getPosition:function(){return this.options.position},setPosition:function(t){var e=this._map;return e&&e.removeControl(this),this.options.position=t,e&&e.addControl(this),this},getContainer:function(){return this._container},addTo:function(t){this.remove(),this._map=t;var e=this._container=this.onAdd(t),i=this.getPosition(),t=t._controlCorners[i];return M(e,"leaflet-control"),-1!==i.indexOf("bottom")?t.insertBefore(e,t.firstChild):t.appendChild(e),this._map.on("unload",this.remove,this),this},remove:function(){return this._map&&(T(this._container),this.onRemove&&this.onRemove(this._map),this._map.off("unload",this.remove,this),this._map=null),this},_refocusOnMap:function(t){this._map&&t&&0",e=document.createElement("div");return e.innerHTML=t,e.firstChild},_addItem:function(t){var e,i=document.createElement("label"),n=this._map.hasLayer(t.layer),n=(t.overlay?((e=document.createElement("input")).type="checkbox",e.className="leaflet-control-layers-selector",e.defaultChecked=n):e=this._createRadioElement("leaflet-base-layers_"+h(this),n),this._layerControlInputs.push(e),e.layerId=h(t.layer),S(e,"click",this._onInputClick,this),document.createElement("span")),o=(n.innerHTML=" "+t.name,document.createElement("span"));return i.appendChild(o),o.appendChild(e),o.appendChild(n),(t.overlay?this._overlaysList:this._baseLayersList).appendChild(i),this._checkDisabledLayers(),i},_onInputClick:function(){if(!this._preventClick){var t,e,i=this._layerControlInputs,n=[],o=[];this._handlingClick=!0;for(var s=i.length-1;0<=s;s--)t=i[s],e=this._getLayer(t.layerId).layer,t.checked?n.push(e):t.checked||o.push(e);for(s=0;se.options.maxZoom},_expandIfNotCollapsed:function(){return this._map&&!this.options.collapsed&&this.expand(),this},_expandSafely:function(){var t=this._section,e=(this._preventClick=!0,S(t,"click",O),this.expand(),this);setTimeout(function(){k(t,"click",O),e._preventClick=!1})}})),qe=B.extend({options:{position:"topleft",zoomInText:'',zoomInTitle:"Zoom in",zoomOutText:'',zoomOutTitle:"Zoom out"},onAdd:function(t){var e="leaflet-control-zoom",i=P("div",e+" leaflet-bar"),n=this.options;return this._zoomInButton=this._createButton(n.zoomInText,n.zoomInTitle,e+"-in",i,this._zoomIn),this._zoomOutButton=this._createButton(n.zoomOutText,n.zoomOutTitle,e+"-out",i,this._zoomOut),this._updateDisabled(),t.on("zoomend zoomlevelschange",this._updateDisabled,this),i},onRemove:function(t){t.off("zoomend zoomlevelschange",this._updateDisabled,this)},disable:function(){return this._disabled=!0,this._updateDisabled(),this},enable:function(){return this._disabled=!1,this._updateDisabled(),this},_zoomIn:function(t){!this._disabled&&this._map._zoomthis._map.getMinZoom()&&this._map.zoomOut(this._map.options.zoomDelta*(t.shiftKey?3:1))},_createButton:function(t,e,i,n,o){i=P("a",i,n);return i.innerHTML=t,i.href="#",i.title=e,i.setAttribute("role","button"),i.setAttribute("aria-label",e),Ie(i),S(i,"click",Re),S(i,"click",o,this),S(i,"click",this._refocusOnMap,this),i},_updateDisabled:function(){var t=this._map,e="leaflet-disabled";z(this._zoomInButton,e),z(this._zoomOutButton,e),this._zoomInButton.setAttribute("aria-disabled","false"),this._zoomOutButton.setAttribute("aria-disabled","false"),!this._disabled&&t._zoom!==t.getMinZoom()||(M(this._zoomOutButton,e),this._zoomOutButton.setAttribute("aria-disabled","true")),!this._disabled&&t._zoom!==t.getMaxZoom()||(M(this._zoomInButton,e),this._zoomInButton.setAttribute("aria-disabled","true"))}}),Ge=(A.mergeOptions({zoomControl:!0}),A.addInitHook(function(){this.options.zoomControl&&(this.zoomControl=new qe,this.addControl(this.zoomControl))}),B.extend({options:{position:"bottomleft",maxWidth:100,metric:!0,imperial:!0},onAdd:function(t){var e="leaflet-control-scale",i=P("div",e),n=this.options;return this._addScales(n,e+"-line",i),t.on(n.updateWhenIdle?"moveend":"move",this._update,this),t.whenReady(this._update,this),i},onRemove:function(t){t.off(this.options.updateWhenIdle?"moveend":"move",this._update,this)},_addScales:function(t,e,i){t.metric&&(this._mScale=P("div",e,i)),t.imperial&&(this._iScale=P("div",e,i))},_update:function(){var t=this._map,e=t.getSize().y/2,t=t.distance(t.containerPointToLatLng([0,e]),t.containerPointToLatLng([this.options.maxWidth,e]));this._updateScales(t)},_updateScales:function(t){this.options.metric&&t&&this._updateMetric(t),this.options.imperial&&t&&this._updateImperial(t)},_updateMetric:function(t){var e=this._getRoundNum(t);this._updateScale(this._mScale,e<1e3?e+" m":e/1e3+" km",e/t)},_updateImperial:function(t){var e,i,t=3.2808399*t;5280'+(b.inlineSvg?' ':"")+"Leaflet"},initialize:function(t){c(this,t),this._attributions={}},onAdd:function(t){for(var e in(t.attributionControl=this)._container=P("div","leaflet-control-attribution"),Ie(this._container),t._layers)t._layers[e].getAttribution&&this.addAttribution(t._layers[e].getAttribution());return this._update(),t.on("layeradd",this._addAttribution,this),this._container},onRemove:function(t){t.off("layeradd",this._addAttribution,this)},_addAttribution:function(t){t.layer.getAttribution&&(this.addAttribution(t.layer.getAttribution()),t.layer.once("remove",function(){this.removeAttribution(t.layer.getAttribution())},this))},setPrefix:function(t){return this.options.prefix=t,this._update(),this},addAttribution:function(t){return t&&(this._attributions[t]||(this._attributions[t]=0),this._attributions[t]++,this._update()),this},removeAttribution:function(t){return t&&this._attributions[t]&&(this._attributions[t]--,this._update()),this},_update:function(){if(this._map){var t,e=[];for(t in this._attributions)this._attributions[t]&&e.push(t);var i=[];this.options.prefix&&i.push(this.options.prefix),e.length&&i.push(e.join(", ")),this._container.innerHTML=i.join(' ')}}}),n=(A.mergeOptions({attributionControl:!0}),A.addInitHook(function(){this.options.attributionControl&&(new Ke).addTo(this)}),B.Layers=Ve,B.Zoom=qe,B.Scale=Ge,B.Attribution=Ke,Ue.layers=function(t,e,i){return new Ve(t,e,i)},Ue.zoom=function(t){return new qe(t)},Ue.scale=function(t){return new Ge(t)},Ue.attribution=function(t){return new Ke(t)},et.extend({initialize:function(t){this._map=t},enable:function(){return this._enabled||(this._enabled=!0,this.addHooks()),this},disable:function(){return this._enabled&&(this._enabled=!1,this.removeHooks()),this},enabled:function(){return!!this._enabled}})),ft=(n.addTo=function(t,e){return t.addHandler(e,this),this},{Events:e}),Ye=b.touch?"touchstart mousedown":"mousedown",Xe=it.extend({options:{clickTolerance:3},initialize:function(t,e,i,n){c(this,n),this._element=t,this._dragStartTarget=e||t,this._preventOutline=i},enable:function(){this._enabled||(S(this._dragStartTarget,Ye,this._onDown,this),this._enabled=!0)},disable:function(){this._enabled&&(Xe._dragging===this&&this.finishDrag(!0),k(this._dragStartTarget,Ye,this._onDown,this),this._enabled=!1,this._moved=!1)},_onDown:function(t){var e,i;this._enabled&&(this._moved=!1,ve(this._element,"leaflet-zoom-anim")||(t.touches&&1!==t.touches.length?Xe._dragging===this&&this.finishDrag():Xe._dragging||t.shiftKey||1!==t.which&&1!==t.button&&!t.touches||((Xe._dragging=this)._preventOutline&&Me(this._element),Le(),re(),this._moving||(this.fire("down"),i=t.touches?t.touches[0]:t,e=Ce(this._element),this._startPoint=new p(i.clientX,i.clientY),this._startPos=Pe(this._element),this._parentScale=Ze(e),i="mousedown"===t.type,S(document,i?"mousemove":"touchmove",this._onMove,this),S(document,i?"mouseup":"touchend touchcancel",this._onUp,this)))))},_onMove:function(t){var e;this._enabled&&(t.touches&&1e&&(i.push(t[n]),o=n);oe.max.x&&(i|=2),t.ye.max.y&&(i|=8),i}function ri(t,e,i,n){var o=e.x,e=e.y,s=i.x-o,r=i.y-e,a=s*s+r*r;return 0this._layersMaxZoom&&this.setZoom(this._layersMaxZoom),void 0===this.options.minZoom&&this._layersMinZoom&&this.getZoom()t.y!=n.y>t.y&&t.x<(n.x-i.x)*(t.y-i.y)/(n.y-i.y)+i.x&&(l=!l);return l||yi.prototype._containsPoint.call(this,t,!0)}});var wi=ci.extend({initialize:function(t,e){c(this,e),this._layers={},t&&this.addData(t)},addData:function(t){var e,i,n,o=d(t)?t:t.features;if(o){for(e=0,i=o.length;es.x&&(r=i.x+a-s.x+o.x),i.x-r-n.x<(a=0)&&(r=i.x-n.x),i.y+e+o.y>s.y&&(a=i.y+e-s.y+o.y),i.y-a-n.y<0&&(a=i.y-n.y),(r||a)&&(this.options.keepInView&&(this._autopanning=!0),t.fire("autopanstart").panBy([r,a]))))},_getAnchor:function(){return m(this._source&&this._source._getPopupAnchor?this._source._getPopupAnchor():[0,0])}})),Ii=(A.mergeOptions({closePopupOnClick:!0}),A.include({openPopup:function(t,e,i){return this._initOverlay(Bi,t,e,i).openOn(this),this},closePopup:function(t){return(t=arguments.length?t:this._popup)&&t.close(),this}}),o.include({bindPopup:function(t,e){return this._popup=this._initOverlay(Bi,this._popup,t,e),this._popupHandlersAdded||(this.on({click:this._openPopup,keypress:this._onKeyPress,remove:this.closePopup,move:this._movePopup}),this._popupHandlersAdded=!0),this},unbindPopup:function(){return this._popup&&(this.off({click:this._openPopup,keypress:this._onKeyPress,remove:this.closePopup,move:this._movePopup}),this._popupHandlersAdded=!1,this._popup=null),this},openPopup:function(t){return this._popup&&(this instanceof ci||(this._popup._source=this),this._popup._prepareOpen(t||this._latlng)&&this._popup.openOn(this._map)),this},closePopup:function(){return this._popup&&this._popup.close(),this},togglePopup:function(){return this._popup&&this._popup.toggle(this),this},isPopupOpen:function(){return!!this._popup&&this._popup.isOpen()},setPopupContent:function(t){return this._popup&&this._popup.setContent(t),this},getPopup:function(){return this._popup},_openPopup:function(t){var e;this._popup&&this._map&&(Re(t),e=t.layer||t.target,this._popup._source!==e||e instanceof fi?(this._popup._source=e,this.openPopup(t.latlng)):this._map.hasLayer(this._popup)?this.closePopup():this.openPopup(t.latlng))},_movePopup:function(t){this._popup.setLatLng(t.latlng)},_onKeyPress:function(t){13===t.originalEvent.keyCode&&this._openPopup(t)}}),Ai.extend({options:{pane:"tooltipPane",offset:[0,0],direction:"auto",permanent:!1,sticky:!1,opacity:.9},onAdd:function(t){Ai.prototype.onAdd.call(this,t),this.setOpacity(this.options.opacity),t.fire("tooltipopen",{tooltip:this}),this._source&&(this.addEventParent(this._source),this._source.fire("tooltipopen",{tooltip:this},!0))},onRemove:function(t){Ai.prototype.onRemove.call(this,t),t.fire("tooltipclose",{tooltip:this}),this._source&&(this.removeEventParent(this._source),this._source.fire("tooltipclose",{tooltip:this},!0))},getEvents:function(){var t=Ai.prototype.getEvents.call(this);return this.options.permanent||(t.preclick=this.close),t},_initLayout:function(){var t="leaflet-tooltip "+(this.options.className||"")+" leaflet-zoom-"+(this._zoomAnimated?"animated":"hide");this._contentNode=this._container=P("div",t),this._container.setAttribute("role","tooltip"),this._container.setAttribute("id","leaflet-tooltip-"+h(this))},_updateLayout:function(){},_adjustPan:function(){},_setPosition:function(t){var e,i=this._map,n=this._container,o=i.latLngToContainerPoint(i.getCenter()),i=i.layerPointToContainerPoint(t),s=this.options.direction,r=n.offsetWidth,a=n.offsetHeight,h=m(this.options.offset),l=this._getAnchor(),i="top"===s?(e=r/2,a):"bottom"===s?(e=r/2,0):(e="center"===s?r/2:"right"===s?0:"left"===s?r:i.xthis.options.maxZoom||nthis.options.maxZoom||void 0!==this.options.minZoom&&oi.max.x)||!e.wrapLat&&(t.yi.max.y))return!1}return!this.options.bounds||(e=this._tileCoordsToBounds(t),g(this.options.bounds).overlaps(e))},_keyToBounds:function(t){return this._tileCoordsToBounds(this._keyToTileCoords(t))},_tileCoordsToNwSe:function(t){var e=this._map,i=this.getTileSize(),n=t.scaleBy(i),i=n.add(i);return[e.unproject(n,t.z),e.unproject(i,t.z)]},_tileCoordsToBounds:function(t){t=this._tileCoordsToNwSe(t),t=new s(t[0],t[1]);return t=this.options.noWrap?t:this._map.wrapLatLngBounds(t)},_tileCoordsToKey:function(t){return t.x+":"+t.y+":"+t.z},_keyToTileCoords:function(t){var t=t.split(":"),e=new p(+t[0],+t[1]);return e.z=+t[2],e},_removeTile:function(t){var e=this._tiles[t];e&&(T(e.el),delete this._tiles[t],this.fire("tileunload",{tile:e.el,coords:this._keyToTileCoords(t)}))},_initTile:function(t){M(t,"leaflet-tile");var e=this.getTileSize();t.style.width=e.x+"px",t.style.height=e.y+"px",t.onselectstart=u,t.onmousemove=u,b.ielt9&&this.options.opacity<1&&C(t,this.options.opacity)},_addTile:function(t,e){var i=this._getTilePos(t),n=this._tileCoordsToKey(t),o=this.createTile(this._wrapCoords(t),a(this._tileReady,this,t));this._initTile(o),this.createTile.length<2&&x(a(this._tileReady,this,t,null,o)),Z(o,i),this._tiles[n]={el:o,coords:t,current:!0},e.appendChild(o),this.fire("tileloadstart",{tile:o,coords:t})},_tileReady:function(t,e,i){e&&this.fire("tileerror",{error:e,tile:i,coords:t});var n=this._tileCoordsToKey(t);(i=this._tiles[n])&&(i.loaded=+new Date,this._map._fadeAnimated?(C(i.el,0),r(this._fadeFrame),this._fadeFrame=x(this._updateOpacity,this)):(i.active=!0,this._pruneTiles()),e||(M(i.el,"leaflet-tile-loaded"),this.fire("tileload",{tile:i.el,coords:t})),this._noTilesToLoad()&&(this._loading=!1,this.fire("load"),b.ielt9||!this._map._fadeAnimated?x(this._pruneTiles,this):setTimeout(a(this._pruneTiles,this),250)))},_getTilePos:function(t){return t.scaleBy(this.getTileSize()).subtract(this._level.origin)},_wrapCoords:function(t){var e=new p(this._wrapX?H(t.x,this._wrapX):t.x,this._wrapY?H(t.y,this._wrapY):t.y);return e.z=t.z,e},_pxBoundsToTileRange:function(t){var e=this.getTileSize();return new f(t.min.unscaleBy(e).floor(),t.max.unscaleBy(e).ceil().subtract([1,1]))},_noTilesToLoad:function(){for(var t in this._tiles)if(!this._tiles[t].loaded)return!1;return!0}});var Di=Ni.extend({options:{minZoom:0,maxZoom:18,subdomains:"abc",errorTileUrl:"",zoomOffset:0,tms:!1,zoomReverse:!1,detectRetina:!1,crossOrigin:!1,referrerPolicy:!1},initialize:function(t,e){this._url=t,(e=c(this,e)).detectRetina&&b.retina&&0')}}catch(t){}return function(t){return document.createElement("<"+t+' xmlns="urn:schemas-microsoft.com:vml" class="lvml">')}}(),zt={_initContainer:function(){this._container=P("div","leaflet-vml-container")},_update:function(){this._map._animatingZoom||(Wi.prototype._update.call(this),this.fire("update"))},_initPath:function(t){var e=t._container=Vi("shape");M(e,"leaflet-vml-shape "+(this.options.className||"")),e.coordsize="1 1",t._path=Vi("path"),e.appendChild(t._path),this._updateStyle(t),this._layers[h(t)]=t},_addPath:function(t){var e=t._container;this._container.appendChild(e),t.options.interactive&&t.addInteractiveTarget(e)},_removePath:function(t){var e=t._container;T(e),t.removeInteractiveTarget(e),delete this._layers[h(t)]},_updateStyle:function(t){var e=t._stroke,i=t._fill,n=t.options,o=t._container;o.stroked=!!n.stroke,o.filled=!!n.fill,n.stroke?(e=e||(t._stroke=Vi("stroke")),o.appendChild(e),e.weight=n.weight+"px",e.color=n.color,e.opacity=n.opacity,n.dashArray?e.dashStyle=d(n.dashArray)?n.dashArray.join(" "):n.dashArray.replace(/( *, *)/g," "):e.dashStyle="",e.endcap=n.lineCap.replace("butt","flat"),e.joinstyle=n.lineJoin):e&&(o.removeChild(e),t._stroke=null),n.fill?(i=i||(t._fill=Vi("fill")),o.appendChild(i),i.color=n.fillColor||n.color,i.opacity=n.fillOpacity):i&&(o.removeChild(i),t._fill=null)},_updateCircle:function(t){var e=t._point.round(),i=Math.round(t._radius),n=Math.round(t._radiusY||i);this._setPath(t,t._empty()?"M0 0":"AL "+e.x+","+e.y+" "+i+","+n+" 0,23592600")},_setPath:function(t,e){t._path.v=e},_bringToFront:function(t){fe(t._container)},_bringToBack:function(t){ge(t._container)}},qi=b.vml?Vi:ct,Gi=Wi.extend({_initContainer:function(){this._container=qi("svg"),this._container.setAttribute("pointer-events","none"),this._rootGroup=qi("g"),this._container.appendChild(this._rootGroup)},_destroyContainer:function(){T(this._container),k(this._container),delete this._container,delete this._rootGroup,delete this._svgSize},_update:function(){var t,e,i;this._map._animatingZoom&&this._bounds||(Wi.prototype._update.call(this),e=(t=this._bounds).getSize(),i=this._container,this._svgSize&&this._svgSize.equals(e)||(this._svgSize=e,i.setAttribute("width",e.x),i.setAttribute("height",e.y)),Z(i,t.min),i.setAttribute("viewBox",[t.min.x,t.min.y,e.x,e.y].join(" ")),this.fire("update"))},_initPath:function(t){var e=t._path=qi("path");t.options.className&&M(e,t.options.className),t.options.interactive&&M(e,"leaflet-interactive"),this._updateStyle(t),this._layers[h(t)]=t},_addPath:function(t){this._rootGroup||this._initContainer(),this._rootGroup.appendChild(t._path),t.addInteractiveTarget(t._path)},_removePath:function(t){T(t._path),t.removeInteractiveTarget(t._path),delete this._layers[h(t)]},_updatePath:function(t){t._project(),t._update()},_updateStyle:function(t){var e=t._path,t=t.options;e&&(t.stroke?(e.setAttribute("stroke",t.color),e.setAttribute("stroke-opacity",t.opacity),e.setAttribute("stroke-width",t.weight),e.setAttribute("stroke-linecap",t.lineCap),e.setAttribute("stroke-linejoin",t.lineJoin),t.dashArray?e.setAttribute("stroke-dasharray",t.dashArray):e.removeAttribute("stroke-dasharray"),t.dashOffset?e.setAttribute("stroke-dashoffset",t.dashOffset):e.removeAttribute("stroke-dashoffset")):e.setAttribute("stroke","none"),t.fill?(e.setAttribute("fill",t.fillColor||t.color),e.setAttribute("fill-opacity",t.fillOpacity),e.setAttribute("fill-rule",t.fillRule||"evenodd")):e.setAttribute("fill","none"))},_updatePoly:function(t,e){this._setPath(t,dt(t._parts,e))},_updateCircle:function(t){var e=t._point,i=Math.max(Math.round(t._radius),1),n="a"+i+","+(Math.max(Math.round(t._radiusY),1)||i)+" 0 1,0 ",e=t._empty()?"M0 0":"M"+(e.x-i)+","+e.y+n+2*i+",0 "+n+2*-i+",0 ";this._setPath(t,e)},_setPath:function(t,e){t._path.setAttribute("d",e)},_bringToFront:function(t){fe(t._path)},_bringToBack:function(t){ge(t._path)}});function Ki(t){return b.svg||b.vml?new Gi(t):null}b.vml&&Gi.include(zt),A.include({getRenderer:function(t){t=(t=t.options.renderer||this._getPaneRenderer(t.options.pane)||this.options.renderer||this._renderer)||(this._renderer=this._createRenderer());return this.hasLayer(t)||this.addLayer(t),t},_getPaneRenderer:function(t){var e;return"overlayPane"!==t&&void 0!==t&&(void 0===(e=this._paneRenderers[t])&&(e=this._createRenderer({pane:t}),this._paneRenderers[t]=e),e)},_createRenderer:function(t){return this.options.preferCanvas&&Ui(t)||Ki(t)}});var Yi=xi.extend({initialize:function(t,e){xi.prototype.initialize.call(this,this._boundsToLatLngs(t),e)},setBounds:function(t){return this.setLatLngs(this._boundsToLatLngs(t))},_boundsToLatLngs:function(t){return[(t=g(t)).getSouthWest(),t.getNorthWest(),t.getNorthEast(),t.getSouthEast()]}});Gi.create=qi,Gi.pointsToPath=dt,wi.geometryToLayer=bi,wi.coordsToLatLng=Li,wi.coordsToLatLngs=Ti,wi.latLngToCoords=Mi,wi.latLngsToCoords=zi,wi.getFeature=Ci,wi.asFeature=Zi,A.mergeOptions({boxZoom:!0});var _t=n.extend({initialize:function(t){this._map=t,this._container=t._container,this._pane=t._panes.overlayPane,this._resetStateTimeout=0,t.on("unload",this._destroy,this)},addHooks:function(){S(this._container,"mousedown",this._onMouseDown,this)},removeHooks:function(){k(this._container,"mousedown",this._onMouseDown,this)},moved:function(){return this._moved},_destroy:function(){T(this._pane),delete this._pane},_resetState:function(){this._resetStateTimeout=0,this._moved=!1},_clearDeferredResetState:function(){0!==this._resetStateTimeout&&(clearTimeout(this._resetStateTimeout),this._resetStateTimeout=0)},_onMouseDown:function(t){if(!t.shiftKey||1!==t.which&&1!==t.button)return!1;this._clearDeferredResetState(),this._resetState(),re(),Le(),this._startPoint=this._map.mouseEventToContainerPoint(t),S(document,{contextmenu:Re,mousemove:this._onMouseMove,mouseup:this._onMouseUp,keydown:this._onKeyDown},this)},_onMouseMove:function(t){this._moved||(this._moved=!0,this._box=P("div","leaflet-zoom-box",this._container),M(this._container,"leaflet-crosshair"),this._map.fire("boxzoomstart")),this._point=this._map.mouseEventToContainerPoint(t);var t=new f(this._point,this._startPoint),e=t.getSize();Z(this._box,t.min),this._box.style.width=e.x+"px",this._box.style.height=e.y+"px"},_finish:function(){this._moved&&(T(this._box),z(this._container,"leaflet-crosshair")),ae(),Te(),k(document,{contextmenu:Re,mousemove:this._onMouseMove,mouseup:this._onMouseUp,keydown:this._onKeyDown},this)},_onMouseUp:function(t){1!==t.which&&1!==t.button||(this._finish(),this._moved&&(this._clearDeferredResetState(),this._resetStateTimeout=setTimeout(a(this._resetState,this),0),t=new s(this._map.containerPointToLatLng(this._startPoint),this._map.containerPointToLatLng(this._point)),this._map.fitBounds(t).fire("boxzoomend",{boxZoomBounds:t})))},_onKeyDown:function(t){27===t.keyCode&&(this._finish(),this._clearDeferredResetState(),this._resetState())}}),Ct=(A.addInitHook("addHandler","boxZoom",_t),A.mergeOptions({doubleClickZoom:!0}),n.extend({addHooks:function(){this._map.on("dblclick",this._onDoubleClick,this)},removeHooks:function(){this._map.off("dblclick",this._onDoubleClick,this)},_onDoubleClick:function(t){var e=this._map,i=e.getZoom(),n=e.options.zoomDelta,i=t.originalEvent.shiftKey?i-n:i+n;"center"===e.options.doubleClickZoom?e.setZoom(i):e.setZoomAround(t.containerPoint,i)}})),Zt=(A.addInitHook("addHandler","doubleClickZoom",Ct),A.mergeOptions({dragging:!0,inertia:!0,inertiaDeceleration:3400,inertiaMaxSpeed:1/0,easeLinearity:.2,worldCopyJump:!1,maxBoundsViscosity:0}),n.extend({addHooks:function(){var t;this._draggable||(t=this._map,this._draggable=new Xe(t._mapPane,t._container),this._draggable.on({dragstart:this._onDragStart,drag:this._onDrag,dragend:this._onDragEnd},this),this._draggable.on("predrag",this._onPreDragLimit,this),t.options.worldCopyJump&&(this._draggable.on("predrag",this._onPreDragWrap,this),t.on("zoomend",this._onZoomEnd,this),t.whenReady(this._onZoomEnd,this))),M(this._map._container,"leaflet-grab leaflet-touch-drag"),this._draggable.enable(),this._positions=[],this._times=[]},removeHooks:function(){z(this._map._container,"leaflet-grab"),z(this._map._container,"leaflet-touch-drag"),this._draggable.disable()},moved:function(){return this._draggable&&this._draggable._moved},moving:function(){return this._draggable&&this._draggable._moving},_onDragStart:function(){var t,e=this._map;e._stop(),this._map.options.maxBounds&&this._map.options.maxBoundsViscosity?(t=g(this._map.options.maxBounds),this._offsetLimit=_(this._map.latLngToContainerPoint(t.getNorthWest()).multiplyBy(-1),this._map.latLngToContainerPoint(t.getSouthEast()).multiplyBy(-1).add(this._map.getSize())),this._viscosity=Math.min(1,Math.max(0,this._map.options.maxBoundsViscosity))):this._offsetLimit=null,e.fire("movestart").fire("dragstart"),e.options.inertia&&(this._positions=[],this._times=[])},_onDrag:function(t){var e,i;this._map.options.inertia&&(e=this._lastTime=+new Date,i=this._lastPos=this._draggable._absPos||this._draggable._newPos,this._positions.push(i),this._times.push(e),this._prunePositions(e)),this._map.fire("move",t).fire("drag",t)},_prunePositions:function(t){for(;1e.max.x&&(t.x=this._viscousLimit(t.x,e.max.x)),t.y>e.max.y&&(t.y=this._viscousLimit(t.y,e.max.y)),this._draggable._newPos=this._draggable._startPos.add(t))},_onPreDragWrap:function(){var t=this._worldWidth,e=Math.round(t/2),i=this._initialWorldOffset,n=this._draggable._newPos.x,o=(n-e+i)%t+e-i,n=(n+e+i)%t-e-i,t=Math.abs(o+i)e.getMaxZoom()&&1 { + 'use strict'; + + const STATUS_LABELS = { sent: 'Sent', failed: 'Failed', dropped: 'Dropped on device', offline: 'Offline' }; + const SHORT_STATUS_LABELS = { sent: 'Sent', failed: 'Failed', dropped: 'Dropped', offline: 'Offline' }; + const STATUS_COLOR_TOKENS = { sent: '--success', failed: '--error', dropped: '--warn', offline: '--muted' }; + const TILE_URL = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'; + const MAX_LIST_ROWS = 2000; + const MAX_GAP_LABELS = 400; + const AUTO_REFRESH_MS = 10000; + const FOCUS_ZOOM = 17; + const EARTH_RADIUS_METERS = 6371000; + + const $ = (id) => document.getElementById(id); + + let dashboard = null; + let controlsBound = false; + let overview = null; + let detail = null; + let selectedStream = ''; + let selectedFile = ''; + let statusFilter = 'all'; + let appStateFilter = 'all'; + let selectedIndex = -1; + let openPoint = null; + let fittedTrackKey = ''; + let autoRefreshTimer = null; + + let map = null; + let routeLayer = null; + let pointLayer = null; + let labelLayer = null; + const markersByIndex = new Map(); + + async function load(context) { + dashboard = context; + bindOnce(); + ensureMap(); + requestAnimationFrame(() => map?.invalidateSize()); + await refresh(); + } + + async function refresh() { + if (!dashboard.hasSession()) { + overview = null; + detail = null; + renderOverview(); + renderTrack(); + return; + } + const response = await fetch('/api/v1/location-pings', { headers: dashboard.auth() }); + if (!response.ok) { + overview = null; + detail = null; + renderOverview(); + renderTrack(response.status === 403 ? 'Network capture is disabled for this app run.' : 'Location pings unavailable: ' + response.status); + return; + } + overview = await response.json(); + renderOverview(); + await loadSelectedTrack(); + } + + async function loadSelectedTrack() { + if (!selectedFile) { + detail = null; + renderTrack(); + return; + } + const query = new URLSearchParams({ stream: selectedStream, file: selectedFile }); + const response = await fetch('/api/v1/location-pings/track?' + query, { headers: dashboard.auth() }); + detail = response.ok ? await response.json() : null; + renderTrack(); + } + + function renderOverview() { + const tracks = overview?.tracks || []; + const streams = overview?.streams || []; + dashboard.setNavCount(tracks.length); + $('lpBadge').textContent = badgeText(); + renderStreamSwitches(streams); + chooseSelection(streams, tracks); + renderStreamPicker(streams, tracks); + renderTrackPicker(tracks); + const schema = overview?.schema || {}; + $('lpTrackLabel').textContent = schema.groupLabel || 'Group'; + $('lpFixGapsToggle').hidden = !schema.hasFixTime; + $('lpFixGapHead').hidden = !schema.hasFixTime; + $('lpAppStateGroup').hidden = !schema.hasAppState; + $('lpDeleteTrack').disabled = !selectedFile; + $('lpDeleteAll').disabled = tracks.length === 0; + const storageError = overview?.storage?.lastError; + showNote(storageError || ''); + } + + function badgeText() { + if (!overview) return ''; + if (!overview.configured) return 'not configured'; + const count = overview.tracks.length; + const storage = overview.storage; + return count + ' track' + (count === 1 ? '' : 's') + ' · ' + formatBytes(storage.usedBytes) + ' of ' + formatBytes(storage.maxBytes); + } + + function renderStreamSwitches(streams) { + const container = $('lpStreams'); + if (!streams.length) { + container.innerHTML = ''; + return; + } + container.innerHTML = 'Recording' + streams.map((stream) => + ``, + ).join(''); + } + + function chooseSelection(streams, tracks) { + const streamNames = availableStreamNames(streams, tracks); + if (!streamNames.includes(selectedStream)) { + selectedStream = tracks[0]?.stream || streamNames[0] || ''; + } + const streamTracks = tracks.filter((track) => track.stream === selectedStream); + if (!streamTracks.some((track) => track.file === selectedFile)) { + selectedFile = streamTracks[0]?.file || ''; + } + } + + function availableStreamNames(streams, tracks) { + const names = streams.map((stream) => stream.name); + tracks.forEach((track) => { if (!names.includes(track.stream)) names.push(track.stream); }); + return names; + } + + function renderStreamPicker(streams, tracks) { + const names = availableStreamNames(streams, tracks); + $('lpStream').innerHTML = names.map((name) => { + const count = tracks.filter((track) => track.stream === name).length; + return ``; + }).join(''); + $('lpStream').disabled = names.length === 0; + } + + function renderTrackPicker(tracks) { + const streamTracks = tracks.filter((track) => track.stream === selectedStream); + $('lpTrack').innerHTML = streamTracks.length + ? streamTracks.map((track) => + ``, + ).join('') + : ''; + $('lpTrack').disabled = streamTracks.length === 0; + } + + function filteredPoints() { + const points = detail?.points || []; + return points.filter((point) => + (statusFilter === 'all' || point.status === statusFilter) && + (appStateFilter === 'all' || appStateOf(point) === appStateFilter)); + } + + function appStateOf(point) { + const value = (point.appState || '').toLowerCase(); + if (value.includes('fore')) return 'foreground'; + if (value.includes('back')) return 'background'; + return value; + } + + function renderTrack(problem) { + const points = filteredPoints(); + renderEmptyState(problem, points); + renderMap(points); + renderList(points); + renderMetrics(points); + if (detail?.truncated) showNote('This track is longer than the dashboard reads at once; only its first pings are shown.'); + } + + function renderEmptyState(problem, points) { + const message = emptyMessage(problem, points); + $('lpEmpty').hidden = !message; + if (message) { + $('lpEmpty').innerHTML = `
` + + `
${dashboard.esc(message.title)}
${dashboard.esc(message.sub)}
`; + } + } + + function emptyMessage(problem, points) { + if (!dashboard.hasSession()) { + return { title: 'Not connected yet', sub: 'Open DevConsole on the device → More → scan the QR or paste the code in Overview to see recorded location pings.' }; + } + if (problem) return { title: 'Location pings', sub: problem }; + if (overview && !overview.configured) { + return { title: 'No ping streams configured', sub: 'Register your location-ping endpoints with DevConsoleConfig.withLocationPingTracking(...) — see docs/LOCATION_PINGS.md.' }; + } + if (!detail) { + return { title: 'No pings recorded yet', sub: 'Switch a stream on under Recording, then use the app. Pings are written to the device as they are sent.' }; + } + if (!points.length) return { title: 'No pings match', sub: 'Every ping in this track is hidden by the current filters.' }; + return null; + } + + function ensureMap() { + if (map || !window.L) return; + map = L.map('lpMap', { preferCanvas: true, zoomControl: true, worldCopyJump: true, attributionControl: false }).setView([0, 0], 2); + L.tileLayer(TILE_URL, { maxZoom: 19 }).addTo(map); + routeLayer = L.layerGroup().addTo(map); + pointLayer = L.layerGroup().addTo(map); + labelLayer = L.layerGroup().addTo(map); + map.on('moveend', renderGapLabels); + new MutationObserver(() => { if (detail) renderTrack(); }) + .observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] }); + } + + function renderMap(points) { + if (!map) return; + routeLayer.clearLayers(); + pointLayer.clearLayers(); + markersByIndex.clear(); + if (!points.length) { + labelLayer.clearLayers(); + return; + } + const latLngs = points.map((point) => [point.lat, point.lng]); + L.polyline(latLngs, { color: cssColor('--signal'), weight: 3, opacity: 0.7 }).addTo(routeLayer); + const lastIndex = points[points.length - 1].index; + const firstIndex = points[0].index; + points.forEach((point) => { + const endpoint = point.index === firstIndex || point.index === lastIndex; + const marker = L.circleMarker([point.lat, point.lng], markerStyle(point, endpoint)) + .on('click', () => selectPoint(point.index, { openDetails: true })) + .bindTooltip(() => markerTooltip(point), { direction: 'top', offset: [0, -6] }) + .addTo(pointLayer); + markersByIndex.set(point.index, marker); + }); + fitTrackOnce(latLngs); + renderGapLabels(); + } + + function markerStyle(point, endpoint) { + const selected = point.index === selectedIndex; + return { + radius: selected ? 9 : endpoint ? 7 : 5, + color: selected ? cssColor('--ink') : endpoint ? cssColor('--panel') : cssColor('--ground'), + weight: selected || endpoint ? 3 : 1, + fillColor: cssColor(STATUS_COLOR_TOKENS[point.status] || '--muted'), + fillOpacity: 0.95, + }; + } + + function markerTooltip(point) { + return dashboard.esc('#' + (point.index + 1) + ' · ' + statusText(point) + ' · ' + formatClock(point.deviceTime)); + } + + function fitTrackOnce(latLngs) { + const key = selectedStream + '/' + selectedFile + '/' + statusFilter + '/' + appStateFilter; + if (key === fittedTrackKey) return; + fittedTrackKey = key; + map.fitBounds(L.latLngBounds(latLngs), { padding: [32, 32], maxZoom: FOCUS_ZOOM }); + } + + function renderGapLabels() { + if (!map) return; + labelLayer.clearLayers(); + const showDevice = $('lpDeviceGaps').checked; + const showFix = $('lpFixGaps').checked && !$('lpFixGapsToggle').hidden; + if (!showDevice && !showFix) return; + const bounds = map.getBounds(); + filteredPoints() + .filter((point) => bounds.contains([point.lat, point.lng])) + .slice(0, MAX_GAP_LABELS) + .forEach((point) => { + const parts = []; + if (showDevice) parts.push('d ' + formatGap(point.deviceGapSeconds)); + if (showFix) parts.push('f ' + formatGap(point.fixGapSeconds)); + L.tooltip({ permanent: true, direction: 'right', offset: [6, 0], className: 'lp-gap-label' }) + .setLatLng([point.lat, point.lng]) + .setContent(dashboard.esc(parts.join(' · '))) + .addTo(labelLayer); + }); + } + + function renderList(points) { + const rows = points.slice(0, MAX_LIST_ROWS).map((point) => { + const appState = appStateOf(point); + const appStateMark = appState === 'foreground' ? 'F' : appState === 'background' ? 'B' : ''; + return ``; + }); + if (points.length > MAX_LIST_ROWS) { + rows.push(`
${points.length - MAX_LIST_ROWS} more pings — narrow the filter to list them.
`); + } + $('lpList').innerHTML = rows.join(''); + } + + function renderMetrics(points) { + const strip = $('lpMetrics'); + const all = detail?.points || []; + strip.hidden = all.length === 0; + if (!all.length) return; + const count = (status) => points.filter((point) => point.status === status).length; + const sent = count('sent'); + const failed = count('failed'); + const dropped = count('dropped'); + const offline = count('offline'); + const delivered = points.length ? Math.round((sent / points.length) * 100) : 0; + const span = points.length > 1 ? (points[points.length - 1].deviceTime - points[0].deviceTime) / 1000 : 0; + strip.innerHTML = [ + metric('Pings shown', String(points.length), points.length === all.length ? '' : 'of ' + all.length, 'signal'), + metric('Delivered', delivered + '%', sent + ' sent', delivered >= 95 ? 'success' : 'warn'), + metric('Not delivered', String(failed + dropped + offline), failed + ' failed · ' + dropped + ' dropped · ' + offline + ' offline', failed + dropped + offline ? 'error' : 'muted'), + metric('Route', formatDistance(routeMeters(points)), 'over ' + formatGap(span), 'put'), + ].join(''); + } + + function metric(label, value, sub, tone) { + return `
${dashboard.esc(label)}
` + + `${dashboard.esc(value)}${sub ? `${dashboard.esc(sub)}` : ''}
`; + } + + function selectPoint(index, { openDetails = false, focus = false } = {}) { + const previous = selectedIndex; + selectedIndex = index; + const point = (detail?.points || []).find((candidate) => candidate.index === index); + restyleMarker(previous); + restyleMarker(index); + markersByIndex.get(index)?.bringToFront(); + document.querySelectorAll('#lpList .lp-row.selected').forEach((row) => row.classList.remove('selected')); + const row = document.querySelector(`#lpList .lp-row[data-index="${index}"]`); + row?.classList.add('selected'); + row?.scrollIntoView({ block: 'nearest' }); + if (point && focus) map?.setView([point.lat, point.lng], Math.max(map.getZoom(), FOCUS_ZOOM)); + if (point && openDetails) openPingDetails(point); + } + + function restyleMarker(index) { + const marker = markersByIndex.get(index); + const point = (detail?.points || []).find((candidate) => candidate.index === index); + if (!marker || !point) return; + const points = filteredPoints(); + const endpoint = point.index === points[0]?.index || point.index === points[points.length - 1]?.index; + marker.setStyle(markerStyle(point, endpoint)); + marker.setRadius(markerStyle(point, endpoint).radius); + } + + function openPingDetails(point) { + openPoint = point; + $('lpPingTitleText').textContent = 'Ping #' + (point.index + 1); + const rows = [ + ['Status', `${dashboard.esc(statusText(point))}`], + ['Device time', dashboard.esc(formatDateTime(point.deviceTime))], + ['Device time gap', dashboard.esc(formatGap(point.deviceGapSeconds))], + ]; + if (point.fixTime != null) { + rows.push(['Fix time', dashboard.esc(formatDateTime(point.fixTime))]); + rows.push(['Fix time gap', dashboard.esc(formatGap(point.fixGapSeconds))]); + } + if (point.appState) rows.push(['App state', dashboard.esc(point.appState)]); + rows.push(['Latitude', dashboard.esc(String(point.lat))], ['Longitude', dashboard.esc(String(point.lng))]); + Object.entries(point.fields || {}).forEach(([key, value]) => rows.push([dashboard.esc(key), dashboard.esc(value)])); + $('lpPingRows').innerHTML = rows.map(([label, value]) => + `
${label}${value}
`).join(''); + $('lpPingModal').hidden = false; + $('lpPingClose').focus(); + } + + function closePingDetails() { + $('lpPingModal').hidden = true; + openPoint = null; + } + + async function copyOpenPoint() { + if (!openPoint) return; + await dashboard.copyToClipboard(JSON.stringify(openPoint, null, 2), 'Ping #' + (openPoint.index + 1)); + } + + async function toggleStream(name, enabled) { + const response = await fetch('/api/v1/location-pings/streams/' + encodeURIComponent(name), { + method: 'PUT', + headers: dashboard.controlHeaders(), + body: String(enabled), + }); + if (response.ok) { + dashboard.toast((enabled ? 'Recording ' : 'Stopped recording ') + name + ' pings.'); + } else { + dashboard.toast('Could not change ' + name + ': ' + response.status, 'error'); + } + await refresh(); + } + + async function deleteSelectedTrack() { + if (!selectedFile) return; + const ok = await dashboard.openConfirm('Delete this track?', `${selectedFile} is removed from the device. This cannot be undone.`, 'Delete track'); + if (!ok) return; + const query = new URLSearchParams({ stream: selectedStream, file: selectedFile }); + const response = await fetch('/api/v1/location-pings/track?' + query, { method: 'DELETE', headers: dashboard.controlHeaders() }); + dashboard.toast(response.ok ? 'Track deleted.' : 'Could not delete the track: ' + response.status, response.ok ? undefined : 'error'); + selectedFile = ''; + await refresh(); + } + + async function deleteEverything() { + const ok = await dashboard.openConfirm('Delete every recorded ping?', 'All location-ping files are removed from the device, for every stream. This cannot be undone.', 'Delete all'); + if (!ok) return; + const response = await fetch('/api/v1/location-pings', { method: 'DELETE', headers: dashboard.controlHeaders() }); + if (response.ok) { + const result = await response.json(); + dashboard.toast(result.filesLeft ? `Deleted ${result.filesDeleted} files; ${result.filesLeft} could not be removed.` : `Deleted ${result.filesDeleted} files.`, result.filesLeft ? 'error' : undefined); + } else { + dashboard.toast('Could not delete pings: ' + response.status, 'error'); + } + selectedFile = ''; + await refresh(); + } + + function setAutoRefresh(enabled) { + clearInterval(autoRefreshTimer); + autoRefreshTimer = enabled + ? setInterval(() => { if (dashboard.isVisible() && dashboard.hasSession()) refresh(); }, AUTO_REFRESH_MS) + : null; + } + + function showNote(text) { + $('lpNote').hidden = !text; + $('lpNote').textContent = text; + } + + function wireSegment(id, onChange) { + $(id).addEventListener('click', (event) => { + const button = event.target.closest('button[data-value]'); + if (!button) return; + $(id).querySelectorAll('button').forEach((candidate) => candidate.classList.toggle('active', candidate === button)); + onChange(button.dataset.value); + }); + } + + function bindOnce() { + if (controlsBound) return; + controlsBound = true; + $('lpStreams').addEventListener('change', (event) => { + const input = event.target.closest('input[data-stream]'); + if (input) toggleStream(input.dataset.stream, input.checked); + }); + $('lpStream').onchange = (event) => { + selectedStream = event.target.value; + selectedFile = ''; + renderOverview(); + loadSelectedTrack(); + }; + $('lpTrack').onchange = (event) => { + selectedFile = event.target.value; + selectedIndex = -1; + $('lpDeleteTrack').disabled = !selectedFile; + loadSelectedTrack(); + }; + wireSegment('lpStatusSeg', (value) => { statusFilter = value; renderTrack(); }); + wireSegment('lpAppStateSeg', (value) => { appStateFilter = value; renderTrack(); }); + $('lpDeviceGaps').onchange = renderGapLabels; + $('lpFixGaps').onchange = renderGapLabels; + $('lpAutoRefresh').onchange = (event) => setAutoRefresh(event.target.checked); + $('lpRefresh').onclick = refresh; + $('lpDeleteTrack').onclick = deleteSelectedTrack; + $('lpDeleteAll').onclick = deleteEverything; + $('lpList').addEventListener('click', (event) => { + const row = event.target.closest('.lp-row'); + if (!row) return; + const index = Number(row.dataset.index); + if (index === selectedIndex) { + const point = (detail?.points || []).find((candidate) => candidate.index === index); + if (point) openPingDetails(point); + } else { + selectPoint(index, { focus: true }); + } + }); + $('lpPingClose').onclick = closePingDetails; + $('lpPingModal').addEventListener('click', (event) => { if (event.target === $('lpPingModal')) closePingDetails(); }); + $('lpPingModal').addEventListener('keydown', (event) => { if (event.key === 'Escape') closePingDetails(); }); + $('lpPingCopy').onclick = copyOpenPoint; + $('lpPingShow').onclick = () => { + const point = openPoint; + closePingDetails(); + if (point) selectPoint(point.index, { focus: true }); + }; + } + + function statusText(point) { + if (point.statusCode != null) return 'HTTP ' + point.statusCode; + return STATUS_LABELS[point.status] || point.status; + } + + function shortStatusText(point) { + if (point.statusCode != null) return 'HTTP ' + point.statusCode; + return SHORT_STATUS_LABELS[point.status] || point.status; + } + + function cssColor(token) { + return getComputedStyle(document.documentElement).getPropertyValue(token).trim() || '#888'; + } + + function routeMeters(points) { + let meters = 0; + for (let i = 1; i < points.length; i += 1) meters += metersBetween(points[i - 1], points[i]); + return meters; + } + + function metersBetween(from, to) { + const toRadians = (degrees) => (degrees * Math.PI) / 180; + const latDelta = toRadians(to.lat - from.lat); + const lngDelta = toRadians(to.lng - from.lng); + const haversine = Math.sin(latDelta / 2) ** 2 + + Math.cos(toRadians(from.lat)) * Math.cos(toRadians(to.lat)) * Math.sin(lngDelta / 2) ** 2; + return 2 * EARTH_RADIUS_METERS * Math.atan2(Math.sqrt(haversine), Math.sqrt(1 - haversine)); + } + + function formatDistance(meters) { + return meters < 1000 ? Math.round(meters) + ' m' : (meters / 1000).toFixed(2) + ' km'; + } + + function formatGap(seconds) { + if (seconds == null) return '–'; + const rounded = Math.round(seconds * 10) / 10; + if (Math.abs(rounded) < 60) return (Number.isInteger(rounded) ? rounded : rounded.toFixed(1)) + 's'; + const whole = Math.round(Math.abs(seconds)); + const sign = seconds < 0 ? '-' : ''; + if (whole < 3600) return sign + Math.floor(whole / 60) + 'm ' + String(whole % 60).padStart(2, '0') + 's'; + return sign + Math.floor(whole / 3600) + 'h ' + String(Math.floor((whole % 3600) / 60)).padStart(2, '0') + 'm'; + } + + function formatBytes(bytes) { + if (bytes < 1024) return bytes + ' B'; + if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'; + return (bytes / (1024 * 1024)).toFixed(1) + ' MB'; + } + + function formatClock(epochMs) { + return new Date(epochMs).toLocaleTimeString(); + } + + function formatDateTime(epochMs) { + return new Date(epochMs).toLocaleString() + ' (' + epochMs + ')'; + } + + window.DevConsoleLocationPings = { load }; +})(); From 1a1e50715d0a0d2c6134bd518746f32675fde6d6 Mon Sep 17 00:00:00 2001 From: zakaria5729 Date: Mon, 26 Oct 2026 20:34:39 +0600 Subject: [PATCH 5/8] feat: record location pings from the SDK runtime DevConsoleConfig.withLocationPingTracking(...) (and the Builder's locationPingTracking) registers the ping streams and body schema. The full runtime keeps the store in app-private files, remembers each stream's switch in SharedPreferences, and records every matching request that goes through the OkHttp interceptor. A request that fails before a response counts as offline. DevConsole.recordLocationPing(...) covers pings the app drops or cannot send, and isLocationPingTrackingEnabled(...) reports whether a stream is recording. Both are gated by the network capture category, and the no-op runtime answers false. --- sdk/api/api/api.api | 5 +++ sdk/api/build.gradle.kts | 1 + .../io/devconsole/api/DevConsoleConfig.kt | 15 +++++++- .../api/DevConsoleFacadeProvider.kt | 9 +++++ .../main/kotlin/io/devconsole/DevConsole.kt | 13 +++++++ sdk/full/api/full.api | 4 +++ .../devconsole/AndroidLocationPingSwitches.kt | 31 ++++++++++++++++ .../io/devconsole/PlatformFacadeProvider.kt | 35 +++++++++++++++++++ sdk/noop/api/noop.api | 4 +++ .../io/devconsole/PlatformFacadeProvider.kt | 9 +++++ 10 files changed, 125 insertions(+), 1 deletion(-) create mode 100644 sdk/full/src/main/kotlin/io/devconsole/AndroidLocationPingSwitches.kt diff --git a/sdk/api/api/api.api b/sdk/api/api/api.api index 792b4bc..a8da33a 100644 --- a/sdk/api/api/api.api +++ b/sdk/api/api/api.api @@ -265,6 +265,7 @@ public final class io/devconsole/api/DevConsoleConfig { public final fun getEditingCapabilities ()Lio/devconsole/api/EditingCapabilities; public final fun getEventBufferCapacity ()I public final fun getFeatureFlags ()Ljava/util/List; + public final fun getLocationPingTracking ()Lio/devconsole/locationping/LocationPingTracking; public final fun getOpenTriggers ()Lio/devconsole/api/OpenTriggers; public final fun getRedactionPolicy ()Lio/devconsole/security/RedactionPolicy; public final fun getRemoteConfigProviders ()Ljava/util/List; @@ -286,6 +287,7 @@ public final class io/devconsole/api/DevConsoleConfig { public final fun withCaptureCategories ([Lio/devconsole/api/CaptureCategory;)Lio/devconsole/api/DevConsoleConfig; public final fun withCrashPolicy (Lio/devconsole/api/CrashPolicy;)Lio/devconsole/api/DevConsoleConfig; public final fun withEditingCapabilities (Lio/devconsole/api/EditingCapabilities;)Lio/devconsole/api/DevConsoleConfig; + public final fun withLocationPingTracking (Lio/devconsole/locationping/LocationPingTracking;)Lio/devconsole/api/DevConsoleConfig; public final fun withOpenTriggers (Lio/devconsole/api/OpenTriggers;)Lio/devconsole/api/DevConsoleConfig; public final fun withRemoteConfigProviders (Ljava/util/List;)Lio/devconsole/api/DevConsoleConfig; public final fun withRetentionPolicy (Lio/devconsole/api/RetentionPolicy;)Lio/devconsole/api/DevConsoleConfig; @@ -309,6 +311,7 @@ public final class io/devconsole/api/DevConsoleConfig$Builder { public final fun crashPolicy (Lio/devconsole/api/CrashPolicy;)Lio/devconsole/api/DevConsoleConfig$Builder; public final fun editingCapabilities (Lio/devconsole/api/EditingCapabilities;)Lio/devconsole/api/DevConsoleConfig$Builder; public final fun eventBufferCapacity (I)Lio/devconsole/api/DevConsoleConfig$Builder; + public final fun locationPingTracking (Lio/devconsole/locationping/LocationPingTracking;)Lio/devconsole/api/DevConsoleConfig$Builder; public final fun openTriggers (Lio/devconsole/api/OpenTriggers;)Lio/devconsole/api/DevConsoleConfig$Builder; public final fun redactionPolicy (Lio/devconsole/security/RedactionPolicy;)Lio/devconsole/api/DevConsoleConfig$Builder; public final fun retentionPolicy (Lio/devconsole/api/RetentionPolicy;)Lio/devconsole/api/DevConsoleConfig$Builder; @@ -331,10 +334,12 @@ public abstract interface class io/devconsole/api/DevConsoleFacadeProvider { public abstract fun featureFlagStringValue (Ljava/lang/String;)Ljava/lang/String; public abstract fun featureFlagValue (Ljava/lang/String;)Z public abstract fun initialize (Landroid/app/Application;Lio/devconsole/api/DevConsoleConfig;)Lio/devconsole/api/InitResult; + public abstract fun isLocationPingTrackingEnabled (Ljava/lang/String;)Z public abstract fun logRecorder ()Lio/devconsole/logs/LogRecorder; public abstract fun mockEngine ()Lio/devconsole/mocks/MockEngine; public abstract fun networkRecorder ()Lio/devconsole/network/NetworkTransactionRecorder; public abstract fun openInspector (Landroid/content/Context;)Lio/devconsole/api/InspectorOpenResult; + public abstract fun recordLocationPing (Ljava/lang/String;Ljava/lang/String;Lio/devconsole/locationping/LocationPingOutcome;)Z public abstract fun recordPush (Lio/devconsole/push/PushInput;)Lio/devconsole/push/PushEvent; public abstract fun registerRemoteConfigProvider (Lio/devconsole/remoteconfig/RemoteConfigProvider;)Z public abstract fun registerStateProvider (Lio/devconsole/state/StateProvider;)Z diff --git a/sdk/api/build.gradle.kts b/sdk/api/build.gradle.kts index 599ce9d..b0e2c1d 100644 --- a/sdk/api/build.gradle.kts +++ b/sdk/api/build.gradle.kts @@ -12,6 +12,7 @@ dependencies { api(project(":sdk:push")) api(project(":sdk:state")) api(project(":sdk:remote-config")) + api(project(":sdk:location-ping")) api(project(":sdk:security")) api(project(":sdk:mocks")) api(project(":sdk:logs")) diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt b/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt index eb841c1..f34a80d 100644 --- a/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt +++ b/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt @@ -1,5 +1,6 @@ package io.devconsole.api +import io.devconsole.locationping.LocationPingTracking import io.devconsole.remoteconfig.RemoteConfigProvider import io.devconsole.security.RedactionEngine import io.devconsole.security.RedactionPolicy @@ -87,6 +88,9 @@ data class DevConsoleConfig( var remoteConfigProviders: List = emptyList() private set + var locationPingTracking: LocationPingTracking = LocationPingTracking() + private set + fun withStoragePolicy(value: StoragePolicy): DevConsoleConfig = duplicate().also { it.storagePolicy = value @@ -134,6 +138,9 @@ data class DevConsoleConfig( fun withRemoteConfigProviders(value: List): DevConsoleConfig = duplicate().also { it.remoteConfigProviders = value.toList() } + fun withLocationPingTracking(value: LocationPingTracking): DevConsoleConfig = + duplicate().also { it.locationPingTracking = value } + fun capturesCategory(category: CaptureCategory): Boolean = category in captureCategories /** @@ -184,7 +191,8 @@ data class DevConsoleConfig( screenshotPolicy == other.screenshotPolicy && captureCategories == other.captureCategories && openTriggers == other.openTriggers && - remoteConfigProviders == other.remoteConfigProviders + remoteConfigProviders == other.remoteConfigProviders && + locationPingTracking == other.locationPingTracking private fun duplicate(): DevConsoleConfig = copy().also { @@ -199,6 +207,7 @@ data class DevConsoleConfig( it.captureCategories = captureCategories it.openTriggers = openTriggers it.remoteConfigProviders = remoteConfigProviders + it.locationPingTracking = locationPingTracking } /** Mutable builder for Java callers and for incremental construction. */ @@ -222,6 +231,7 @@ data class DevConsoleConfig( private var captureCategories: Set = CaptureCategory.all() private var openTriggers = OpenTriggers() private val remoteConfigProviders = mutableListOf() + private var locationPingTracking = LocationPingTracking() fun eventBufferCapacity(value: Int) = apply { eventBufferCapacity = value } @@ -261,6 +271,8 @@ data class DevConsoleConfig( fun addRemoteConfigProvider(value: RemoteConfigProvider) = apply { remoteConfigProviders += value } + fun locationPingTracking(value: LocationPingTracking) = apply { locationPingTracking = value } + fun build(): DevConsoleConfig { val configured = DevConsoleConfig( @@ -281,6 +293,7 @@ data class DevConsoleConfig( .withCaptureCategories(captureCategories) .withOpenTriggers(openTriggers) .withRemoteConfigProviders(remoteConfigProviders) + .withLocationPingTracking(locationPingTracking) return retentionPolicy?.let(configured::withRetentionPolicy) ?: configured } } diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleFacadeProvider.kt b/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleFacadeProvider.kt index 1e9b1b4..7fcaa58 100644 --- a/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleFacadeProvider.kt +++ b/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleFacadeProvider.kt @@ -3,6 +3,7 @@ package io.devconsole.api import android.app.Application import android.content.Context import android.content.Intent +import io.devconsole.locationping.LocationPingOutcome import io.devconsole.logs.LogRecorder import io.devconsole.mocks.MockEngine import io.devconsole.network.NetworkTransactionRecorder @@ -94,4 +95,12 @@ interface DevConsoleFacadeProvider { * (a boolean flag returns `"true"`/`"false"`). Falls back to `""` for an unknown key. */ fun featureFlagStringValue(key: String): String + + fun recordLocationPing( + url: String, + body: String, + outcome: LocationPingOutcome, + ): Boolean + + fun isLocationPingTrackingEnabled(streamName: String?): Boolean } diff --git a/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt b/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt index 10aaeba..0637e04 100644 --- a/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt +++ b/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt @@ -13,6 +13,7 @@ import io.devconsole.api.ScreenshotResult import io.devconsole.api.StartRequest import io.devconsole.api.StartResult import io.devconsole.api.StopReason +import io.devconsole.locationping.LocationPingOutcome import io.devconsole.logs.LogRecorder import io.devconsole.mocks.MockEngine import io.devconsole.network.NetworkTransactionRecorder @@ -236,4 +237,16 @@ object DevConsole { */ @JvmStatic fun featureFlagStringValue(key: String): String = provider.featureFlagStringValue(key) + + @JvmStatic + fun recordLocationPing( + url: String, + body: String, + outcome: LocationPingOutcome, + ): Boolean = provider.recordLocationPing(url, body, outcome) + + @JvmStatic + @JvmOverloads + fun isLocationPingTrackingEnabled(streamName: String? = null): Boolean = + provider.isLocationPingTrackingEnabled(streamName) } diff --git a/sdk/full/api/full.api b/sdk/full/api/full.api index 7440361..25a8e55 100644 --- a/sdk/full/api/full.api +++ b/sdk/full/api/full.api @@ -9,10 +9,14 @@ public final class io/devconsole/DevConsole { public static final fun featureFlagValue (Ljava/lang/String;)Z public static final fun initialize (Landroid/app/Application;Lio/devconsole/api/DevConsoleConfig;)Lio/devconsole/api/InitResult; public static synthetic fun initialize$default (Landroid/app/Application;Lio/devconsole/api/DevConsoleConfig;ILjava/lang/Object;)Lio/devconsole/api/InitResult; + public static final fun isLocationPingTrackingEnabled ()Z + public static final fun isLocationPingTrackingEnabled (Ljava/lang/String;)Z + public static synthetic fun isLocationPingTrackingEnabled$default (Ljava/lang/String;ILjava/lang/Object;)Z public static final fun logRecorder ()Lio/devconsole/logs/LogRecorder; public static final fun mockEngine ()Lio/devconsole/mocks/MockEngine; public static final fun networkRecorder ()Lio/devconsole/network/NetworkTransactionRecorder; public static final fun open (Landroid/content/Context;)Lio/devconsole/api/InspectorOpenResult; + public static final fun recordLocationPing (Ljava/lang/String;Ljava/lang/String;Lio/devconsole/locationping/LocationPingOutcome;)Z public static final fun recordPush (Lio/devconsole/push/PushInput;)Lio/devconsole/push/PushEvent; public static final fun registerRemoteConfigProvider (Lio/devconsole/remoteconfig/RemoteConfigProvider;)Z public static final fun registerStateProvider (Lio/devconsole/state/StateProvider;)Z diff --git a/sdk/full/src/main/kotlin/io/devconsole/AndroidLocationPingSwitches.kt b/sdk/full/src/main/kotlin/io/devconsole/AndroidLocationPingSwitches.kt new file mode 100644 index 0000000..94f6852 --- /dev/null +++ b/sdk/full/src/main/kotlin/io/devconsole/AndroidLocationPingSwitches.kt @@ -0,0 +1,31 @@ +/** + * @author Zakaria + * @since 26/10/26 + */ +package io.devconsole + +import android.content.Context +import android.content.SharedPreferences +import io.devconsole.locationping.LocationPingSwitches + +internal class AndroidLocationPingSwitches( + context: Context, +) : LocationPingSwitches { + private val preferences: SharedPreferences = + context.applicationContext.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE) + + override fun isEnabled(streamName: String): Boolean = preferences.getBoolean(keyOf(streamName), false) + + override fun setEnabled( + streamName: String, + enabled: Boolean, + ) { + preferences.edit().putBoolean(keyOf(streamName), enabled).apply() + } + + private fun keyOf(streamName: String): String = "enabled.$streamName" + + private companion object { + const val PREFERENCES_NAME = "devconsole_location_pings" + } +} diff --git a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt index 5fbdd54..eb61141 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt @@ -29,6 +29,8 @@ import io.devconsole.api.StopReason import io.devconsole.core.DevConsoleRuntime import io.devconsole.core.EventBatchWriter import io.devconsole.core.RuntimeGate +import io.devconsole.locationping.LocationPingOutcome +import io.devconsole.locationping.LocationPingStore import io.devconsole.logs.LogRecorder import io.devconsole.logs.LogSink import io.devconsole.mocks.MockEngine @@ -206,6 +208,11 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { .withAttachmentSink(::persistNetworkAttachment) .withCaptureGate { method, url -> categoryEnabled(CaptureCategory.NETWORK) && captureRuleEngineInstance.allowsCapture(method, url) + }.withCompletionObserver { request, response -> + if (categoryEnabled(CaptureCategory.NETWORK)) { + val answeredStatus = response?.takeIf { it.error == null }?.statusCode + locationPingStore?.recordNetworkPing(request.url, request.body, answeredStatus) + } } private val socketRecorderInstance = SocketRecorder(redaction, socketStore) @@ -250,6 +257,8 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { @Volatile private var activeConfig: DevConsoleConfig? = null + @Volatile private var locationPingStore: LocationPingStore? = null + private val crashCapture = CrashCapture( ::activeSessionId, @@ -745,6 +754,7 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { config.remoteConfigProviders.forEach { provider -> safely { remoteConfigRegistry.register(provider) } } } featureFlags = SessionFeatureFlags(config.featureFlags) + configureLocationPings(application, config) buildOrReconfigureServerEngine( application, config, @@ -765,6 +775,19 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { return result } + private fun configureLocationPings( + application: Application, + config: DevConsoleConfig, + ) { + val store = + locationPingStore ?: LocationPingStore( + rootDirectory = File(application.filesDir, LOCATION_PING_DIRECTORY), + switches = AndroidLocationPingSwitches(application), + redactFields = { fields -> redaction.redactFields(fields) }, + ).also { locationPingStore = it } + store.configure(config.locationPingTracking) + } + /** * Split out of [initialize] purely to keep that function's cyclomatic complexity under the * project's detekt threshold -- every gated inspector below was already computed by the caller. @@ -1008,6 +1031,7 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { sessionsProvider = { sessionStore?.sessions().orEmpty() }, screenshotCapture = ::captureScreenshot, ).withRetainedCaptures(RetainedCaptureQuery({ eventStore }, runtime::currentSessionId)) + .withLocationPings { locationPingStore } .withBrowserSecurity(config.browserSecurity) .withAttachmentReader { attachmentId -> roomAttachmentStore?.read(attachmentId) } .withAttachmentMetadataReader { attachmentId -> roomAttachmentStore?.metadata(attachmentId) } @@ -1396,6 +1420,15 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { return runCatching { flags.booleanValue(key) }.getOrDefault(false) } + override fun recordLocationPing( + url: String, + body: String, + outcome: LocationPingOutcome, + ): Boolean = categoryEnabled(CaptureCategory.NETWORK) && locationPingStore?.record(url, body, outcome) == true + + override fun isLocationPingTrackingEnabled(streamName: String?): Boolean = + categoryEnabled(CaptureCategory.NETWORK) && locationPingStore?.isEnabled(streamName) == true + override fun featureFlagStringValue(key: String): String { val flags = if (::featureFlags.isInitialized) featureFlags else return "" return runCatching { flags.value(key) }.getOrDefault("") @@ -1628,6 +1661,8 @@ private fun io.devconsole.api.RetentionPolicy.toInspectorRetentionUi(): Inspecto private const val CURSOR_SECRET_BYTES = 16 +private const val LOCATION_PING_DIRECTORY = "devconsole/location-pings" + private fun randomCursorSecret(): ByteArray = ByteArray(CURSOR_SECRET_BYTES).also(SecureRandom()::nextBytes) /** diff --git a/sdk/noop/api/noop.api b/sdk/noop/api/noop.api index 0fa96f0..065be87 100644 --- a/sdk/noop/api/noop.api +++ b/sdk/noop/api/noop.api @@ -9,10 +9,14 @@ public final class io/devconsole/DevConsole { public static final fun featureFlagValue (Ljava/lang/String;)Z public static final fun initialize (Landroid/app/Application;Lio/devconsole/api/DevConsoleConfig;)Lio/devconsole/api/InitResult; public static synthetic fun initialize$default (Landroid/app/Application;Lio/devconsole/api/DevConsoleConfig;ILjava/lang/Object;)Lio/devconsole/api/InitResult; + public static final fun isLocationPingTrackingEnabled ()Z + public static final fun isLocationPingTrackingEnabled (Ljava/lang/String;)Z + public static synthetic fun isLocationPingTrackingEnabled$default (Ljava/lang/String;ILjava/lang/Object;)Z public static final fun logRecorder ()Lio/devconsole/logs/LogRecorder; public static final fun mockEngine ()Lio/devconsole/mocks/MockEngine; public static final fun networkRecorder ()Lio/devconsole/network/NetworkTransactionRecorder; public static final fun open (Landroid/content/Context;)Lio/devconsole/api/InspectorOpenResult; + public static final fun recordLocationPing (Ljava/lang/String;Ljava/lang/String;Lio/devconsole/locationping/LocationPingOutcome;)Z public static final fun recordPush (Lio/devconsole/push/PushInput;)Lio/devconsole/push/PushEvent; public static final fun registerRemoteConfigProvider (Lio/devconsole/remoteconfig/RemoteConfigProvider;)Z public static final fun registerStateProvider (Lio/devconsole/state/StateProvider;)Z diff --git a/sdk/noop/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt b/sdk/noop/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt index 523fa18..15c8e91 100644 --- a/sdk/noop/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt +++ b/sdk/noop/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt @@ -14,6 +14,7 @@ import io.devconsole.api.ScreenshotResult import io.devconsole.api.StartRequest import io.devconsole.api.StartResult import io.devconsole.api.StopReason +import io.devconsole.locationping.LocationPingOutcome import io.devconsole.logs.LogRecorder import io.devconsole.logs.LogSink import io.devconsole.mocks.MockEngine @@ -110,6 +111,14 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { override fun featureFlagStringValue(key: String): String = declaredDefault(key) + override fun recordLocationPing( + url: String, + body: String, + outcome: LocationPingOutcome, + ): Boolean = false + + override fun isLocationPingTrackingEnabled(streamName: String?): Boolean = false + private fun declaredDefault(key: String): String = flags.firstOrNull { it.key == key }?.defaultValue.orEmpty() } From e91ec9eba3ab8ea56d9ac6aca2f77d2ff72ba925 Mon Sep 17 00:00:00 2001 From: zakaria5729 Date: Mon, 26 Oct 2026 20:34:46 +0600 Subject: [PATCH 6/8] feat(inspector): add location ping switches to the More screen The in-app inspector's More screen lists each configured stream with a switch, so a tester can start or stop recording on the phone without opening the dashboard. The list is empty, and the group hidden, when no streams are configured or network capture is off. --- .../io/devconsole/FullInspectorDataSource.kt | 30 +++++++ .../io/devconsole/PlatformFacadeProvider.kt | 1 + sdk/ui-compose/api/ui-compose.api | 86 +++++++++++++------ .../devconsole/ui/compose/InspectorAction.kt | 5 ++ .../ui/compose/InspectorDataSource.kt | 12 +++ .../ui/compose/InspectorMoreScreen.kt | 43 ++++++++++ .../devconsole/ui/compose/InspectorState.kt | 1 + .../ui/compose/InspectorViewModel.kt | 13 +++ 8 files changed, 167 insertions(+), 24 deletions(-) diff --git a/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt b/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt index 473f8c0..fa93f28 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt @@ -15,6 +15,7 @@ import io.devconsole.api.ScreenshotResult import io.devconsole.composer.ComposerDestinationRejectedException import io.devconsole.composer.ComposerExecutor import io.devconsole.composer.UrlConnectionComposerTransport +import io.devconsole.locationping.LocationPingStore import io.devconsole.logs.LogLevel import io.devconsole.mocks.MockAction import io.devconsole.mocks.MockEngine @@ -82,6 +83,7 @@ import io.devconsole.ui.compose.InspectorFileEntryUi import io.devconsole.ui.compose.InspectorFileListingUi import io.devconsole.ui.compose.InspectorFilePreviewUi import io.devconsole.ui.compose.InspectorHealthUi +import io.devconsole.ui.compose.InspectorLocationPingStreamUi import io.devconsole.ui.compose.InspectorLogUi import io.devconsole.ui.compose.InspectorMockRuleUi import io.devconsole.ui.compose.InspectorPreferenceEntryUi @@ -189,6 +191,7 @@ internal class FullInspectorDataSource( * [InspectorDataSource.onNotificationPermissionGranted] for why a grant alone shows nothing. */ private val republishKeepAliveNotification: () -> Unit = {}, + private val locationPingStoreSupplier: () -> LocationPingStore? = { null }, ) : InspectorDataSource, InspectorServerStartPermissionProvider { override fun onNotificationPermissionGranted() = republishKeepAliveNotification() @@ -375,9 +378,22 @@ internal class FullInspectorDataSource( retention = retentionSupplier(), keepAlivePromptNeeded = keepAlivePromptSupplier(), captureCategories = categories, + locationPingStreams = + if (CaptureCategory.NETWORK in + categories + ) { + locationPingStoreSupplier().streamsUi() + } else { + emptyList() + }, ) } + override fun setLocationPingStreamEnabled( + name: String, + enabled: Boolean, + ): InspectorCommandResult = locationPingStoreSupplier().switchStream(name, enabled) + private fun transactionsFor( categories: Set, trafficQuery: InspectorTrafficQuery, @@ -1422,3 +1438,17 @@ private fun StoredEvent.evidenceCrashSnapshotJson(): String = payloadJson?.let { append(",\"payload\":").append(it) } append('}') } + +private fun LocationPingStore?.streamsUi(): List = + this?.streams().orEmpty().map { InspectorLocationPingStreamUi(it.name, it.path, it.enabled) } + +private fun LocationPingStore?.switchStream( + name: String, + enabled: Boolean, +): InspectorCommandResult = + when { + this == null -> InspectorCommandResult.Unavailable + !setEnabled(name, enabled) -> InspectorCommandResult.Invalid("Unknown location ping stream $name") + enabled -> InspectorCommandResult.Success(summary = "Recording $name pings") + else -> InspectorCommandResult.Success(summary = "Stopped recording $name pings") + } diff --git a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt index eb61141..f054e8d 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt @@ -863,6 +863,7 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { republishKeepAliveNotification = ::republishKeepAliveNotification, keepAlivePromptSupplier = ::keepAlivePromptNeeded, serverStartPermissionSupplier = ::serverStartPermissionNeeded, + locationPingStoreSupplier = { locationPingStore }, ), ) } diff --git a/sdk/ui-compose/api/ui-compose.api b/sdk/ui-compose/api/ui-compose.api index d2e1875..ea7dd0b 100644 --- a/sdk/ui-compose/api/ui-compose.api +++ b/sdk/ui-compose/api/ui-compose.api @@ -109,9 +109,11 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorMoreSc public final fun getLambda$-996758428$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$1129667334$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$1180200415$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$1267130819$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$1347851092$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$1403158116$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$272598894$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$402877100$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$538904397$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$636091227$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$908145821$ui_compose_release ()Lkotlin/jvm/functions/Function3; @@ -573,6 +575,20 @@ public final class io/devconsole/ui/compose/InspectorAction$SetFeatureFlag : io/ public fun toString ()Ljava/lang/String; } +public final class io/devconsole/ui/compose/InspectorAction$SetLocationPingStreamEnabled : io/devconsole/ui/compose/InspectorAction { + public static final field $stable I + public fun (Ljava/lang/String;Z)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Z + public final fun copy (Ljava/lang/String;Z)Lio/devconsole/ui/compose/InspectorAction$SetLocationPingStreamEnabled; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorAction$SetLocationPingStreamEnabled;Ljava/lang/String;ZILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorAction$SetLocationPingStreamEnabled; + public fun equals (Ljava/lang/Object;)Z + public final fun getEnabled ()Z + public final fun getName ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/ui/compose/InspectorAction$SetMockRuleEnabled : io/devconsole/ui/compose/InspectorAction { public static final field $stable I public fun (Ljava/lang/String;Z)V @@ -940,6 +956,7 @@ public abstract interface class io/devconsole/ui/compose/InspectorDataSource { public fun revokePrincipal (Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorCommandResult; public abstract fun setCaptureRuleEnabled (Ljava/lang/String;Z)Lio/devconsole/ui/compose/InspectorCommandResult; public abstract fun setFeatureFlag (Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorCommandResult; + public fun setLocationPingStreamEnabled (Ljava/lang/String;Z)Lio/devconsole/ui/compose/InspectorCommandResult; public abstract fun setMockRuleEnabled (Ljava/lang/String;Z)Lio/devconsole/ui/compose/InspectorCommandResult; public abstract fun setMocksEnabled (Z)Lio/devconsole/ui/compose/InspectorCommandResult; public abstract fun setPreference (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorCommandResult; @@ -973,6 +990,7 @@ public final class io/devconsole/ui/compose/InspectorDataSource$DefaultImpls { public static fun mockRules (Lio/devconsole/ui/compose/InspectorDataSource;)Ljava/util/List; public static fun onNotificationPermissionGranted (Lio/devconsole/ui/compose/InspectorDataSource;)V public static fun revokePrincipal (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorCommandResult; + public static fun setLocationPingStreamEnabled (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;Z)Lio/devconsole/ui/compose/InspectorCommandResult; public static fun setServerRunning (Lio/devconsole/ui/compose/InspectorDataSource;Z)Lio/devconsole/ui/compose/InspectorCommandResult; public static fun shareableFilePath (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; public static fun snapshot (Lio/devconsole/ui/compose/InspectorDataSource;Lio/devconsole/ui/compose/InspectorTrafficQuery;)Lio/devconsole/ui/compose/InspectorSnapshot; @@ -1160,6 +1178,22 @@ public final class io/devconsole/ui/compose/InspectorHealthUi { public fun toString ()Ljava/lang/String; } +public final class io/devconsole/ui/compose/InspectorLocationPingStreamUi { + public static final field $stable I + public fun (Ljava/lang/String;Ljava/lang/String;Z)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Z + public final fun copy (Ljava/lang/String;Ljava/lang/String;Z)Lio/devconsole/ui/compose/InspectorLocationPingStreamUi; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorLocationPingStreamUi;Ljava/lang/String;Ljava/lang/String;ZILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorLocationPingStreamUi; + public fun equals (Ljava/lang/Object;)Z + public final fun getEnabled ()Z + public final fun getName ()Ljava/lang/String; + public final fun getPath ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/ui/compose/InspectorLogUi { public static final field $stable I public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JLjava/lang/String;)V @@ -1388,8 +1422,8 @@ public final class io/devconsole/ui/compose/InspectorSessionUi { public final class io/devconsole/ui/compose/InspectorSnapshot { public static final field $stable I public fun ()V - public fun (ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;)V - public synthetic fun (ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;Ljava/util/List;)V + public synthetic fun (ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()Z public final fun component10 ()Ljava/util/List; public final fun component11 ()Ljava/util/List; @@ -1405,6 +1439,7 @@ public final class io/devconsole/ui/compose/InspectorSnapshot { public final fun component20 ()Lio/devconsole/ui/compose/InspectorRetentionUi; public final fun component21 ()Z public final fun component22 ()Ljava/util/Set; + public final fun component23 ()Ljava/util/List; public final fun component3 ()Lio/devconsole/ui/compose/InspectorEditingUi; public final fun component4 ()Z public final fun component5 ()Ljava/util/List; @@ -1412,8 +1447,8 @@ public final class io/devconsole/ui/compose/InspectorSnapshot { public final fun component7 ()Ljava/util/List; public final fun component8 ()Ljava/util/List; public final fun component9 ()Ljava/util/List; - public final fun copy (ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;)Lio/devconsole/ui/compose/InspectorSnapshot; - public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorSnapshot;ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorSnapshot; + public final fun copy (ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;Ljava/util/List;)Lio/devconsole/ui/compose/InspectorSnapshot; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorSnapshot;ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;Ljava/util/List;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorSnapshot; public fun equals (Ljava/lang/Object;)Z public final fun getAvailable ()Z public final fun getBrowser ()Lio/devconsole/ui/compose/InspectorBrowserUi; @@ -1426,6 +1461,7 @@ public final class io/devconsole/ui/compose/InspectorSnapshot { public final fun getFileRoots ()Ljava/util/List; public final fun getHealth ()Lio/devconsole/ui/compose/InspectorHealthUi; public final fun getKeepAlivePromptNeeded ()Z + public final fun getLocationPingStreams ()Ljava/util/List; public final fun getLogs ()Ljava/util/List; public final fun getMockRules ()Ljava/util/List; public final fun getMocksEnabled ()Z @@ -1549,8 +1585,8 @@ public final class io/devconsole/ui/compose/InspectorSqlResultUi$Wrote : io/devc public final class io/devconsole/ui/compose/InspectorState { public static final field $stable I public fun ()V - public fun (ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;)V - public synthetic fun (ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;IILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;)V + public synthetic fun (ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;IILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()Z public final fun component10 ()Ljava/util/List; public final fun component11 ()Ljava/util/List; @@ -1565,31 +1601,32 @@ public final class io/devconsole/ui/compose/InspectorState { public final fun component2 ()Z public final fun component20 ()Ljava/util/List; public final fun component21 ()Ljava/util/List; - public final fun component22 ()Lio/devconsole/ui/compose/InspectorFileListingUi; - public final fun component23 ()Lio/devconsole/ui/compose/InspectorFilePreviewUi; - public final fun component24 ()Ljava/lang/String; - public final fun component25 ()Ljava/util/List; - public final fun component26 ()Lio/devconsole/ui/compose/InspectorDatabaseListingUi; - public final fun component27 ()Lio/devconsole/ui/compose/InspectorQueryResultUi; - public final fun component28 ()Lio/devconsole/ui/compose/InspectorSqlResultUi; - public final fun component29 ()Ljava/util/List; + public final fun component22 ()Ljava/util/List; + public final fun component23 ()Lio/devconsole/ui/compose/InspectorFileListingUi; + public final fun component24 ()Lio/devconsole/ui/compose/InspectorFilePreviewUi; + public final fun component25 ()Ljava/lang/String; + public final fun component26 ()Ljava/util/List; + public final fun component27 ()Lio/devconsole/ui/compose/InspectorDatabaseListingUi; + public final fun component28 ()Lio/devconsole/ui/compose/InspectorQueryResultUi; + public final fun component29 ()Lio/devconsole/ui/compose/InspectorSqlResultUi; public final fun component3 ()Ljava/util/List; - public final fun component30 ()Ljava/lang/String; - public final fun component31 ()Z - public final fun component32 ()Lio/devconsole/ui/compose/InspectorHealthUi; - public final fun component33 ()Lio/devconsole/ui/compose/InspectorBrowserUi; - public final fun component34 ()Lio/devconsole/ui/compose/InspectorRetentionUi; - public final fun component35 ()Lio/devconsole/api/ScreenshotResult; - public final fun component36 ()Z - public final fun component37 ()Ljava/util/Set; + public final fun component30 ()Ljava/util/List; + public final fun component31 ()Ljava/lang/String; + public final fun component32 ()Z + public final fun component33 ()Lio/devconsole/ui/compose/InspectorHealthUi; + public final fun component34 ()Lio/devconsole/ui/compose/InspectorBrowserUi; + public final fun component35 ()Lio/devconsole/ui/compose/InspectorRetentionUi; + public final fun component36 ()Lio/devconsole/api/ScreenshotResult; + public final fun component37 ()Z + public final fun component38 ()Ljava/util/Set; public final fun component4 ()Lio/devconsole/ui/compose/InspectorEditingUi; public final fun component5 ()Z public final fun component6 ()Ljava/util/List; public final fun component7 ()Ljava/util/List; public final fun component8 ()Lio/devconsole/ui/compose/InspectorCommandResult; public final fun component9 ()Ljava/util/List; - public final fun copy (ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;)Lio/devconsole/ui/compose/InspectorState; - public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorState;ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;IILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorState; + public final fun copy (ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;)Lio/devconsole/ui/compose/InspectorState; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorState;ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;IILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorState; public fun equals (Ljava/lang/Object;)Z public final fun getAvailable ()Z public final fun getBrowser ()Lio/devconsole/ui/compose/InspectorBrowserUi; @@ -1609,6 +1646,7 @@ public final class io/devconsole/ui/compose/InspectorState { public final fun getKeepAlivePromptNeeded ()Z public final fun getLastCommandResult ()Lio/devconsole/ui/compose/InspectorCommandResult; public final fun getLastScreenshotResult ()Lio/devconsole/api/ScreenshotResult; + public final fun getLocationPingStreams ()Ljava/util/List; public final fun getLogs ()Ljava/util/List; public final fun getMockRules ()Ljava/util/List; public final fun getMocksEnabled ()Z diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorAction.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorAction.kt index d015d3e..1e46ba9 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorAction.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorAction.kt @@ -68,6 +68,11 @@ sealed interface InspectorAction { val enabled: Boolean, ) : InspectorAction + data class SetLocationPingStreamEnabled( + val name: String, + val enabled: Boolean, + ) : InspectorAction + data class UpsertMockRule( val rule: InspectorMockRuleUi, ) : InspectorAction diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt index 162025a..58259bb 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt @@ -503,6 +503,13 @@ data class InspectorSnapshot( val keepAlivePromptNeeded: Boolean = false, /** Capture categories the host enabled at init; every list above is already filtered to this set. */ val captureCategories: Set = CaptureCategory.all(), + val locationPingStreams: List = emptyList(), +) + +data class InspectorLocationPingStreamUi( + val name: String, + val path: String, + val enabled: Boolean, ) data class InspectorComposerRequest( @@ -610,6 +617,11 @@ interface InspectorDataSource { fun setMocksEnabled(enabled: Boolean): InspectorCommandResult + fun setLocationPingStreamEnabled( + name: String, + enabled: Boolean, + ): InspectorCommandResult = InspectorCommandResult.Unavailable + /** Ungated read, mirroring the other listing methods; only the mutations below are gated. */ fun mockRules(): List = snapshot().mockRules diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt index 0056638..206f477 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt @@ -21,10 +21,12 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.items import androidx.compose.material3.AlertDialog import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect @@ -40,6 +42,8 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.ClipboardManager import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight @@ -178,6 +182,7 @@ internal data class MoreActions( val onCaptureScreenshot: () -> Unit, val onRevoke: (String) -> Unit, val onSelectSession: (String) -> Unit, + val onSetLocationPingStream: (String, Boolean) -> Unit = { _, _ -> }, ) @Composable @@ -204,6 +209,9 @@ private fun rememberMoreActions( onCaptureScreenshot = { viewModel.dispatch(InspectorAction.CaptureScreenshot) }, onRevoke = { id -> viewModel.dispatch(InspectorAction.RevokePrincipal(id)) }, onSelectSession = { id -> viewModel.dispatch(InspectorAction.SelectSession(id)) }, + onSetLocationPingStream = { name, enabled -> + viewModel.dispatch(InspectorAction.SetLocationPingStreamEnabled(name, enabled)) + }, ) /** @@ -310,6 +318,13 @@ internal fun MoreScreen( item { BrowserSessionsRow(state, actions, colors) } item { RetentionRow(state, colors) } item { Spacer(Modifier.height(8.dp)) } + if (state.locationPingStreams.isNotEmpty()) { + item { GroupLabel("Location pings") } + items(state.locationPingStreams, key = { stream -> "location-ping-${stream.name}" }) { stream -> + LocationPingStreamRow(stream, actions, colors) + } + item { Spacer(Modifier.height(8.dp)) } + } item { GroupLabel("SDK health") } sdkHealthRows(state.health, colors) } @@ -766,6 +781,34 @@ private fun CaptureScreenshotRow( ) } +@Composable +private fun LocationPingStreamRow( + stream: InspectorLocationPingStreamUi, + actions: MoreActions, + colors: DevConsoleColors, +) { + TonalListRow( + leadText = if (stream.enabled) "REC" else "OFF", + leadColor = if (stream.enabled) colors.put else colors.muted, + leadContainerColor = if (stream.enabled) colors.putSoft else colors.surface3, + title = stream.name, + subtitle = stream.path, + trailValue = "", + trailContent = { + Switch( + checked = stream.enabled, + onCheckedChange = { checked -> actions.onSetLocationPingStream(stream.name, checked) }, + modifier = + Modifier.semantics { + contentDescription = "${if (stream.enabled) "Stop" else "Start"} recording ${stream.name} pings" + }, + ) + }, + onClick = { actions.onSetLocationPingStream(stream.name, !stream.enabled) }, + mergeDescendants = false, + ) +} + /** RUN: real retained-run list, expand-in-place -- the old screen's [InspectorSessionUi] browsing, restyled. */ @Composable private fun RetainedRunsRow( diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorState.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorState.kt index fa04948..8e85fcb 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorState.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorState.kt @@ -41,6 +41,7 @@ data class InspectorState( val stateProviders: List = emptyList(), /** Remote Config providers, already redacted and STATE-gated by the data source. */ val remoteConfig: List = emptyList(), + val locationPingStreams: List = emptyList(), val preferenceFiles: List = emptyList(), val fileRoots: List = emptyList(), val fileListing: InspectorFileListingUi? = null, diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorViewModel.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorViewModel.kt index b5f1aaf..d5b6dc5 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorViewModel.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorViewModel.kt @@ -98,6 +98,8 @@ class InspectorViewModel is InspectorAction.ToggleCrashFlag -> toggleCrashFlag(action.id) is InspectorAction.ExecuteComposer -> executeComposer(action.request) is InspectorAction.SetMocksEnabled -> setMocksEnabled(action.enabled) + is InspectorAction.SetLocationPingStreamEnabled -> + setLocationPingStreamEnabled(action.name, action.enabled) is InspectorAction.UpsertMockRule -> upsertMockRule(action.rule) is InspectorAction.DeleteMockRule -> deleteMockRule(action.id) is InspectorAction.SetMockRuleEnabled -> setMockRuleEnabled(action.id, action.enabled) @@ -256,6 +258,7 @@ class InspectorViewModel featureFlags = snapshot.featureFlags, stateProviders = snapshot.stateProviders, remoteConfig = snapshot.remoteConfig, + locationPingStreams = snapshot.locationPingStreams, preferenceFiles = snapshot.preferenceFiles, fileRoots = snapshot.fileRoots, databases = snapshot.databases, @@ -354,6 +357,16 @@ class InspectorViewModel } } + private fun setLocationPingStreamEnabled( + name: String, + enabled: Boolean, + ) { + viewModelScope.launch(dispatcher) { + showComposerResult(dataSource.setLocationPingStreamEnabled(name, enabled)) + loadSnapshot() + } + } + private fun setMocksEnabled(enabled: Boolean) { if (!mutableState.value.capabilities.mocks) { showComposerResult(InspectorCommandResult.Disabled(CAPABILITY_MOCKS)) From 31ef9928132a658eda20d638ac87087de1a81ae0 Mon Sep 17 00:00:00 2001 From: zakaria5729 Date: Mon, 26 Oct 2026 20:34:46 +0600 Subject: [PATCH 7/8] sample: send location pings from the views-java app Registers a "ride" stream and adds a Send location ping button. Each tap moves 120 m along a route and cycles through the four outcomes: 200 and 401 go through OkHttp, answered by mock rules, while dropped and offline are reported with DevConsole.recordLocationPing. --- .../sample/viewsjava/MainActivity.java | 5 + .../sample/viewsjava/SampleLocationPings.java | 165 ++++++++++++++++++ .../src/main/res/layout/activity_main.xml | 5 + 3 files changed, 175 insertions(+) create mode 100644 samples/views-java-app/src/main/java/io/devconsole/sample/viewsjava/SampleLocationPings.java diff --git a/samples/views-java-app/src/main/java/io/devconsole/sample/viewsjava/MainActivity.java b/samples/views-java-app/src/main/java/io/devconsole/sample/viewsjava/MainActivity.java index 5ca6fa1..1444d35 100644 --- a/samples/views-java-app/src/main/java/io/devconsole/sample/viewsjava/MainActivity.java +++ b/samples/views-java-app/src/main/java/io/devconsole/sample/viewsjava/MainActivity.java @@ -113,6 +113,7 @@ public final class MainActivity extends Activity { private CoroutineScope panelScope; private OkHttpClient client; + private SampleLocationPings sampleLocationPings; private OkHttpClient socketClient; private TextView lastResponse; private DevConsolePanelController panel; @@ -155,6 +156,7 @@ public final class MainActivity extends Activity { // engine DevConsole published at initialize, so no DevConsoleMockInterceptor line is needed. client = DevConsoleOkHttp.install(new OkHttpClient.Builder(), DevConsole.networkRecorder()) .build(); + sampleLocationPings = new SampleLocationPings(client); socketClient = new OkHttpClient(); // Mock rules are SESSION-scoped and dropped on every server restart -- restoreRunningSession // (re)installs it on each Running transition instead, so a one-shot call here isn't needed. @@ -183,6 +185,8 @@ public final class MainActivity extends Activity { findViewById(R.id.btnSimulateFirebasePush).setOnClickListener(view -> simulateFirebasePush()); findViewById(R.id.btnReadFeatureFlag).setOnClickListener(view -> readFeatureFlag()); findViewById(R.id.btnToggleMockRule).setOnClickListener(view -> toggleMockRule()); + findViewById(R.id.btnSendLocationPing).setOnClickListener(view -> + ioExecutor.execute(() -> postResult(sampleLocationPings.sendNextPing()))); findViewById(R.id.btnCaptureScreenshot).setOnClickListener(view -> captureScreenshot()); findViewById(R.id.btnTriggerCrash).setOnClickListener(view -> triggerCrash()); findViewById(R.id.btnTriggerAnr).setOnClickListener(view -> triggerAnr()); @@ -236,6 +240,7 @@ private DevConsoleConfig buildConfig() { .addStateProvider(stateProvider) .addFeatureFlag(featureFlag) .editingCapabilities(editingCapabilities) + .locationPingTracking(SampleLocationPings.tracking()) // The floating button is not a Compose feature: OpenTriggerController attaches a // plain ImageView to the Activity's decorView, so an XML/Views host gets the same // draggable, translucent button a Compose host does. Enabled here to show that. diff --git a/samples/views-java-app/src/main/java/io/devconsole/sample/viewsjava/SampleLocationPings.java b/samples/views-java-app/src/main/java/io/devconsole/sample/viewsjava/SampleLocationPings.java new file mode 100644 index 0000000..45fb39c --- /dev/null +++ b/samples/views-java-app/src/main/java/io/devconsole/sample/viewsjava/SampleLocationPings.java @@ -0,0 +1,165 @@ +/** + * @author Zakaria + * @since 26/10/26 + */ +package io.devconsole.sample.viewsjava; + +import java.io.IOException; +import java.util.Collections; +import java.util.Locale; + +import io.devconsole.DevConsole; +import io.devconsole.locationping.LocationPingOutcome; +import io.devconsole.locationping.LocationPingSchema; +import io.devconsole.locationping.LocationPingStream; +import io.devconsole.locationping.LocationPingTracking; +import io.devconsole.mocks.MockAction; +import io.devconsole.mocks.MockRule; +import io.devconsole.mocks.MockScope; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; + +final class SampleLocationPings { + static final String STREAM_NAME = "ride"; + + private static final String PING_PATH = "/v1/rides/pings"; + private static final String PING_URL = "https://example.test" + PING_PATH; + private static final String STATUS_HEADER = "X-Sample-Ping-Status"; + private static final String ACCEPTED_RULE_ID = "java-sample-ping-accepted"; + private static final String REJECTED_RULE_ID = "java-sample-ping-rejected"; + private static final String RIDE_ID = "sample-ride-42"; + private static final MediaType JSON = MediaType.get("application/json"); + private static final int OUTCOMES_IN_CYCLE = 4; + private static final double METERS_BETWEEN_PINGS = 120.0; + private static final long FIX_AGE_MILLIS = 850; + private static final double EARTH_RADIUS_METERS = 6_371_000.0; + private static final double[][] ROUTE = { + {23.793644, 90.410654}, {23.794589, 90.413653}, {23.794912, 90.414259}, + {23.793998, 90.414788}, {23.790881, 90.415958}, {23.787626, 90.416817}, + {23.785072, 90.417069}, {23.780999, 90.416727}, {23.780156, 90.416931}, + {23.778169, 90.416700}, + }; + + private final OkHttpClient client; + private int pingsSent; + + SampleLocationPings(OkHttpClient client) { + this.client = client; + } + + static LocationPingTracking tracking() { + return new LocationPingTracking( + Collections.singletonList(new LocationPingStream(STREAM_NAME, PING_PATH)), + new LocationPingSchema("pings", "lat", "lng", "device_time", "fix_time", "ride_ids", "app_state", "Ride"), + LocationPingTracking.DEFAULT_MAX_STORAGE_BYTES + ); + } + + static void installMockResponses() { + DevConsole.mockEngine().upsert(mockAnswering(REJECTED_RULE_ID, 1, + Collections.singletonMap(STATUS_HEADER, "401"), 401)); + DevConsole.mockEngine().upsert(mockAnswering(ACCEPTED_RULE_ID, 0, Collections.emptyMap(), 200)); + } + + String sendNextPing() { + int pingIndex = pingsSent++; + String body = pingBodyAt(pingIndex); + String outcome; + switch (pingIndex % OUTCOMES_IN_CYCLE) { + case 0: + outcome = sendThroughNetwork(body, false); + break; + case 1: + outcome = sendThroughNetwork(body, true); + break; + case 2: + DevConsole.recordLocationPing(PING_URL, body, LocationPingOutcome.droppedOnDevice()); + outcome = "dropped on device"; + break; + default: + DevConsole.recordLocationPing(PING_URL, body, LocationPingOutcome.noConnection()); + outcome = "not sent, offline"; + break; + } + String recording = DevConsole.isLocationPingTrackingEnabled(STREAM_NAME) + ? "recorded" + : "not recorded -- turn on the ride stream in More → Location pings"; + return "Location ping #" + (pingIndex + 1) + ": " + outcome + " (" + recording + ")"; + } + + private String sendThroughNetwork(String body, boolean rejected) { + installMockResponses(); + Request.Builder request = new Request.Builder().url(PING_URL).post(RequestBody.create(body, JSON)); + if (rejected) request.header(STATUS_HEADER, "401"); + try (Response response = client.newCall(request.build()).execute()) { + return "HTTP " + response.code(); + } catch (IOException error) { + return "failed: " + error.getMessage(); + } + } + + private String pingBodyAt(int pingIndex) { + long deviceTime = System.currentTimeMillis(); + double[] position = positionAfter(pingIndex * METERS_BETWEEN_PINGS); + String appState = pingIndex % 2 == 0 ? "FOREGROUND" : "BACKGROUND"; + return String.format(Locale.US, + "{\"ride_ids\":[\"%s\"],\"app_state\":\"%s\",\"battery\":%d,\"pings\":[{\"lat\":%.6f,\"lng\":%.6f," + + "\"device_time\":%d,\"fix_time\":%d,\"accuracy\":4.3,\"speed\":7.1}]}", + RIDE_ID, appState, 100 - pingIndex % 100, position[0], position[1], deviceTime, + deviceTime - FIX_AGE_MILLIS); + } + + private static double[] positionAfter(double meters) { + double routeLength = routeLengthMeters(); + double lap = routeLength * 2; + double inLap = meters % lap; + double metersLeft = inLap <= routeLength ? inLap : lap - inLap; + for (int leg = 0; leg < ROUTE.length - 1; leg++) { + double legLength = metersBetween(ROUTE[leg], ROUTE[leg + 1]); + if (metersLeft <= legLength) { + double share = legLength == 0 ? 0 : metersLeft / legLength; + return new double[]{ + ROUTE[leg][0] + (ROUTE[leg + 1][0] - ROUTE[leg][0]) * share, + ROUTE[leg][1] + (ROUTE[leg + 1][1] - ROUTE[leg][1]) * share, + }; + } + metersLeft -= legLength; + } + return ROUTE[ROUTE.length - 1]; + } + + private static double routeLengthMeters() { + double total = 0; + for (int leg = 0; leg < ROUTE.length - 1; leg++) total += metersBetween(ROUTE[leg], ROUTE[leg + 1]); + return total; + } + + private static double metersBetween(double[] from, double[] to) { + double latDelta = Math.toRadians(to[0] - from[0]); + double lngDelta = Math.toRadians(to[1] - from[1]); + double haversine = Math.sin(latDelta / 2) * Math.sin(latDelta / 2) + + Math.cos(Math.toRadians(from[0])) * Math.cos(Math.toRadians(to[0])) + * Math.sin(lngDelta / 2) * Math.sin(lngDelta / 2); + return EARTH_RADIUS_METERS * 2 * Math.atan2(Math.sqrt(haversine), Math.sqrt(1 - haversine)); + } + + private static MockRule mockAnswering(String id, int priority, java.util.Map headers, int status) { + return new MockRule( + id, + priority, + "POST", + null, + null, + PING_PATH, + Collections.emptyMap(), + headers, + null, + MockScope.SESSION, + new MockAction.StaticResponse(status, "{\"accepted\":" + (status == 200) + "}", Collections.emptyMap()), + null + ); + } +} diff --git a/samples/views-java-app/src/main/res/layout/activity_main.xml b/samples/views-java-app/src/main/res/layout/activity_main.xml index b04282e..c7344d9 100644 --- a/samples/views-java-app/src/main/res/layout/activity_main.xml +++ b/samples/views-java-app/src/main/res/layout/activity_main.xml @@ -63,6 +63,11 @@ style="@style/DevConsoleButton" android:text="Send mocked request" /> +