diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/common/data/ServerFeatures.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/common/data/ServerFeatures.kt new file mode 100644 index 00000000..8a8bfb53 --- /dev/null +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/common/data/ServerFeatures.kt @@ -0,0 +1,35 @@ +package de.markusressel.mkdocseditor.feature.common.data + +import de.markusressel.mkdocseditor.auth.domain.AuthRepository +import de.markusressel.mkdocseditor.feature.auth.common.data.AuthBackends +import de.markusressel.mkdocseditor.feature.backendconfig.common.data.toBackendRef +import timber.log.Timber +import java.util.concurrent.ConcurrentHashMap +import javax.inject.Inject +import javax.inject.Singleton + +/** + * The optional API features of the selected server (`features` of `GET /server-info/`, see `ServerFeature`). The answer + * is kept for the app's lifetime, so a page opened offline still shows what the server had once it was reached. + */ +@Singleton +internal class ServerFeatures @Inject constructor( + private val backends: AuthBackends, + private val authRepository: AuthRepository, +) { + private val known = ConcurrentHashMap>() + + /** false while the server can't be asked and has not been before */ + suspend fun has(feature: String): Boolean = feature in features() + + private suspend fun features(): Set { + val backend = backends.selected()?.toBackendRef() ?: return emptySet() + known[backend.baseUrl]?.let { return it } + return try { + authRepository.serverInfo(backend).features.toSet().also { known[backend.baseUrl] = it } + } catch (e: Exception) { + Timber.w(e, "Could not read the server features") + emptySet() + } + } +} diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/CodeEditorViewModel.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/CodeEditorViewModel.kt index 6d890ca2..0fe479f5 100644 --- a/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/CodeEditorViewModel.kt +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/CodeEditorViewModel.kt @@ -1,5 +1,7 @@ package de.markusressel.mkdocseditor.feature.editor.ui +import de.markusressel.mkdocseditor.auth.api.ServerFeature +import de.markusressel.mkdocseditor.feature.common.data.ServerFeatures import de.markusressel.mkdocseditor.feature.history.domain.SeenChangesUseCase import de.markusressel.mkdocseditor.feature.history.domain.changeLocation import de.markusressel.mkdocsrestclient.history.DiffHunkModel @@ -139,6 +141,7 @@ internal class CodeEditorViewModel @Inject constructor( private val pendingQrKey: PendingQrKey, private val resolveQrCode: ResolveQrCodeUseCase, private val seenChanges: SeenChangesUseCase, + private val serverFeatures: ServerFeatures, savedStateHandle: SavedStateHandle, clientInstanceId: ClientInstanceId, moveItemUseCase: MoveItemUseCase, @@ -318,6 +321,11 @@ internal class CodeEditorViewModel @Inject constructor( } launch { _uiState.update { it.copy(qrCodesAvailable = qrCodesSupport.isSupported()) } } + launch { + val history = serverFeatures.has(ServerFeature.HISTORY) + val revert = serverFeatures.has(ServerFeature.REVERT) + _uiState.update { it.copy(historyAvailable = history, revertAvailable = revert) } + } // a key of a sticker without a page, to put on this one launch { @@ -675,7 +683,13 @@ internal class CodeEditorViewModel @Inject constructor( is TopAppBarAction.CodeEditor.PageReferencesAction -> showPageReferences() is TopAppBarAction.CodeEditor.QrCodesAction -> showQrCodes() is TopAppBarAction.CodeEditor.HistoryAction -> uiState.value.documentId?.let { - _navigationEvents.send(NavigationRequest.OpenHistory(it, canRestore = uiState.value.canEdit)) + _navigationEvents.send( + NavigationRequest.OpenHistory( + documentId = it, + canRestore = uiState.value.canEdit, + canRevert = uiState.value.canEdit && uiState.value.revertAvailable, + ) + ) } } } @@ -1258,6 +1272,12 @@ internal class CodeEditorViewModel @Inject constructor( /** whether the server has QR codes, see [QrCodesSupport] */ val qrCodesAvailable: Boolean = false, + /** whether the server has the revision history, see [ServerFeatures] */ + val historyAvailable: Boolean = false, + + /** whether the server can undo a single change of the history */ + val revertAvailable: Boolean = false, + /** what others changed since the user last looked at the page, null if nothing; see [SeenChangesUseCase] */ val changesSinceSeen: DocumentChangesModel? = null, ) { @@ -1360,7 +1380,7 @@ internal class CodeEditorViewModel @Inject constructor( sealed interface NavigationRequest { data class Login(val backendId: Long) : NavigationRequest data class OpenDocument(val documentId: String) : NavigationRequest - data class OpenHistory(val documentId: String, val canRestore: Boolean) : NavigationRequest + data class OpenHistory(val documentId: String, val canRestore: Boolean, val canRevert: Boolean) : NavigationRequest /** leave the editor, e.g. to show a folder in the file browser */ data object Close : NavigationRequest data class ShareLink(val link: String) : NavigationRequest { diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorScreen.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorScreen.kt index 4d5a2568..3a20d37e 100644 --- a/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorScreen.kt +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorScreen.kt @@ -106,7 +106,9 @@ internal data class CodeEditorScreen( navigator.push(CodeEditorScreen(documentId = request.documentId)) is CodeEditorViewModel.NavigationRequest.OpenHistory -> - navigator.push(HistoryScreen(documentId = request.documentId, canRestore = request.canRestore)) + navigator.push( + HistoryScreen(documentId = request.documentId, canRestore = request.canRestore, canRevert = request.canRevert) + ) is CodeEditorViewModel.NavigationRequest.Close -> navigator.pop() diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorScreenContent.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorScreenContent.kt index a3366065..1a1e55b4 100644 --- a/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorScreenContent.kt +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorScreenContent.kt @@ -407,7 +407,7 @@ internal fun editorTopBarActions( listOfNotNull( viewSettings.takeIf { !viewInBar }, TopAppBarAction.CodeEditor.PageReferencesAction.takeIf { !wide }, - TopAppBarAction.CodeEditor.HistoryAction, + TopAppBarAction.CodeEditor.HistoryAction.takeIf { uiState.historyAvailable }, TopAppBarAction.CodeEditor.MenuDivider, TopAppBarAction.CodeEditor.ShareLinkAction, TopAppBarAction.CodeEditor.ShowInBrowserAction, diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/history/domain/SeenChangesUseCase.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/domain/SeenChangesUseCase.kt index 20b8d542..684d4181 100644 --- a/app/src/main/java/de/markusressel/mkdocseditor/feature/history/domain/SeenChangesUseCase.kt +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/domain/SeenChangesUseCase.kt @@ -1,7 +1,9 @@ package de.markusressel.mkdocseditor.feature.history.domain import com.github.kittinunf.result.Result +import de.markusressel.mkdocseditor.auth.api.ServerFeature import de.markusressel.mkdocseditor.auth.domain.AuthRepository +import de.markusressel.mkdocseditor.feature.common.data.ServerFeatures import de.markusressel.mkdocseditor.feature.auth.common.data.AuthBackends import de.markusressel.mkdocsrestclient.IMkDocsRestClient import de.markusressel.mkdocsrestclient.history.ChangeAuthorModel @@ -12,12 +14,13 @@ import javax.inject.Inject /** * What changed in a page since the account last looked at it (`GET /document/{id}/changes/`), and marking it as seen. - * The server keeps the mark, so all devices and the web client agree. A server without it tells nothing. + * The server keeps the mark, so all devices and the web client agree. A server without `changes` is not asked. */ internal class SeenChangesUseCase @Inject constructor( private val restClient: IMkDocsRestClient, private val backends: AuthBackends, private val authRepository: AuthRepository, + private val features: ServerFeatures, ) { /** @@ -28,6 +31,7 @@ internal class SeenChangesUseCase @Inject constructor( * seen, nothing changed, only the account itself changed it, or the server can't say */ suspend fun open(documentId: String): DocumentChangesModel? { + if (!features.has(ServerFeature.CHANGES)) return null val changes = changes(documentId) ?: return null markSeen(documentId, changes.seenToken) if (changes.since == null || changes.hunks.isEmpty()) return null @@ -38,6 +42,7 @@ internal class SeenChangesUseCase @Inject constructor( /** The page as it is now counts as seen, when the account leaves it: its own edits are no news later. */ suspend fun leave(documentId: String) { + if (!features.has(ServerFeature.CHANGES)) return changes(documentId)?.let { markSeen(documentId, it.seenToken) } } diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/HistoryViewModel.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/HistoryViewModel.kt index 907d35a7..43516f5b 100644 --- a/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/HistoryViewModel.kt +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/HistoryViewModel.kt @@ -12,6 +12,7 @@ import de.markusressel.mkdocseditor.feature.history.domain.changeLocation import de.markusressel.mkdocsrestclient.IMkDocsRestClient import de.markusressel.mkdocsrestclient.history.DiffHunkModel import de.markusressel.mkdocsrestclient.history.HistoryEntryModel +import de.markusressel.mkdocsrestclient.history.RevertErrorModel import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow @@ -37,10 +38,10 @@ internal class HistoryViewModel @Inject constructor( private var documentId: String? = null - fun initialize(documentId: String, canRestore: Boolean) { + fun initialize(documentId: String, canRestore: Boolean, canRevert: Boolean = false) { if (this.documentId != null) return this.documentId = documentId - _uiState.update { it.copy(canRestore = canRestore) } + _uiState.update { it.copy(canRestore = canRestore, canRevert = canRevert) } launch { load() } } @@ -49,9 +50,14 @@ internal class HistoryViewModel @Inject constructor( is UiEvent.RetryClicked -> launch { load() } is UiEvent.EntryClicked -> onEntryClicked(event.revision) is UiEvent.HunkClicked -> launch { _events.send(HistoryEvent.OpenInEditor(event.hunk.changeLocation())) } - is UiEvent.RestoreClicked -> _uiState.update { it.copy(confirmRestore = event.entry) } - is UiEvent.RestoreDismissed -> _uiState.update { it.copy(confirmRestore = null) } - is UiEvent.RestoreConfirmed -> launch { restore() } + is UiEvent.RestoreClicked -> _uiState.update { it.copy(confirm = Confirm.Restore(event.entry)) } + is UiEvent.UndoClicked -> _uiState.update { it.copy(confirm = Confirm.Undo(event.entry)) } + is UiEvent.ConfirmDismissed -> _uiState.update { it.copy(confirm = null) } + is UiEvent.Confirmed -> when (val confirm = uiState.value.confirm) { + is Confirm.Restore -> launch { restore(confirm.entry) } + is Confirm.Undo -> launch { undo(confirm.entry) } + null -> Unit + } is UiEvent.BackClicked -> launch { _events.send(HistoryEvent.Close) } } } @@ -101,12 +107,11 @@ internal class HistoryViewModel @Inject constructor( private fun setDiff(revision: String, diff: DiffState) = _uiState.update { it.copy(diffs = it.diffs + (revision to diff)) } - private suspend fun restore() { + private suspend fun restore(entry: HistoryEntryModel) { val documentId = documentId ?: return - val entry = uiState.value.confirmRestore ?: return - _uiState.update { it.copy(confirmRestore = null, restoring = true) } + _uiState.update { it.copy(confirm = null, working = true) } val result = restClient.restoreDocumentRevision(documentId, entry.revision) - _uiState.update { it.copy(restoring = false) } + _uiState.update { it.copy(working = false) } when (result) { is Result.Success -> { _events.send(HistoryEvent.Message(R.string.history_restored)) @@ -119,6 +124,43 @@ internal class HistoryViewModel @Inject constructor( } } + /** Undoes the changes of one entry; later changes stay. A conflict or a change that is gone changes nothing. */ + private suspend fun undo(entry: HistoryEntryModel) { + val documentId = documentId ?: return + _uiState.update { it.copy(confirm = null, working = true) } + val result = restClient.revertDocumentRevision(documentId, entry.revision) + _uiState.update { it.copy(working = false) } + when (result) { + is Result.Success -> { + _events.send(HistoryEvent.Message(R.string.history_undone)) + load() + } + is Result.Failure -> { + val error = RevertErrorModel.parse(result.error.response.data) + val message = when (error?.code) { + RevertErrorModel.CONFLICT -> HistoryEvent.UndoConflict(error.details?.headings.orEmpty()) + RevertErrorModel.NOTHING_TO_REVERT -> HistoryEvent.Message(R.string.history_undo_nothing) + else -> { + Timber.w(result.error, "revert of %s at %s", documentId, entry.revision) + HistoryEvent.Message(result.error.userMessage()) + } + } + _events.send(message) + } + } + } + + /** an action that waits for the user to confirm it */ + internal sealed interface Confirm { + val entry: HistoryEntryModel + + /** the text of the page becomes the one of [entry] */ + data class Restore(override val entry: HistoryEntryModel) : Confirm + + /** the changes of [entry] are taken back */ + data class Undo(override val entry: HistoryEntryModel) : Confirm + } + internal sealed interface DiffState { data object Loading : DiffState data class Loaded(val hunks: List) : DiffState @@ -131,7 +173,8 @@ internal class HistoryViewModel @Inject constructor( /** * @param expanded the revision whose diff is shown * @param diffs by revision - * @param confirmRestore the entry whose text is about to come back, while the user confirms it + * @param confirm the action the user is asked to confirm + * @param working a restore or undo is on its way */ internal data class UiState( val loading: Boolean = true, @@ -140,8 +183,9 @@ internal class HistoryViewModel @Inject constructor( val expanded: String? = null, val diffs: Map = emptyMap(), val canRestore: Boolean = false, - val confirmRestore: HistoryEntryModel? = null, - val restoring: Boolean = false, + val canRevert: Boolean = false, + val confirm: Confirm? = null, + val working: Boolean = false, ) internal sealed interface UiEvent { @@ -149,14 +193,18 @@ internal class HistoryViewModel @Inject constructor( data class EntryClicked(val revision: String) : UiEvent data class HunkClicked(val hunk: DiffHunkModel) : UiEvent data class RestoreClicked(val entry: HistoryEntryModel) : UiEvent - data object RestoreDismissed : UiEvent - data object RestoreConfirmed : UiEvent + data class UndoClicked(val entry: HistoryEntryModel) : UiEvent + data object ConfirmDismissed : UiEvent + data object Confirmed : UiEvent data object BackClicked : UiEvent } internal sealed interface HistoryEvent { data class OpenInEditor(val change: ChangeLocation) : HistoryEvent data class Message(@param:StringRes val text: Int) : HistoryEvent + + /** later changes in these sections are in the way, null for the part above the first heading */ + data class UndoConflict(val headings: List) : HistoryEvent data object Close : HistoryEvent } } diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreen.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreen.kt index 66d39627..ec9093c3 100644 --- a/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreen.kt +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreen.kt @@ -11,6 +11,7 @@ import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.hilt.getViewModel import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.currentOrThrow +import de.markusressel.mkdocseditor.R import de.markusressel.mkdocseditor.feature.editor.ui.compose.CodeEditorScreen import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.HistoryEvent @@ -23,10 +24,12 @@ import de.markusressel.mkdocseditor.feature.main.data.rememberMainNavigationRequ * The revision history of a document, see [HistoryViewModel] * * @param canRestore whether the account may edit the document, and so bring back an old text + * @param canRevert whether it may also undo a single change, which needs `revert` on the server */ data class HistoryScreen( val documentId: String, val canRestore: Boolean, + val canRevert: Boolean = false, ) : Screen { @Composable @@ -38,7 +41,7 @@ data class HistoryScreen( val uiState by viewModel.uiState.collectAsState() LaunchedEffect(viewModel, documentId) { - viewModel.initialize(documentId, canRestore) + viewModel.initialize(documentId, canRestore, canRevert) } LaunchedEffect(viewModel) { @@ -55,6 +58,11 @@ data class HistoryScreen( } } is HistoryEvent.Message -> Toast.makeText(context, event.text, Toast.LENGTH_LONG).show() + is HistoryEvent.UndoConflict -> { + val top = context.getString(R.string.history_page_start) + val headings = event.headings.joinToString(", ") { it ?: top } + Toast.makeText(context, context.getString(R.string.history_undo_conflict, headings), Toast.LENGTH_LONG).show() + } is HistoryEvent.Close -> navigator.pop() } } diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreenContent.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreenContent.kt index c9251692..c65e6f9e 100644 --- a/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreenContent.kt +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreenContent.kt @@ -59,6 +59,7 @@ import de.markusressel.mkdocseditor.feature.history.domain.pairChangedLines import de.markusressel.mkdocseditor.feature.history.domain.peopleWithAgents import de.markusressel.mkdocseditor.feature.history.domain.shownName import de.markusressel.mkdocseditor.feature.history.domain.wordChanges +import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.Confirm import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.DiffState import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.UiEvent import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.UiState @@ -94,7 +95,7 @@ internal fun HistoryScreenContent( }, ) { paddingValues -> Column(modifier = Modifier.fillMaxSize().padding(paddingValues)) { - if (uiState.loading || uiState.restoring) { + if (uiState.loading || uiState.working) { LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) } val problem = uiState.problem @@ -118,6 +119,8 @@ internal fun HistoryScreenContent( diff = uiState.diffs[entry.revision], // the newest entry is the text as it is canRestore = uiState.canRestore && entry != uiState.entries.first(), + // the oldest one created the page, which is undone by deleting it + canUndo = uiState.canRevert && entry != uiState.entries.last(), onUiEvent = onUiEvent, ) HorizontalDivider() @@ -127,16 +130,28 @@ internal fun HistoryScreenContent( } } - uiState.confirmRestore?.let { entry -> + uiState.confirm?.let { confirm -> + val entry = confirm.entry + val (title, text, action) = when (confirm) { + is Confirm.Restore -> Triple( + stringResource(R.string.history_restore_title), + stringResource(R.string.history_restore_text, relativeTime(entry.time), entry.author.shownName), + stringResource(R.string.history_restore), + ) + // the diff of the entry is open above, so the dialog names who and when + is Confirm.Undo -> Triple( + stringResource(R.string.history_undo_title), + stringResource(R.string.history_undo_text, whoText(entry), relativeTime(entry.time)), + stringResource(R.string.history_undo), + ) + } AlertDialog( - onDismissRequest = { onUiEvent(UiEvent.RestoreDismissed) }, - title = { Text(stringResource(R.string.history_restore_title)) }, - text = { Text(stringResource(R.string.history_restore_text, relativeTime(entry.time), entry.author.shownName)) }, - confirmButton = { - TextButton(onClick = { onUiEvent(UiEvent.RestoreConfirmed) }) { Text(stringResource(R.string.history_restore)) } - }, + onDismissRequest = { onUiEvent(UiEvent.ConfirmDismissed) }, + title = { Text(title) }, + text = { Text(text) }, + confirmButton = { TextButton(onClick = { onUiEvent(UiEvent.Confirmed) }) { Text(action) } }, dismissButton = { - TextButton(onClick = { onUiEvent(UiEvent.RestoreDismissed) }) { Text(stringResource(android.R.string.cancel)) } + TextButton(onClick = { onUiEvent(UiEvent.ConfirmDismissed) }) { Text(stringResource(android.R.string.cancel)) } }, ) } @@ -148,6 +163,7 @@ private fun HistoryEntry( expanded: Boolean, diff: DiffState?, canRestore: Boolean, + canUndo: Boolean, onUiEvent: (UiEvent) -> Unit, ) { Column( @@ -182,11 +198,17 @@ private fun HistoryEntry( if (expanded) { Spacer(Modifier.size(8.dp)) EntryDiff(diff, onUiEvent) - if (canRestore) { - OutlinedButton( - modifier = Modifier.padding(top = 8.dp), - onClick = { onUiEvent(UiEvent.RestoreClicked(entry)) }, - ) { Text(stringResource(R.string.history_restore_action)) } + Row(modifier = Modifier.padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + if (canUndo) { + OutlinedButton(onClick = { onUiEvent(UiEvent.UndoClicked(entry)) }) { + Text(stringResource(R.string.history_undo_action)) + } + } + if (canRestore) { + OutlinedButton(onClick = { onUiEvent(UiEvent.RestoreClicked(entry)) }) { + Text(stringResource(R.string.history_restore_action)) + } + } } } } @@ -239,11 +261,12 @@ private fun summaryText(summary: HistorySummaryModel?): String? { return if (summary.headings.isEmpty()) lines else "$lines ยท ${summary.headings.joinToString(", ")}" } -/** a commit from a server whose clock is a little ahead is "now", not "in 0 minutes" */ +/** within the last minute, or from a server whose clock is a little ahead, it is "just now", not "in 0 minutes" */ @Composable private fun relativeTime(time: Date): String { val now = System.currentTimeMillis() - return DateUtils.getRelativeTimeSpanString(minOf(time.time, now), now, DateUtils.MINUTE_IN_MILLIS).toString() + if (now - time.time < DateUtils.MINUTE_IN_MILLIS) return stringResource(R.string.history_just_now) + return DateUtils.getRelativeTimeSpanString(time.time, now, DateUtils.MINUTE_IN_MILLIS).toString() } @Composable @@ -363,7 +386,7 @@ private fun HistoryScreenContentPreview() { HistoryScreenContent( uiState = UiState( loading = false, entries = entries, expanded = "b", diffs = mapOf("b" to DiffState.Loaded(listOf(hunk))), - canRestore = true, + canRestore = true, canRevert = true, ), onUiEvent = {}, ) diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/qr/data/QrCodesSupport.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/qr/data/QrCodesSupport.kt index cf441f01..026c8d29 100644 --- a/app/src/main/java/de/markusressel/mkdocseditor/feature/qr/data/QrCodesSupport.kt +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/qr/data/QrCodesSupport.kt @@ -1,34 +1,13 @@ package de.markusressel.mkdocseditor.feature.qr.data import de.markusressel.mkdocseditor.auth.api.ServerFeature -import de.markusressel.mkdocseditor.auth.domain.AuthRepository -import de.markusressel.mkdocseditor.feature.auth.common.data.AuthBackends -import de.markusressel.mkdocseditor.feature.backendconfig.common.data.toBackendRef -import timber.log.Timber -import java.util.concurrent.ConcurrentHashMap +import de.markusressel.mkdocseditor.feature.common.data.ServerFeatures import javax.inject.Inject -import javax.inject.Singleton -/** - * Whether the selected server has QR codes (`qr-codes` in its features). The answer is kept for the app's lifetime, - * so a page opened offline still shows the menu entry once the server was reached. - */ -@Singleton +/** Whether the selected server has QR codes (`qr-codes` in its features), see [ServerFeatures] */ internal class QrCodesSupport @Inject constructor( - private val backends: AuthBackends, - private val authRepository: AuthRepository, + private val features: ServerFeatures, ) { - private val known = ConcurrentHashMap() - /** false while the server can't be asked and has not been before */ - suspend fun isSupported(): Boolean { - val backend = backends.selected()?.toBackendRef() ?: return false - known[backend.baseUrl]?.let { return it } - return try { - (ServerFeature.QR_CODES in authRepository.serverInfo(backend).features).also { known[backend.baseUrl] = it } - } catch (e: Exception) { - Timber.w(e, "Could not read the server features") - false - } - } + suspend fun isSupported(): Boolean = features.has(ServerFeature.QR_CODES) } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0efd5aab..d3412a95 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -462,6 +462,14 @@ The page gets the text it had %1$s, after the change of %2$s. Everyone sees it as an edit, which can be undone. Restore Version restored + just now + Undo this change + Undo this change? + The change of %1$s from %2$s is taken back. Later changes stay. Everyone sees it as an edit, which can be undone. + Undo + Change undone + This change is not in the page anymore. + Can\'t undo: later changes in %1$s are in the way. Changed by %1$s since you were here Changes since your last visit Hide diff --git a/app/src/test/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/EditorTopBarActionsTest.kt b/app/src/test/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/EditorTopBarActionsTest.kt index 6fcb2254..e756493e 100644 --- a/app/src/test/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/EditorTopBarActionsTest.kt +++ b/app/src/test/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/EditorTopBarActionsTest.kt @@ -12,7 +12,7 @@ import kotlin.test.assertTrue class EditorTopBarActionsTest { - private val editing = CodeEditorViewModel.UiState(editModeActive = true) + private val editing = CodeEditorViewModel.UiState(editModeActive = true, historyAvailable = true) /** a phone in portrait */ private val phone = 411 @@ -99,6 +99,15 @@ class EditorTopBarActionsTest { } } + @Test + fun `the history is in the menu only when the server has it`() { + val without = menuOf(editorTopBarActions(editing.copy(historyAvailable = false), SplitMode.Off, widthDp = phone)) + val with = menuOf(editorTopBarActions(editing, SplitMode.Off, widthDp = phone)) + + assertTrue(TopAppBarAction.CodeEditor.HistoryAction !in without) + assertTrue(TopAppBarAction.CodeEditor.HistoryAction in with) + } + @Test fun `the page can be renamed, moved, pinned and deleted from the menu, last`() { val menu = menuOf(editorTopBarActions(CodeEditorViewModel.UiState(), SplitMode.Off, widthDp = phone)) diff --git a/app/src/test/java/de/markusressel/mkdocseditor/feature/history/domain/SeenChangesUseCaseTest.kt b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/domain/SeenChangesUseCaseTest.kt index fda91320..b4692380 100644 --- a/app/src/test/java/de/markusressel/mkdocseditor/feature/history/domain/SeenChangesUseCaseTest.kt +++ b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/domain/SeenChangesUseCaseTest.kt @@ -5,7 +5,10 @@ import com.github.kittinunf.fuel.core.Response import com.github.kittinunf.result.Result import de.markusressel.mkdocseditor.auth.FakeAuthApi import de.markusressel.mkdocseditor.auth.InMemoryTokenStore +import de.markusressel.mkdocseditor.auth.api.ServerFeature +import de.markusressel.mkdocseditor.auth.api.ServerInfo import de.markusressel.mkdocseditor.auth.domain.AuthRepository +import de.markusressel.mkdocseditor.feature.common.data.ServerFeatures import de.markusressel.mkdocseditor.auth.token.AuthSession import de.markusressel.mkdocseditor.feature.auth.FakeAuthBackends import de.markusressel.mkdocseditor.feature.auth.backendConfig @@ -44,18 +47,17 @@ class SeenChangesUseCaseTest { } } - private val useCase = SeenChangesUseCase( - restClient = client, - backends = FakeAuthBackends().apply { - configs += backendConfig(1) - selectedId = 1 - }, - authRepository = AuthRepository( - InMemoryTokenStore().apply { put(1, AuthSession("t", null, "carol")) }, - { FakeAuthApi() }, - deviceName = "Pixel 8", - ), + private var serverFeatures = listOf(ServerFeature.CHANGES) + private val backends = FakeAuthBackends().apply { + configs += backendConfig(1) + selectedId = 1 + } + private val authRepository = AuthRepository( + InMemoryTokenStore().apply { put(1, AuthSession("t", null, "carol")) }, + { FakeAuthApi().apply { onServerInfo = { ServerInfo(name = "Wiki", features = serverFeatures) } } }, + deviceName = "Pixel 8", ) + private val useCase = SeenChangesUseCase(client, backends, authRepository, ServerFeatures(backends, authRepository)) @Test fun `changes of someone else are told, and the page counts as seen with the token of the answer`() = runTest { @@ -105,6 +107,26 @@ class SeenChangesUseCaseTest { assertEquals(emptyList(), seen) } + @Test + fun `a server without the changes feature is not asked`() = runTest { + serverFeatures = emptyList() + var asked = false + val useCase = SeenChangesUseCase( + object : IMkDocsRestClient by client { + override suspend fun getDocumentChanges(documentId: String, since: String?): Result { + asked = true + return answer + } + }, + backends, authRepository, ServerFeatures(backends, authRepository), + ) + + assertNull(useCase.open("d1")) + useCase.leave("d1") + assertEquals(false, asked) + assertEquals(emptyList(), seen) + } + @Test fun `leaving the page marks it as it is now`() = runTest { useCase.leave("d1") diff --git a/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/HistoryViewModelTest.kt b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/HistoryViewModelTest.kt index aba8227c..529a1bc6 100644 --- a/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/HistoryViewModelTest.kt +++ b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/HistoryViewModelTest.kt @@ -2,6 +2,7 @@ package de.markusressel.mkdocseditor.feature.history.ui import com.github.kittinunf.fuel.core.FuelError import com.github.kittinunf.fuel.core.Response +import com.github.kittinunf.fuel.core.requests.DefaultBody import com.github.kittinunf.result.Result import de.markusressel.mkdocseditor.R import de.markusressel.mkdocseditor.feature.editor.domain.ChangeLocation @@ -26,6 +27,7 @@ import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach +import java.io.ByteArrayInputStream import java.net.URL import java.util.Date import kotlin.test.Test @@ -46,6 +48,8 @@ class HistoryViewModelTest { private var history: Result, FuelError> = Result.success(listOf(entry("c"), entry("b"), entry("a"))) private val diffRequests = mutableListOf>() private val restored = mutableListOf() + private val reverted = mutableListOf() + private var revertAnswer: Result = Result.success(entry("d")) private var historyRequests = 0 private val events = mutableListOf() @@ -60,6 +64,11 @@ class HistoryViewModelTest { return Result.success(HistoryDiffModel(from, to, listOf(hunk))) } + override suspend fun revertDocumentRevision(documentId: String, revision: String): Result { + reverted += revision + return revertAnswer + } + override suspend fun restoreDocumentRevision(documentId: String, revision: String): Result { restored += revision return Result.success("") @@ -74,7 +83,7 @@ class HistoryViewModelTest { private fun TestScope.viewModel(canRestore: Boolean = true) = HistoryViewModel(client).also { viewModel -> backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { viewModel.events.collect { events += it } } - viewModel.initialize("d1", canRestore) + viewModel.initialize("d1", canRestore, canRevert = true) } @Test @@ -139,10 +148,10 @@ class HistoryViewModelTest { viewModel.onUiEvent(UiEvent.RestoreClicked(entry("b"))) assertEquals(emptyList(), restored) - viewModel.onUiEvent(UiEvent.RestoreConfirmed) + viewModel.onUiEvent(UiEvent.Confirmed) assertEquals(listOf("b"), restored) - assertNull(viewModel.uiState.value.confirmRestore) + assertNull(viewModel.uiState.value.confirm) assertEquals(2, historyRequests) assertEquals(listOf(HistoryEvent.Message(R.string.history_restored)), events) } @@ -152,9 +161,59 @@ class HistoryViewModelTest { val viewModel = viewModel() viewModel.onUiEvent(UiEvent.RestoreClicked(entry("b"))) - viewModel.onUiEvent(UiEvent.RestoreDismissed) - viewModel.onUiEvent(UiEvent.RestoreConfirmed) + viewModel.onUiEvent(UiEvent.ConfirmDismissed) + viewModel.onUiEvent(UiEvent.Confirmed) + + assertEquals(emptyList(), restored) + } + + private fun conflict(body: String) = Result.error( + FuelError.wrap( + RuntimeException("409"), + Response( + url = URL("http://localhost/"), + statusCode = 409, + body = DefaultBody.from({ ByteArrayInputStream(body.toByteArray()) }, { body.length.toLong() }), + ), + ) + ) + + @Test + fun `a change is undone after confirming, and the history reloads`() = runTest { + val viewModel = viewModel() + viewModel.onUiEvent(UiEvent.UndoClicked(entry("b"))) + assertEquals(emptyList(), reverted) + + viewModel.onUiEvent(UiEvent.Confirmed) + assertEquals(listOf("b"), reverted) assertEquals(emptyList(), restored) + assertEquals(2, historyRequests) + assertEquals(listOf(HistoryEvent.Message(R.string.history_undone)), events) + } + + @Test + fun `an undo in the way of later changes names their sections`() = runTest { + // the answer of a real backend (MkDocsEditor-Backend#99) + revertAnswer = conflict( + """{"name":"Conflict","code":"revert-conflict","message":"later edits changed the same lines, edit the document by hand",""" + + """"details":{"conflicts":[{"heading":"Setup","headingOccurrence":1,"line":3}],"headings":["Setup"]}}""" + ) + val viewModel = viewModel() + viewModel.onUiEvent(UiEvent.UndoClicked(entry("b"))) + viewModel.onUiEvent(UiEvent.Confirmed) + + assertEquals(listOf(HistoryEvent.UndoConflict(listOf("Setup"))), events) + assertEquals(1, historyRequests) + } + + @Test + fun `an undo of a change that is gone says so`() = runTest { + revertAnswer = conflict("""{"name":"Conflict","code":"nothing-to-revert","message":"the change of this revision is not in the document anymore"}""") + val viewModel = viewModel() + viewModel.onUiEvent(UiEvent.UndoClicked(entry("b"))) + viewModel.onUiEvent(UiEvent.Confirmed) + + assertEquals(listOf(HistoryEvent.Message(R.string.history_undo_nothing)), events) } } diff --git a/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreenContentTest.kt b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreenContentTest.kt index dcea20a9..d2554afb 100644 --- a/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreenContentTest.kt +++ b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreenContentTest.kt @@ -95,6 +95,39 @@ class HistoryScreenContentTest { assertEquals(listOf(UiEvent.HunkClicked(hunk), UiEvent.RestoreClicked(entries[1])), events) } + @Test + fun `editors on a server with revert can undo a change, but not the first version`() { + val events = mutableListOf() + composeRule.setContent { + Shown { + HistoryScreenContent( + UiState( + loading = false, entries = entries, expanded = "b", + diffs = mapOf("b" to DiffState.Loaded(listOf(hunk)), "a" to DiffState.FirstVersion), canRevert = true, + ), + onUiEvent = { events += it }, + ) + } + } + + composeRule.onNodeWithText("Undo this change").performClick() + assertEquals(listOf(UiEvent.UndoClicked(entries[0])), events) + } + + @Test + fun `the first version can not be undone`() { + composeRule.setContent { + Shown { + HistoryScreenContent( + UiState(loading = false, entries = entries, expanded = "a", diffs = mapOf("a" to DiffState.FirstVersion), canRevert = true), + onUiEvent = {}, + ) + } + } + + composeRule.onNodeWithText("Undo this change").assertDoesNotExist() + } + @Test fun `the newest entry can not be restored, it is the text as it is`() { composeRule.setContent { diff --git a/auth/src/main/java/de/markusressel/mkdocseditor/auth/api/Models.kt b/auth/src/main/java/de/markusressel/mkdocseditor/auth/api/Models.kt index e157dee0..89eaf6c9 100644 --- a/auth/src/main/java/de/markusressel/mkdocseditor/auth/api/Models.kt +++ b/auth/src/main/java/de/markusressel/mkdocseditor/auth/api/Models.kt @@ -222,6 +222,15 @@ object ServerFeature { const val AVATARS = "avatars" const val PUSH = "push" const val QR_CODES = "qr-codes" + + /** `GET /document/{id}/changes/` and `PUT /document/{id}/seen/` */ + const val CHANGES = "changes" + + /** the revision history with summaries, agents and diffs as JSON; needs git on the server */ + const val HISTORY = "history" + + /** `POST /document/{id}/history/{revision}/revert/` */ + const val REVERT = "revert" } /** POST /auth/access-requests/. The token is only shown once. */ diff --git a/rest/src/main/java/de/markusressel/mkdocsrestclient/DummyMkDocsRestClient.kt b/rest/src/main/java/de/markusressel/mkdocsrestclient/DummyMkDocsRestClient.kt index df75f145..5305e99c 100644 --- a/rest/src/main/java/de/markusressel/mkdocsrestclient/DummyMkDocsRestClient.kt +++ b/rest/src/main/java/de/markusressel/mkdocsrestclient/DummyMkDocsRestClient.kt @@ -297,6 +297,9 @@ class DummyMkDocsRestClient : IMkDocsRestClient { override suspend fun putDocumentSeen(documentId: String, seenToken: String): Result = Result.success(SeenModel(Date(), seenToken)) + override suspend fun revertDocumentRevision(documentId: String, revision: String): Result = + Result.error(FuelError.wrap(UnsupportedOperationException())) + override suspend fun restoreDocumentRevision(documentId: String, revision: String): Result = Result.success("") diff --git a/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryApi.kt b/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryApi.kt index bc60e986..c489f4b6 100644 --- a/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryApi.kt +++ b/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryApi.kt @@ -51,6 +51,14 @@ interface HistoryApi { /** Marks the text of [seenToken] as seen by the signed in account. A token the document no longer knows answers 409. */ suspend fun putDocumentSeen(documentId: String, seenToken: String): Result + /** + * Undoes the changes of one commit in the live text; later changes stay. Editors, admins and write tokens only. + * + * @return the entry of the revert commit. A 409 `revert-conflict` (see [RevertErrorModel]) or `nothing-to-revert` + * changes nothing, 400 is the commit that created the file. + */ + suspend fun revertDocumentRevision(documentId: String, revision: String): Result + /** Sets the live text to the one of [revision], as an edit of the signed in account. Editors and admins only. */ suspend fun restoreDocumentRevision(documentId: String, revision: String): Result } @@ -102,6 +110,13 @@ class HistoryApiImpl( kind = RequestKind.Quick, ) + override suspend fun revertDocumentRevision(documentId: String, revision: String): Result = + requestManager.doRequest( + url = "/document/$documentId/history/$revision/revert/", + method = Method.POST, + kind = RequestKind.LongAction, + ) + override suspend fun restoreDocumentRevision(documentId: String, revision: String): Result = requestManager.doRequest( url = "/document/$documentId/history/$revision/restore/", diff --git a/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryModels.kt b/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryModels.kt index 735e4166..6e3c9f09 100644 --- a/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryModels.kt +++ b/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryModels.kt @@ -2,6 +2,7 @@ package de.markusressel.mkdocsrestclient.history import com.squareup.moshi.Json import com.squareup.moshi.JsonClass +import com.squareup.moshi.Moshi import java.util.Date /** @@ -109,3 +110,34 @@ enum class DiffOp { @Json(name = "+") ADDED, } + +/** + * The error body of a revert that changed nothing + * + * @param code `revert-conflict` when later changes touched the same lines, `nothing-to-revert` when the change is gone + */ +@JsonClass(generateAdapter = true) +data class RevertErrorModel( + val code: String? = null, + val details: RevertConflictModel? = null, +) { + companion object { + const val CONFLICT = "revert-conflict" + const val NOTHING_TO_REVERT = "nothing-to-revert" + + private val adapter by lazy { Moshi.Builder().build().adapter(RevertErrorModel::class.java) } + + /** the error in a response body, null when the body is not one */ + fun parse(body: ByteArray): RevertErrorModel? = try { + adapter.fromJson(String(body, Charsets.UTF_8)) + } catch (e: Exception) { + null + } + } +} + +/** @param headings the distinct headings of the sections where later changes are in the way */ +@JsonClass(generateAdapter = true) +data class RevertConflictModel( + val headings: List = emptyList(), +) diff --git a/rest/src/test/java/de/markusressel/mkdocsrestclient/history/RevertModelsTest.kt b/rest/src/test/java/de/markusressel/mkdocsrestclient/history/RevertModelsTest.kt new file mode 100644 index 00000000..626f49f4 --- /dev/null +++ b/rest/src/test/java/de/markusressel/mkdocsrestclient/history/RevertModelsTest.kt @@ -0,0 +1,46 @@ +package de.markusressel.mkdocsrestclient.history + +import de.markusressel.mkdocsrestclient.toEntity +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** Real answers of a backend with revert (MkDocsEditor-Backend#99) */ +class RevertModelsTest { + + @Test + fun `a revert answers with the entry of its commit`() { + val entry = """ + {"revision":"ef16954b863aa386884140a04a5321cb5422706a","time":"2026-11-14T04:37:00+01:00", + "author":{"name":"Anna","email":"anna@mkdocseditor.invalid","username":"anna","accountId":"e4dheissqqro4keaag5e6f2qhq","displayName":"Anna","color":"#1971c2","avatar":null}, + "coAuthors":[],"message":"Revert f5be247d069c on guide/setup.md","path":"guide/setup.md","appTokens":[],"agents":[], + "summary":{"linesAdded":5,"linesRemoved":1,"headings":["Setup","Install","Troubleshooting"]}} + """.trimIndent().toEntity() + + assertEquals("Revert f5be247d069c on guide/setup.md", entry.message) + assertEquals("anna", entry.author.username) + } + + @Test + fun `a conflict names the headings where later edits are in the way`() { + val body = """ + {"name":"Conflict","code":"revert-conflict","message":"later edits changed the same lines, edit the document by hand", + "details":{"conflicts":[{"heading":"Setup","headingOccurrence":1,"line":3}],"headings":["Setup"]}} + """.trimIndent() + + val error = RevertErrorModel.parse(body.toByteArray()) + + assertEquals(RevertErrorModel.CONFLICT, error?.code) + assertEquals(listOf("Setup"), error?.details?.headings) + } + + @Test + fun `a change that is gone already has no details`() { + val body = """{"name":"Conflict","code":"nothing-to-revert","message":"the change of this revision is not in the document anymore"}""" + + val error = RevertErrorModel.parse(body.toByteArray()) + + assertEquals(RevertErrorModel.NOTHING_TO_REVERT, error?.code) + assertNull(error?.details) + } +}