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
24 changes: 22 additions & 2 deletions .github/workflows/test-reports.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,28 @@ jobs:
timeout-minutes: 5
steps:
# Parse uploaded data only; never check out or run code from the tested PR.
- name: Check out the pinned JUnit reporter
uses: actions/checkout@v6
with:
repository: dorny/test-reporter
ref: 79b4b4400dc2354b89e9dd811ef9caa9bdd4f665 # Includes retries for checks.update (upstream #867).
path: .test-reporter
persist-credentials: false
- name: Allow a new Check Run to become visible before updating it
run: |
python3 - <<'PYTHON'
from pathlib import Path

# Upstream retries 404s but sends the first update immediately.
entry = Path(".test-reporter/dist/index.js")
source = entry.read_text()
update = "const resp = await retryOnNotFound(async () => this.octokit.rest.checks.update("
if source.count(update) != 1:
raise SystemExit("Review the initial Check Run delay for this reporter version")
entry.write_text(source.replace(update, "await new Promise(resolve => setTimeout(resolve, 1000));\n" + update))
PYTHON
- name: Publish JUnit results in GitHub Checks
uses: dorny/test-reporter@d1b5dff021aa968b288b02285a8bf47471c5928a # v3
uses: ./.test-reporter
with:
artifact: ${{ inputs.artifact || '/^junit-(.+)$/' }}
name: 'Test results · $1'
Expand All @@ -42,7 +62,7 @@ jobs:
use-actions-summary: false
- name: Add collapsible test groups to Actions Summary
if: ${{ !cancelled() }}
uses: dorny/test-reporter@d1b5dff021aa968b288b02285a8bf47471c5928a # v3
uses: ./.test-reporter
with:
artifact: ${{ inputs.artifact || '/^junit-(.+)$/' }}
name: 'Test results · $1'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,34 @@ class StorageDeliveryDeviceTest {
finally { discardImages(images); input.delete() }
}

@Test fun waitingForImageProviderLeavesBitmapBudgetAvailable() {
val uri = android.net.Uri.parse("content://life.andre.message487.test.images/slow")
context.contentResolver.call(uri, "release", null, null)
val style = android.app.Notification.MessagingStyle("self").addMessage(
android.app.Notification.MessagingStyle.Message("", 1L, "sender").setData("image/png", uri))
val notification = android.app.Notification.Builder(context, "test")
.setSmallIcon(android.R.drawable.ic_dialog_info).setStyle(style).build()
val executor = java.util.concurrent.Executors.newFixedThreadPool(2)
val signal = android.os.CancellationSignal()
val capture = executor.submit {
try { discardImages(notificationImages(context, notification, ForwardingSettings(), cancellation = signal) {}) }
catch (_: android.os.OperationCanceledException) { }
}
try {
val until = android.os.SystemClock.elapsedRealtime() + 3000
while (context.contentResolver.call(uri, "opened", null, null)!!.getInt("count") == 0) {
check(android.os.SystemClock.elapsedRealtime() < until) { "Provider did not open the pipe" }
Thread.sleep(20)
}
executor.submit { withImageMemory { Unit } }.get(2, TimeUnit.SECONDS)
assertFalse(capture.isDone)
} finally {
signal.cancel()
context.contentResolver.call(uri, "release", null, null)
try { capture.get(5, TimeUnit.SECONDS) } finally { executor.shutdownNow() }
}
}

@Test fun blockedContentPipeExpiresAndStillCompletesTextCallback() {
val uri = android.net.Uri.parse("content://life.andre.message487.test.images/slow")
context.contentResolver.call(uri, "release", null, null)
Expand Down
100 changes: 80 additions & 20 deletions app/src/main/java/life/andre/message487/ConnectionViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
Expand Down Expand Up @@ -64,21 +66,55 @@ class ConnectionViewModel @JvmOverloads constructor(application: Application,
internal val previewCandidates = mutableCandidates.asStateFlow()
private var previewClosed = false

fun exportDocument(uri: android.net.Uri, includeToken: Boolean) = action(R.string.settings_exported) {
val json = exportSettings(graph.settings.load(), includeToken)
require(json.toByteArray(Charsets.UTF_8).size <= MAX_SETTINGS_FILE_BYTES)
requireNotNull(getApplication<Application>().contentResolver.openOutputStream(uri, "wt")).use {
it.write(json.toByteArray(Charsets.UTF_8))
private var transferJob: Job? = null
private val mutableTransferring = MutableStateFlow(false)
val transferring = mutableTransferring.asStateFlow()

fun cancelTransfer() { transferJob?.cancel() }

private fun transfer(errorNotice: Int, operation: suspend () -> Unit) {
if (mutableTransferring.value || !settingsLoaded.value) return
mutableTransferring.value = true
transferJob = viewModelScope.launch {
try {
if (withTimeoutOrNull(30_000) { operation(); true } == null) {
mutableState.value = state.value.copy(notice = R.string.document_timeout)
}
} catch (cancelled: kotlinx.coroutines.CancellationException) { throw cancelled }
catch (_: Exception) { mutableState.value = state.value.copy(notice = errorNotice) }
finally { mutableTransferring.value = false }
}
}

fun exportDocument(uri: android.net.Uri, includeToken: Boolean) = transfer(R.string.local_error) {
documentIo.providerOperation { signal ->
val bytes = exportSettings(graph.settings.load(), includeToken).toByteArray(Charsets.UTF_8)
require(bytes.size <= MAX_SETTINGS_FILE_BYTES)
withDocument(uri, "wt", signal) { asset ->
asset.createOutputStream().use { it.write(bytes) }
}
}
mutableState.value = state.value.copy(notice = R.string.settings_exported)
}

fun importDocument(uri: android.net.Uri) = action(failureNotice = R.string.invalid_settings_file) {
try {
val text = requireNotNull(getApplication<Application>().contentResolver.openInputStream(uri)).use(::readSettingsFile)
mutableImport.value = importSettings(text, graph.settings.load())
} catch (error: Exception) {
// Parser/provider errors can include file contents or credentials. Do not log them.
throw java.io.IOException("Settings file could not be imported")
fun importDocument(uri: android.net.Uri) = transfer(R.string.invalid_settings_file) {
mutableImport.value = documentIo.providerOperation { signal ->
val text = withDocument(uri, "r", signal) { asset ->
asset.createInputStream().use(::readSettingsFile)
}
signal.throwIfCanceled()
importSettings(text, graph.settings.load())
}
}

private fun <T> withDocument(uri: android.net.Uri, mode: String, signal: android.os.CancellationSignal,
action: (android.content.res.AssetFileDescriptor) -> T): T {
val resolver = getApplication<Application>().contentResolver
signal.throwIfCanceled()
return requireNotNull(resolver.openAssetFileDescriptor(uri, mode, signal)).use { asset ->
signal.setOnCancelListener { runCatching { asset.close() } }
try { signal.throwIfCanceled(); action(asset) }
finally { signal.setOnCancelListener(null) }
}
}

Expand Down Expand Up @@ -112,15 +148,37 @@ class ConnectionViewModel @JvmOverloads constructor(application: Application,
mutableCandidates.value = NotificationCaptureService.previewCandidates(settings.value.packages)
}

internal fun previewNotification(key: String) = action {
val config = graph.settings.load()
val notification = NotificationCaptureService.preview(key, config)
try { replacePreview(EventPreview(graph.notificationEvent(notification, config), config, notification.imageWarning)) }
catch (error: Exception) { discardImages(notification.images); throw error }
mutableCandidates.value = null
private var previewJob: Job? = null
private val mutableLoadingPreview = MutableStateFlow(false)
internal val loadingPreview = mutableLoadingPreview.asStateFlow()

internal fun previewNotification(key: String) {
if (previewJob?.isActive == true || state.value.busy) return
mutableLoadingPreview.value = true
previewJob = viewModelScope.launch {
try {
val completed = withTimeoutOrNull(10_000) {
val result = previewIo.providerOperation(discard = { discardImages(it.event.images) }) { signal ->
val config = graph.settings.load()
val notification = NotificationCaptureService.preview(key, config, signal)
try { EventPreview(graph.notificationEvent(notification, config), config, notification.imageWarning) }
catch (error: Exception) { discardImages(notification.images); throw error }
}
replacePreview(result)
mutableCandidates.value = null
true
}
if (completed == null) mutableState.value = state.value.copy(notice = R.string.preview_timeout)
} catch (cancelled: kotlinx.coroutines.CancellationException) { throw cancelled }
catch (_: Exception) { mutableState.value = state.value.copy(notice = R.string.local_error) }
finally { mutableLoadingPreview.value = false }
}
}

internal fun dismissCandidates() { mutableCandidates.value = null }
internal fun dismissCandidates() {
previewJob?.cancel()
mutableCandidates.value = null
}

@Synchronized private fun replacePreview(value: EventPreview) {
if (previewClosed) { discardImages(value.event.images); return }
Expand Down Expand Up @@ -296,7 +354,7 @@ class ConnectionViewModel @JvmOverloads constructor(application: Application,
}
fun pause(paused: Boolean) = action {
graph.settings.update { it.copy(paused = paused) }
if (!paused) graph.recover()
if (!paused) graph.scheduler.requestRecovery()
}
fun retry(id: String) = action {
if (graph.outbox.retry(id)) {
Expand All @@ -323,6 +381,8 @@ class ConnectionViewModel @JvmOverloads constructor(application: Application,
}
}
}
fun showDocumentPickerError() { mutableState.value = state.value.copy(notice = R.string.document_picker_unavailable) }

fun showSettingsError() { mutableState.value = state.value.copy(notice = R.string.settings_unavailable) }

private fun action(notice: Int? = null, failureNotice: Int = R.string.local_error, block: () -> Unit) {
Expand Down
5 changes: 5 additions & 0 deletions app/src/main/java/life/andre/message487/DeliveryWorker.kt
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ class DeliveryScheduler(context: Context) {
return manager.enqueueUniqueWork("event-$id", if (replace) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.KEEP, work)
}

fun requestRecovery() = manager.enqueueUniqueWork("outbox-recovery-now", ExistingWorkPolicy.KEEP,
OneTimeWorkRequestBuilder<RecoveryWorker>().build())

fun startRecovery() {
manager.enqueueUniquePeriodicWork("outbox-recovery", ExistingPeriodicWorkPolicy.KEEP,
PeriodicWorkRequestBuilder<RecoveryWorker>(15, TimeUnit.MINUTES).build())
Expand All @@ -47,6 +50,8 @@ class DeliveryWorker(context: Context, parameters: WorkerParameters) : Coroutine
if (pauseBlocksDelivery(graph.settings.load().paused, inputData.getBoolean("manual_test", false))) return@withContext Result.retry()
val attempt = try {
graph.outbox.beginAttempt(id)
} catch (_: PayloadMemoryException) {
return@withContext Result.retry()
} catch (databaseError: android.database.SQLException) {
throw databaseError
} catch (error: Exception) {
Expand Down
4 changes: 3 additions & 1 deletion app/src/main/java/life/andre/message487/EventPreview.kt
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,17 @@ internal data class EventPreview(val event: MessageEvent, val settings: Forwardi
@Composable
internal fun EventPreviewDialogs(model: ConnectionViewModel, busy: Boolean, paused: Boolean) {
val preview by model.preview.collectAsState()
val loading by model.loadingPreview.collectAsState()
val candidates by model.previewCandidates.collectAsState()
candidates?.let { notifications ->
AlertDialog(onDismissRequest = { if (!busy) model.dismissCandidates() },
title = { Text(stringResource(R.string.preview_notifications)) },
text = { Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
SupportingText(stringResource(R.string.preview_capture_hint))
if (loading) LinearProgressIndicator(Modifier.fillMaxWidth())
if (notifications.isEmpty()) Text(stringResource(R.string.preview_no_notifications))
notifications.forEach { notification ->
OutlinedButton(onClick = { model.previewNotification(notification.key) }, enabled = !busy,
OutlinedButton(onClick = { model.previewNotification(notification.key) }, enabled = !busy && !loading,
modifier = Modifier.fillMaxWidth()) {
Text(notification.packageName + "\n" + notification.title, maxLines = 3)
}
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/java/life/andre/message487/MessageGraph.kt
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class MessageGraph internal constructor(private val context: Application) {
submitCapture {
settings.update { it }
scheduler.startRecovery()
recover()
scheduler.requestRecovery()
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class NotificationCaptureService : NotificationListenerService() {
ListenerState.mutableConnected.value = true
val graph = MessageGraph.get(this)
graph.submitCapture {
try { graph.recover() } catch (error: Exception) { graph.captureFailed(error) }
try { graph.scheduler.requestRecovery() } catch (error: Exception) { graph.captureFailed(error) }
}
}

Expand Down Expand Up @@ -106,14 +106,15 @@ class NotificationCaptureService : NotificationListenerService() {
it.notification.flags and Notification.FLAG_GROUP_SUMMARY == 0 }
.sortedByDescending { it.postTime }.take(20).map(::notificationContent)

internal fun preview(key: String, config: ForwardingSettings): CapturedNotification {
internal fun preview(key: String, config: ForwardingSettings, cancellation: android.os.CancellationSignal): CapturedNotification {
val listener = requireNotNull(activeListener.get()) { "Notification listener disconnected" }
val current = listener.getActiveNotifications(arrayOf(key)).firstOrNull()
?: error("Notification is no longer available")
require(current.packageName in config.packages && current.packageName != listener.packageName)
var imageWarning = false
val images = notificationImages(listener, current.notification, config, current.packageName) { imageWarning = true }
return notificationContent(current).copy(images = images, imageWarning = imageWarning)
val content = notificationContent(current)
val images = notificationImages(listener, current.notification, config, current.packageName, cancellation) { imageWarning = true }
return content.copy(images = images, imageWarning = imageWarning)
}
}

Expand Down
Loading
Loading