diff --git a/app/detekt-baseline-debug.xml b/app/detekt-baseline-debug.xml
index 617a3564..d2cfe78b 100644
--- a/app/detekt-baseline-debug.xml
+++ b/app/detekt-baseline-debug.xml
@@ -175,6 +175,7 @@
InjectDispatcher:RewardsKeeper.kt:RewardsKeeper$IOInjectDispatcher:ShareScreen.kt:IOInjectDispatcher:StrapService.kt:StrapService$Default
+ InjectDispatcher:SummarySections.kt:IOInjectDispatcher:ZeppCloud.kt:ZeppCloud$IOLambdaParameterEventTrailing:ActivityDetail.kt:onPick: (Int?) -> UnitLambdaParameterEventTrailing:ChooseScreen.kt:onChange: (String) -> Unit
diff --git a/app/detekt-baseline-release.xml b/app/detekt-baseline-release.xml
index 707ca60f..6e23d9dc 100644
--- a/app/detekt-baseline-release.xml
+++ b/app/detekt-baseline-release.xml
@@ -177,6 +177,7 @@
InjectDispatcher:RewardsKeeper.kt:RewardsKeeper$IOInjectDispatcher:ShareScreen.kt:IOInjectDispatcher:StrapService.kt:StrapService$Default
+ InjectDispatcher:SummarySections.kt:IOInjectDispatcher:ZeppCloud.kt:ZeppCloud$IOLambdaParameterEventTrailing:ActivityDetail.kt:onPick: (Int?) -> UnitLambdaParameterEventTrailing:ChooseScreen.kt:onChange: (String) -> Unit
diff --git a/app/src/main/kotlin/org/openstrap/app/data/Route.kt b/app/src/main/kotlin/org/openstrap/app/data/Route.kt
index 7fa3352e..b9edb111 100644
--- a/app/src/main/kotlin/org/openstrap/app/data/Route.kt
+++ b/app/src/main/kotlin/org/openstrap/app/data/Route.kt
@@ -417,5 +417,5 @@ object Route {
return out.filter { it.first.size >= 2 }
}
- private const val MAX_HR_GAP_S = 30L
+ const val MAX_HR_GAP_S = 30L
}
diff --git a/app/src/main/kotlin/org/openstrap/app/export/GpxShare.kt b/app/src/main/kotlin/org/openstrap/app/export/GpxShare.kt
new file mode 100644
index 00000000..181321f8
--- /dev/null
+++ b/app/src/main/kotlin/org/openstrap/app/export/GpxShare.kt
@@ -0,0 +1,34 @@
+package org.openstrap.app.export
+
+import android.content.ClipData
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+import android.util.Log
+import androidx.core.content.FileProvider
+import java.io.File
+
+private const val TAG = "GpxShare"
+
+// The FileProvider's authority after the package name, as in the manifest; export/ may not reach ui/ for StoryFiles's copy.
+private const val AUTHORITY_SUFFIX = ".share"
+
+/** A workout's GPX as a cached file another app can read for a moment, through the share FileProvider. */
+internal object GpxShare {
+ /** Named like the story picture: after the workout's start (epoch seconds). */
+ fun fileName(workoutStart: Long) = "OpenStrap_$workoutStart.gpx"
+
+ /** [gpx] written over [fileName] in the share cache; null when it can't be written. Blocks on the file write. */
+ fun forSharing(context: Context, fileName: String, gpx: String): Uri? = runCatching {
+ val file = File(File(context.cacheDir, "share").apply { mkdirs() }, fileName)
+ file.writeText(gpx)
+ FileProvider.getUriForFile(context, context.packageName + AUTHORITY_SUFFIX, file)
+ }.onFailure { Log.w(TAG, "writing the route to share failed", it) }.getOrNull()
+
+ /** Opens the share sheet for [uri]. */
+ fun send(context: Context, uri: Uri) {
+ val send = Intent(Intent.ACTION_SEND).setType("application/gpx+xml").putExtra(Intent.EXTRA_STREAM, uri)
+ .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION).also { it.clipData = ClipData.newRawUri(null, uri) }
+ context.startActivity(Intent.createChooser(send, null))
+ }
+}
diff --git a/app/src/main/kotlin/org/openstrap/app/export/GpxWriter.kt b/app/src/main/kotlin/org/openstrap/app/export/GpxWriter.kt
new file mode 100644
index 00000000..2aafb4fe
--- /dev/null
+++ b/app/src/main/kotlin/org/openstrap/app/export/GpxWriter.kt
@@ -0,0 +1,61 @@
+package org.openstrap.app.export
+
+import org.openstrap.app.data.Route
+import java.time.Instant
+import java.util.Locale
+import kotlin.math.abs
+
+/** A workout's route as GPX 1.1 with Garmin's heart-rate extension, for sharing to other apps. */
+object GpxWriter {
+ /**
+ * [points] go through [Route.track], the line the map draws; a pause starts a new segment. [heartRate] is (epoch
+ * seconds, bpm) ascending. `ele` is GPS altitude as recorded (WGS84 ellipsoid, not sea level); Strava and similar
+ * services re-derive elevation.
+ */
+ fun write(name: String, points: List, heartRate: List>, pauses: List = emptyList()): String {
+ val times = heartRate.map { it.first }
+ fun hrAt(t: Long): Int? {
+ val i = times.binarySearch(t).let { if (it < 0) -it - 1 else it }
+ val near = listOf(i - 1, i).filter { it in heartRate.indices }
+ .minByOrNull { abs(heartRate[it].first - t) } ?: return null
+ return heartRate[near].takeIf { abs(it.first - t) <= Route.MAX_HR_GAP_S }?.second
+ }
+ val sb = StringBuilder()
+ sb.append("\n")
+ sb.append("\n")
+ sb.append("").append(escape(name)).append("\n")
+ // Fixes strictly inside a pause are left out, so no line runs through it; a pause ends a segment.
+ var prev: Route.Point? = null
+ var gap = false
+ Route.track(points).forEach { p ->
+ if (pauses.any { p.t > it.first && p.t < it.last }) {
+ gap = true
+ return@forEach
+ }
+ val last = prev
+ val pausedBetween = last != null && pauses.any { it.first < p.t && it.last > last.t }
+ if (last == null || gap || pausedBetween) {
+ if (last != null) sb.append("\n")
+ sb.append("\n")
+ }
+ prev = p
+ gap = false
+ sb.append("")
+ p.altitude?.let { sb.append("").append(String.format(Locale.ROOT, "%.1f", it)).append("") }
+ sb.append("")
+ hrAt(p.t)?.let {
+ sb.append("").append(it)
+ sb.append("")
+ }
+ sb.append("\n")
+ }
+ if (prev != null) sb.append("\n")
+ sb.append("\n\n")
+ return sb.toString()
+ }
+
+ private fun coord(v: Double) = String.format(Locale.ROOT, "%.7f", v)
+
+ private fun escape(s: String) = s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """)
+}
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/SummarySections.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/SummarySections.kt
index 60c0649a..5adfee5d 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/glow/SummarySections.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/SummarySections.kt
@@ -1,6 +1,14 @@
package org.openstrap.app.ui.glow
+import android.widget.Toast
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.ui.platform.LocalContext
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
import org.openstrap.app.R
+import org.openstrap.app.export.GpxShare
+import org.openstrap.app.export.GpxWriter
import org.openstrap.app.data.Weeks
import org.openstrap.app.i18n.Strings
import androidx.compose.ui.res.pluralStringResource
@@ -258,9 +266,24 @@ internal fun FamilySection(
@Composable
private fun RouteCard(summary: PhoneSummary, onOpenMap: () -> Unit) {
if (!Route.mappable(summary.route)) return
+ val context = LocalContext.current
+ val scope = rememberCoroutineScope()
+ val failed = stringResource(R.string.glow_summary_export_failed)
+ val name = summary.analysis.sportName
+ fun export() {
+ scope.launch {
+ val uri = withContext(Dispatchers.IO) {
+ val gpx = GpxWriter.write(name, summary.route, summary.history, summary.pauses)
+ GpxShare.forSharing(context, GpxShare.fileName(summary.analysis.workout.start), gpx)
+ }
+ if (uri != null) GpxShare.send(context, uri) else Toast.makeText(context, failed, Toast.LENGTH_SHORT).show()
+ }
+ }
PictureCard(MetricColors.steps, Modifier.fillMaxWidth()) {
val climb = Route.climb(summary.route)?.let { stringResource(R.string.glow_summary_climb, Math.round(it)) }
- EdgeTitle(stringResource(R.string.glow_summary_route), climb)
+ EdgeTitle(stringResource(R.string.glow_summary_route), climb, action = {
+ IconPill(stringResource(R.string.glow_summary_export), onClick = { export() }, icon = AppIcons.DownloadSimple, height = 36.dp)
+ })
RouteMap(summary, Modifier.padding(top = 12.dp), onOpen = onOpenMap)
}
}
diff --git a/app/src/main/res/values/strings_glow_summary.xml b/app/src/main/res/values/strings_glow_summary.xml
index 27e8c3a7..bfa1ad03 100644
--- a/app/src/main/res/values/strings_glow_summary.xml
+++ b/app/src/main/res/values/strings_glow_summary.xml
@@ -93,6 +93,10 @@
Route
+
+ Export
+
+ Couldn\'t export the routeClimb %1$d m
diff --git a/app/src/test/kotlin/org/openstrap/app/export/GpxShareTest.kt b/app/src/test/kotlin/org/openstrap/app/export/GpxShareTest.kt
new file mode 100644
index 00000000..8de1a06e
--- /dev/null
+++ b/app/src/test/kotlin/org/openstrap/app/export/GpxShareTest.kt
@@ -0,0 +1,41 @@
+package org.openstrap.app.export
+
+import android.content.Context
+import androidx.core.content.FileProvider
+import androidx.test.core.app.ApplicationProvider
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotNull
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+
+/** The GPX file a workout's Export hands to the share sheet: its name, and the cached copy behind the FileProvider. */
+@RunWith(RobolectricTestRunner::class)
+class GpxShareTest {
+ private val context: Context = ApplicationProvider.getApplicationContext()
+
+ // FileProvider keeps its roots per authority for the process, and Robolectric gives each test its own cache dir.
+ @Before fun forgetProviderRoots() {
+ (FileProvider::class.java.getDeclaredField("sCache").apply { isAccessible = true }.get(null) as MutableMap<*, *>).clear()
+ }
+
+ private fun read(uri: android.net.Uri) = context.contentResolver.openInputStream(uri)!!.use { it.readBytes().decodeToString() }
+
+ @Test fun `fileName names the file after the workout`() {
+ assertEquals("OpenStrap_1792000000.gpx", GpxShare.fileName(1_792_000_000))
+ }
+
+ @Test fun `forSharing writes the text and returns a content uri`() {
+ val uri = GpxShare.forSharing(context, "run.gpx", "")
+ assertNotNull(uri)
+ assertEquals(context.packageName + ".share", uri!!.authority)
+ assertEquals("", read(uri))
+ }
+
+ @Test fun `a second export replaces the first`() {
+ GpxShare.forSharing(context, "run.gpx", "first and longer")
+ val uri = GpxShare.forSharing(context, "run.gpx", "2")
+ assertEquals("2", read(uri!!))
+ }
+}
diff --git a/app/src/test/kotlin/org/openstrap/app/export/GpxWriterTest.kt b/app/src/test/kotlin/org/openstrap/app/export/GpxWriterTest.kt
new file mode 100644
index 00000000..381a79bc
--- /dev/null
+++ b/app/src/test/kotlin/org/openstrap/app/export/GpxWriterTest.kt
@@ -0,0 +1,87 @@
+package org.openstrap.app.export
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.openstrap.app.data.Route
+import org.w3c.dom.Document
+import org.w3c.dom.Element
+import java.io.ByteArrayInputStream
+import java.time.Instant
+import java.util.Locale
+import javax.xml.parsers.DocumentBuilderFactory
+
+class GpxWriterTest {
+ private val start = 1_700_000_000L
+
+ private fun east(t: Long, metres: Double, altitude: Double? = null) = Route.Point(t, 0.0, metres / 111_195.0, 5f, altitude = altitude)
+
+ /** A steady 3 m/s run east for 100 s, one fix a second. */
+ private fun run(altitude: Double? = null) = (0..100).map { east(start + it, it * 3.0, altitude) }
+
+ private fun parse(xml: String): Document = DocumentBuilderFactory.newInstance().apply { isNamespaceAware = true }
+ .newDocumentBuilder().parse(ByteArrayInputStream(xml.toByteArray()))
+
+ private fun Document.all(tag: String) = getElementsByTagNameNS("*", tag)
+
+ @Test fun `a run is one segment of timed points`() {
+ val doc = parse(GpxWriter.write("Run", run(), emptyList()))
+ assertEquals("1.1", doc.documentElement.getAttribute("version"))
+ assertEquals(1, doc.all("trk").length)
+ assertEquals(1, doc.all("trkseg").length)
+ assertTrue(doc.all("trkpt").length > 50)
+ val first = Route.track(run()).first()
+ val time = (doc.all("trkpt").item(0) as Element).getElementsByTagNameNS("*", "time").item(0).textContent
+ assertEquals(Instant.ofEpochSecond(first.t).toString(), time)
+ }
+
+ @Test fun `a pause splits the track in two segments`() {
+ val doc = parse(GpxWriter.write("Run", run(), emptyList(), listOf(start + 40..start + 60)))
+ assertEquals(2, doc.all("trkseg").length)
+ val times = (0 until doc.all("time").length).map { Instant.parse(doc.all("time").item(it).textContent).epochSecond }
+ assertTrue(times.isNotEmpty() && times.none { it > start + 40 && it < start + 60 })
+ assertTrue(times.any { it <= start + 40 } && times.any { it >= start + 60 })
+ }
+
+ @Test fun `a pause between two fixes still splits the track`() {
+ val gap = (0..40).map { east(start + it, it * 3.0) } + (42..100).map { east(start + it, it * 3.0) }
+ val doc = parse(GpxWriter.write("Run", gap, emptyList(), listOf(start + 40..start + 42)))
+ assertEquals(2, doc.all("trkseg").length)
+ }
+
+ @Test fun `heart rate rides along when a reading is near`() {
+ val hr = (0L..50L step 5).map { start + it to 140 }
+ val pts = parse(GpxWriter.write("Run", run(), hr)).all("trkpt")
+ val first = pts.item(0) as Element
+ assertEquals("140", first.getElementsByTagNameNS("*", "hr").item(0).textContent)
+ val last = pts.item(pts.length - 1) as Element
+ assertEquals(0, last.getElementsByTagNameNS("*", "extensions").length)
+ }
+
+ @Test fun `altitude appears only when the fix has one`() {
+ assertTrue(parse(GpxWriter.write("Run", run(12.3), emptyList())).all("ele").item(0).textContent == "12.3")
+ assertEquals(0, parse(GpxWriter.write("Run", run(), emptyList())).all("ele").length)
+ }
+
+ @Test fun `a name with markup is escaped`() {
+ val name = "Run & \"Hill\" <1>"
+ assertEquals(name, parse(GpxWriter.write(name, run(), emptyList())).all("name").item(0).textContent)
+ }
+
+ @Test fun `coordinates use a dot whatever the locale`() {
+ val saved = Locale.getDefault()
+ Locale.setDefault(Locale.GERMANY)
+ try {
+ val xml = GpxWriter.write("Run", run(), emptyList())
+ assertTrue(xml.contains("lat=\"0.0000000\""))
+ assertFalse(Regex("""(lat|lon)="[^"]*,""").containsMatchIn(xml))
+ } finally {
+ Locale.setDefault(saved)
+ }
+ }
+
+ @Test fun `no route is a valid document with no points`() {
+ assertEquals(0, parse(GpxWriter.write("Run", emptyList(), emptyList())).all("trkpt").length)
+ }
+}
diff --git a/docs/privacy.md b/docs/privacy.md
index 318495b4..bbe8bfd2 100644
--- a/docs/privacy.md
+++ b/docs/privacy.md
@@ -9,6 +9,7 @@ unstrap goes online for your Zepp account, for firmware and for workout maps onl
- **Sign in with Zepp** opens Zepp's own sign-in page (watchface.zepp.com) in an in-app browser. unstrap never sees your password. After sign-in it reads the app token and user ID from the page's cookies. It then makes one request to Zepp's device list (`GET users/{userId}/devices` on `api-mifit*.zepp.com`) and shows you the strap's Bluetooth address and auth key to confirm. It saves the token and user ID for firmware checks and clears the Zepp cookies.
- **Check for update** sends your Zepp token, user ID, and the strap's firmware version, hardware version and serial number to the update server you set. **Download** fetches the image from the URL that server returns.
- **Workout maps** load map tiles from [OpenFreeMap](https://openfreemap.org) (`tiles.openfreemap.org`), only when you open the map of a GPS workout. No account, API key or cookies. Like any tile server it sees roughly where the map is and your IP address. **Route only** on the map page loads no tiles at all. Your route itself never leaves the phone.
+- **Export route** on a GPS workout's summary hands a GPX file to the app you pick in the share sheet. OpenStrap itself sends nothing.
- **New versions of unstrap.** Once a day, when the phone has a network, unstrap reads the list of its releases from GitHub (`GET api.github.com/repos/sayed0am/unstrap/releases`), and again when you tap **Check now**. The request carries no account, token or ID, only unstrap's version in the user agent. Like any server, GitHub sees your IP address. When a newer release is out, a notification says so once. Turn it off with **Check every day** in **You → Updates**.
- **Installing an update** downloads that release's APK from GitHub, only when you tap it. unstrap checks it against the SHA-256 GitHub lists for it, and that it's unstrap signed with the same key, before handing it to Android to install.