Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/detekt-baseline-debug.xml
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@
<ID>InjectDispatcher:RewardsKeeper.kt:RewardsKeeper$IO</ID>
<ID>InjectDispatcher:ShareScreen.kt:IO</ID>
<ID>InjectDispatcher:StrapService.kt:StrapService$Default</ID>
<ID>InjectDispatcher:SummarySections.kt:IO</ID>
<ID>InjectDispatcher:ZeppCloud.kt:ZeppCloud$IO</ID>
<ID>LambdaParameterEventTrailing:ActivityDetail.kt:onPick: (Int?) -&gt; Unit</ID>
<ID>LambdaParameterEventTrailing:ChooseScreen.kt:onChange: (String) -&gt; Unit</ID>
Expand Down
1 change: 1 addition & 0 deletions app/detekt-baseline-release.xml
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@
<ID>InjectDispatcher:RewardsKeeper.kt:RewardsKeeper$IO</ID>
<ID>InjectDispatcher:ShareScreen.kt:IO</ID>
<ID>InjectDispatcher:StrapService.kt:StrapService$Default</ID>
<ID>InjectDispatcher:SummarySections.kt:IO</ID>
<ID>InjectDispatcher:ZeppCloud.kt:ZeppCloud$IO</ID>
<ID>LambdaParameterEventTrailing:ActivityDetail.kt:onPick: (Int?) -&gt; Unit</ID>
<ID>LambdaParameterEventTrailing:ChooseScreen.kt:onChange: (String) -&gt; Unit</ID>
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/kotlin/org/openstrap/app/data/Route.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
34 changes: 34 additions & 0 deletions app/src/main/kotlin/org/openstrap/app/export/GpxShare.kt
Original file line number Diff line number Diff line change
@@ -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))
}
}
61 changes: 61 additions & 0 deletions app/src/main/kotlin/org/openstrap/app/export/GpxWriter.kt
Original file line number Diff line number Diff line change
@@ -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<Route.Point>, heartRate: List<Pair<Long, Int>>, pauses: List<LongRange> = 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("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
sb.append("<gpx version=\"1.1\" creator=\"OpenStrap\" xmlns=\"http://www.topografix.com/GPX/1/1\" ")
sb.append("xmlns:gpxtpx=\"http://www.garmin.com/xmlschemas/TrackPointExtension/v1\">\n")
sb.append("<trk><name>").append(escape(name)).append("</name>\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("</trkseg>\n")
sb.append("<trkseg>\n")
}
prev = p
gap = false
sb.append("<trkpt lat=\"").append(coord(p.lat)).append("\" lon=\"").append(coord(p.lon)).append("\">")
p.altitude?.let { sb.append("<ele>").append(String.format(Locale.ROOT, "%.1f", it)).append("</ele>") }
sb.append("<time>").append(Instant.ofEpochSecond(p.t)).append("</time>")
hrAt(p.t)?.let {
sb.append("<extensions><gpxtpx:TrackPointExtension><gpxtpx:hr>").append(it)
sb.append("</gpxtpx:hr></gpxtpx:TrackPointExtension></extensions>")
}
sb.append("</trkpt>\n")
}
if (prev != null) sb.append("</trkseg>\n")
sb.append("</trk>\n</gpx>\n")
return sb.toString()
}

private fun coord(v: Double) = String.format(Locale.ROOT, "%.7f", v)

private fun escape(s: String) = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;")
}
25 changes: 24 additions & 1 deletion app/src/main/kotlin/org/openstrap/app/ui/glow/SummarySections.kt
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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)
}
}
Expand Down
4 changes: 4 additions & 0 deletions app/src/main/res/values/strings_glow_summary.xml
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@

<!-- Title of the card with the workout's route on a map. One word. -->
<string name="glow_summary_route">Route</string>
<!-- Button on the route card: hands the route to another app as a GPX file. One word. -->
<string name="glow_summary_export">Export</string>
<!-- Toast when the route's file couldn't be written. -->
<string name="glow_summary_export_failed">Couldn\'t export the route</string>
<!-- Beside the route's title: how far it climbed, in metres. -->
<string name="glow_summary_climb">Climb <xliff:g id="meters" example="42">%1$d</xliff:g> m</string>
<!-- Content description of the route card's map: tapping it opens the map full screen. -->
Expand Down
41 changes: 41 additions & 0 deletions app/src/test/kotlin/org/openstrap/app/export/GpxShareTest.kt
Original file line number Diff line number Diff line change
@@ -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", "<gpx/>")
assertNotNull(uri)
assertEquals(context.packageName + ".share", uri!!.authority)
assertEquals("<gpx/>", read(uri))
}

@Test fun `a second export replaces the first`() {
GpxShare.forSharing(context, "run.gpx", "<gpx>first and longer</gpx>")
val uri = GpxShare.forSharing(context, "run.gpx", "<gpx>2</gpx>")
assertEquals("<gpx>2</gpx>", read(uri!!))
}
}
87 changes: 87 additions & 0 deletions app/src/test/kotlin/org/openstrap/app/export/GpxWriterTest.kt
Original file line number Diff line number Diff line change
@@ -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)
}
}
1 change: 1 addition & 0 deletions docs/privacy.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down