Skip to content
Merged
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
22 changes: 22 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,20 @@ uses semantic versioning (`MAJOR.MINOR.PATCH`).

### Added

- **Show technical error details.** Settings, About gains an Error reporting
switch, off by default. On, a failed request says which status came back and
what the server actually said, instead of a short summary: "[404] Field not
found" rather than "Not found", and a network failure names the exception
behind it. It sits on About because that is the screen you already open to
copy a version and a commit into a bug report. The web app has had the same
setting for a while, and turning it on here is remembered for your other
Android devices; the two clients keep their own answer, since a status code
in a toast is least wanted on a phone.

The setting also applies when the server cannot be reached at all, which is
when it is most often wanted: it is kept on the device, not only on the
account, so it does not depend on the request that is failing.

- **Slider custom fields.** A field can now be a slider, matching the type the
server and the web app gained: either a labelled one from 0 to 100 between
two words of your choosing ("Drained" to "Wired", read as a percentage), or a
Expand All @@ -28,6 +42,14 @@ uses semantic versioning (`MAJOR.MINOR.PATCH`).

### Fixed

- **Sharing and custom fields no longer explain failures their own way.** The
screens that tell three kinds of refusal apart, so they can ask for a
password or say publishing is off, carried a second set of wordings for
everything else. So the same status could read differently depending on
which call had failed, and the new error-details setting did nothing on
those screens. They now share one formatter, keeping the server's own prose
where it is the useful part.

- **Image avatars now appear on the watch, on instances that serve files
themselves.** A member with an uploaded avatar showed nothing where their
picture should be: no image, and not even the initials circle, on Currently
Expand Down
28 changes: 28 additions & 0 deletions sheaf/app/src/main/java/systems/lupine/sheaf/SheafApplication.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,15 @@ import androidx.work.Configuration
import coil.ImageLoader
import coil.ImageLoaderFactory
import dagger.hilt.android.HiltAndroidApp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import systems.lupine.sheaf.data.repository.PreferencesRepository
import systems.lupine.sheaf.lock.AppLockManager
import systems.lupine.sheaf.notification.FrontNotificationHelper
import systems.lupine.sheaf.push.PushNotificationChannels
import systems.lupine.sheaf.util.TechnicalErrors
import javax.inject.Inject

@HiltAndroidApp
Expand All @@ -19,6 +25,7 @@ class SheafApplication : Application(), ImageLoaderFactory, Configuration.Provid
@Inject lateinit var imageLoader: ImageLoader
@Inject lateinit var workerFactory: HiltWorkerFactory
@Inject lateinit var lockManager: AppLockManager
@Inject lateinit var prefs: PreferencesRepository

override val workManagerConfiguration: Configuration
get() = Configuration.Builder().setWorkerFactory(workerFactory).build()
Expand All @@ -28,6 +35,27 @@ class SheafApplication : Application(), ImageLoaderFactory, Configuration.Provid
notificationHelper.createChannel()
pushChannels.register()
lockManager.start()
seedTechnicalErrorsPreference()
}

/**
* Put the stored "show technical error details" choice where error
* formatting can see it, before anything has a chance to fail.
*
* Read from the device rather than the account on purpose. The account's
* copy arrives with the first successful load, and the failures this
* preference exists to explain are exactly the ones where that load does
* not happen: a preference that has to be fetched before it applies is off
* precisely when somebody is trying to find out why nothing is loading.
*
* Collected for the life of the process, not read once, so a change made
* on this device, or adopted from the account mid-session, takes effect on
* the next error rather than the next launch.
*/
private fun seedTechnicalErrorsPreference() {
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
prefs.showTechnicalErrors.collect { TechnicalErrors.set(it) }
}
}

override fun newImageLoader(): ImageLoader = imageLoader
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ class PreferencesRepository @Inject constructor(
val KEY_CF_CLIENT_SECRET = stringPreferencesKey("cf_client_secret")
val KEY_FILE_CDN_BASE = stringPreferencesKey("file_cdn_base")
val KEY_APP_LOCK = booleanPreferencesKey("app_lock")
// "Show technical error details". Kept on the device as well as in the
// account's client settings, because the one time it matters most is
// when the server cannot be reached, and a preference that has to be
// fetched is a preference that is off exactly when it is wanted.
val KEY_TECHNICAL_ERRORS = booleanPreferencesKey("show_technical_errors")
// Mirrors the backend's sheaf_trusted_device cookie. We store it
// verbatim plus its expiry-millis so the CookieJar can drop it once
// expired without a server round-trip.
Expand Down Expand Up @@ -138,6 +143,10 @@ class PreferencesRepository @Inject constructor(
val cfClientId: Flow<String?> = context.dataStore.data.map { it[KEY_CF_CLIENT_ID] }
val cfClientSecret: Flow<String?> = context.dataStore.data.map { it[KEY_CF_CLIENT_SECRET] }
val appLockEnabled: Flow<Boolean> = context.dataStore.data.map { it[KEY_APP_LOCK] ?: false }

/** Off by default: most people do not want a status code in a toast. */
val showTechnicalErrors: Flow<Boolean> =
context.dataStore.data.map { it[KEY_TECHNICAL_ERRORS] ?: false }
val historyView: Flow<String> = context.dataStore.data.map { it[KEY_HISTORY_VIEW] ?: "infinite" }
val historyPageSize: Flow<Int> = context.dataStore.data.map { it[KEY_HISTORY_PAGE_SIZE] ?: 50 }
val accountTimezone: Flow<String?> = context.dataStore.data.map { it[KEY_ACCOUNT_TIMEZONE] }
Expand Down Expand Up @@ -257,6 +266,19 @@ class PreferencesRepository @Inject constructor(
context.dataStore.edit { it[KEY_APP_LOCK] = enabled }
}

/**
* Store the preference and update the copy error formatting reads.
*
* Both, always, and in that order: the flow is the durable value and
* [TechnicalErrors] is what `toUserMessage` can actually see. Writing only
* the first would leave the next error formatted by the old setting until
* something restarted the process.
*/
suspend fun saveShowTechnicalErrors(enabled: Boolean) {
context.dataStore.edit { it[KEY_TECHNICAL_ERRORS] = enabled }
systems.lupine.sheaf.util.TechnicalErrors.set(enabled)
}

suspend fun saveHistoryView(view: String) {
context.dataStore.edit { it[KEY_HISTORY_VIEW] = view }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,16 @@ class HomeViewModel @Inject constructor(
_state.update { it.copy(user = u) }
}
}
launch {
// Adopt the account's "show technical error details"
// choice, if it has one. Done on the load that already
// fetches this blob, so it costs no extra round-trip, and
// early enough that the first error of the session is
// formatted the way the user asked for.
systems.lupine.sheaf.util.TechnicalErrors
.fromClientSettings(clientSettingsD.await().getOrNull()?.settings)
?.let { prefs.saveShowTechnicalErrors(it) }
}
launch {
val announcements = announcementsD.await().getOrNull()
// Server-side "don't show again" set. Merge (union) with
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package systems.lupine.sheaf.ui.settings

import android.content.ClipData
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
Expand All @@ -19,6 +20,7 @@ import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
Expand Down Expand Up @@ -54,6 +56,7 @@ fun AboutScreen(
) {
val serverVersion by viewModel.serverVersion.collectAsState()
val baseUrl by viewModel.baseUrl.collectAsState()
val showTechnicalErrors by viewModel.showTechnicalErrors.collectAsState()

Scaffold(
contentWindowInsets = WindowInsets(0),
Expand Down Expand Up @@ -120,7 +123,58 @@ fun AboutScreen(
version.buildTime?.takeIf { it.isNotBlank() }?.let { DetailRow("Built", it) }
version.mode?.takeIf { it.isNotBlank() }?.let { DetailRow("Mode", it) }
}

// Filed here rather than under its own settings category, which is
// where the web app keeps it. This screen is already the one
// somebody opens to put a build and a server into a bug report,
// and the setting changes what a bug report can say.
//
// Not the Debug Menu, despite the name fitting: that row is behind
// BuildConfig.DEBUG, and the people who need this are on release
// builds, reporting something that went wrong on their own phone.
SectionHeader("Error reporting", modifier = Modifier.padding(horizontal = 16.dp))
TechnicalErrorsRow(
checked = showTechnicalErrors,
onCheckedChange = viewModel::setShowTechnicalErrors,
)
}
}
}

/**
* The "show me what actually went wrong" switch.
*
* Off by default, and worth keeping that way for most people: a status code in
* a toast is noise to somebody who cannot act on it. On, it is the difference
* between "Something went wrong" and a line that says which call failed and
* what the server said about it.
*/
@Composable
private fun TechnicalErrorsRow(
checked: Boolean,
onCheckedChange: (Boolean) -> Unit,
) {
Row(
modifier = Modifier
.fillMaxWidth()
.clickable { onCheckedChange(!checked) }
.padding(start = 16.dp, end = 16.dp, top = 12.dp, bottom = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
Text("Show technical error details", style = MaterialTheme.typography.bodyLarge)
Text(
"When something goes wrong, show the status code and the server's exact " +
"message instead of a short summary. Useful for reporting a problem; " +
"noisy day to day.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Switch(checked = checked, onCheckedChange = onCheckedChange)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,18 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import systems.lupine.sheaf.data.api.SheafApiService
import systems.lupine.sheaf.data.model.ClientSettingsBody
import systems.lupine.sheaf.data.model.ServerVersion
import systems.lupine.sheaf.data.repository.PreferencesRepository
import systems.lupine.sheaf.data.repository.ServerInfoRepository
import systems.lupine.sheaf.util.TechnicalErrors
import javax.inject.Inject

// Same blob SettingsViewModel and HomeViewModel write to; the client id is the
// platform, so every Android device on the account shares one set.
private const val CLIENT_ID = "android"

/**
* What About needs beyond `BuildConfig`: which instance this is and what it is
* running.
Expand All @@ -24,7 +31,8 @@ import javax.inject.Inject
@HiltViewModel
class AboutViewModel @Inject constructor(
private val serverInfo: ServerInfoRepository,
prefs: PreferencesRepository,
private val prefs: PreferencesRepository,
private val api: SheafApiService,
) : ViewModel() {

val serverVersion: StateFlow<ServerVersion?> = serverInfo.version
Expand All @@ -33,9 +41,33 @@ class AboutViewModel @Inject constructor(
.map { it.orEmpty() }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "")

val showTechnicalErrors: StateFlow<Boolean> = prefs.showTechnicalErrors
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)

init { refresh() }

fun refresh() {
viewModelScope.launch { serverInfo.ensureLoaded() }
}

/**
* Apply the choice here, then tell the account.
*
* Local first and unconditionally: this is the one preference whose whole
* job is to explain a failing request, so it cannot depend on a request
* succeeding. The PATCH is best-effort and carries only its own nested
* group, so a failure leaves the device's setting in force and nothing
* else in the blob disturbed.
*/
fun setShowTechnicalErrors(enabled: Boolean) {
viewModelScope.launch {
prefs.saveShowTechnicalErrors(enabled)
runCatching {
api.patchClientSettings(
CLIENT_ID,
ClientSettingsBody(TechnicalErrors.toClientSettings(enabled)),
)
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package systems.lupine.sheaf.ui.sharing

import com.squareup.moshi.Moshi
import retrofit2.HttpException
import systems.lupine.sheaf.util.errorDetail
import systems.lupine.sheaf.util.toUserMessage

/**
Expand Down Expand Up @@ -53,37 +53,32 @@ fun Throwable.toShareError(fallback: String): ShareError {
code() == 403 && detail != null && "turned off on this instance" in detail ->
ShareError.PublishingUnavailable(detail)
code() == 403 -> ShareError.BadCredentials(detail ?: "Incorrect password or authenticator code")
else -> ShareError.Other(detail ?: httpFallback(fallback))
// Not one of the states above, so it is an ordinary failure being
// reported as a message, and it goes through the same formatter as
// every other one. preferDetail keeps what this branch already did
// (these endpoints answer with prose worth reading) while letting the
// technical register add the status, which it could not before: the
// preference used to do nothing on any screen that classified its
// errors through here, so the same setting said different things
// depending on which call had failed.
//
// The classified states above keep their own wording. They are states
// with their own UI, not messages, and a status code in the step-up
// sheet's "incorrect password" line would read as a fault rather than
// as a prompt.
else -> ShareError.Other(toUserMessage(fallback, preferDetail = true))
}
}

// Moshi rather than org.json: the classification is the interesting part of
// this file and org.json is an Android framework stub off-device, so parsing
// with it would make these branches untestable on the JVM.
private val errorBodyAdapter by lazy {
Moshi.Builder().build().adapter<Map<String, Any?>>(
com.squareup.moshi.Types.newParameterizedType(
Map::class.java,
String::class.java,
Any::class.java,
),
)
}

// The body is a one-shot stream, so read it once here rather than letting
// toUserMessage race us for it.
private fun HttpException.errorDetail(): String? = runCatching {
val body = response()?.errorBody()?.string().orEmpty()
if (body.isBlank()) return@runCatching null
(errorBodyAdapter.fromJson(body)?.get("detail") as? String)?.takeIf { it.isNotBlank() }
}.getOrNull()
// The detail reader moved to util/ApiErrorDetail.kt, which peeks the body
// instead of consuming it. That retires the race this file used to work
// around: toUserMessage now reads the detail too, for the technical-errors
// preference, and two readers on one exception is the normal case rather than
// something to avoid.

private fun HttpException.httpFallback(fallback: String): String = when (code()) {
401 -> "Session expired, please log in again"
404 -> "Not found"
429 -> "Too many requests, please wait a moment"
else -> fallback
}
// The per-status wording this file used to carry has gone: toUserMessage
// already maps every one of those codes, and keeping a second table meant the
// same status could read two ways depending on which screen asked.

fun ShareError.message(fallback: String): String = when (this) {
is ShareError.StepUpRequired -> fallback
Expand Down
Loading
Loading