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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
Android-App mit Homescreen-Widget für [Backrest](https://github.com/garethgeorge/backrest) (restic-Web-UI).

- **Laufende Backups**: Welcher Plan gerade sichert, mit Fortschritt in %, Datenmenge, Dateien und aktueller Datei. Prüfung, Prune, Hooks usw. werden ebenfalls angezeigt. In der App lassen sie sich abbrechen.
- **Warteschlange**: Backrest arbeitet Aufgaben nacheinander ab. Fällige, aber noch wartende Backups und Repo-Aufgaben (z. B. hinter einer langen Prüfung) erscheinen unter „Wartet in der Warteschlange“ mit Platz und Wartezeit; die Plan-Karte und das Widget zeigen „wartet seit … · Platz n“, die Statuszeile „… · 3 warten“.
- **Remote-Instanzen (Multihost)**: Ist dein Backrest ein Multihost-Server, erscheinen die Pläne der verbundenen Clients (z. B. VPS) mit Instanzname, Verbindungsstatus, letztem und nächstem Backup. Starten und abbrechen lassen sie sich nur auf der jeweiligen Instanz.
- **Widget**: Gesamtstatus (grün/blau/orange/rot), je Plan letztes Backup und nächster Lauf, Aktualisieren-Button, Offline-Anzeige mit letztem Stand. Größe frei veränderbar; flach gezogen zeigt es nur die Statuszeile. Material You ab Android 12, Dark Mode.
- **App**: Pläne mit letztem Backup, Dauer, nächstem Lauf, 30-Tage-Statistik und Verlaufsbalken; Repositories mit gesicherter Größe; „Backup starten“ je Plan; Link zur Weboberfläche.
Expand Down
4 changes: 2 additions & 2 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ android {
applicationId = "at.daschmidt.backrestwidget"
minSdk = 26
targetSdk = 36
versionCode = 7
versionName = "0.5.1"
versionCode = 8
versionName = "0.6.0"
}

signingConfigs {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ class BackrestClient(private val settings: Settings) {
}

/** The newest [lastN] operations of all plans and repositories (empty selector). */
fun recentOperations(lastN: Int = 100): JSONObject =
fun recentOperations(lastN: Int = 200): JSONObject =
call("GetOperations", JSONObject().put("selector", JSONObject()).put("lastN", lastN.toString()))

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,12 @@ class BackrestWidget : AppWidgetProvider() {
showProgress(context, row, active, plan.instance)
return row
}
val waiting = snapshot.queuedBackup(plan)
if (waiting != null && !plan.running) {
row.setTextViewText(R.id.row_last, "wartet")
row.setTextViewText(R.id.row_next, Format.waiting(context, waiting.first, waiting.second))
return row
}
val last = plan.lastFinished
row.setTextViewText(
R.id.row_last,
Expand Down
8 changes: 7 additions & 1 deletion app/src/main/java/at/daschmidt/backrestwidget/Format.kt
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ object Format {
val failed = snapshot.plans.count { it.health == Health.ERROR }
val warned = snapshot.plans.count { it.health == Health.WARNING }
val running = snapshot.running
return when {
val base = when {
snapshot.plans.isEmpty() && running.isEmpty() -> "Keine Pläne"
failed > 0 -> "$failed fehlgeschlagen"
warned > 0 -> if (warned == 1) "1 Warnung" else "$warned Warnungen"
Expand All @@ -93,8 +93,14 @@ object Format {
snapshot.plans.any { it.running } -> "Backup läuft"
else -> "Alles OK"
}
val waiting = snapshot.queued.size
return if (waiting == 0) base else "$base · $waiting ${if (waiting == 1) "wartet" else "warten"}"
}

/** "wartet seit 00:00 · Platz 2" for a queued operation. */
fun waiting(context: Context, op: QueuedOp, position: Int): String =
"wartet seit ${time(context, op.dueMs)} · Platz $position"

fun connectionLabel(state: String): String = when (state) {
"connected" -> "verbunden"
"disconnected" -> "getrennt"
Expand Down
32 changes: 28 additions & 4 deletions app/src/main/java/at/daschmidt/backrestwidget/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ class MainActivity : Activity() {
// Keep polling while in front; closely while something runs.
handler.removeCallbacks(poll)
if (resumed) {
val busy = settings.snapshot?.running?.isNotEmpty() == true
val busy = settings.snapshot?.let { it.running.isNotEmpty() || it.queued.isNotEmpty() } == true
handler.postDelayed(poll, if (busy) POLL_RUNNING_MS else POLL_IDLE_MS)
}
}
Expand Down Expand Up @@ -118,10 +118,18 @@ class MainActivity : Activity() {
findViewById<View>(R.id.running_label).visibility =
if (snapshot?.running.isNullOrEmpty()) View.GONE else View.VISIBLE

val queue = findViewById<LinearLayout>(R.id.queued)
queue.removeAllViews()
snapshot?.queued?.forEachIndexed { index, op -> queue.addView(queuedView(inflater, queue, op, index + 1)) }
findViewById<View>(R.id.queued_label).visibility =
if (snapshot?.queued.isNullOrEmpty()) View.GONE else View.VISIBLE

val plans = findViewById<LinearLayout>(R.id.plans)
plans.removeAllViews()
snapshot?.plans?.forEach { plan ->
plans.addView(planView(inflater, plans, plan, snapshot.remotes.firstOrNull { it.instance == plan.instance }))
plans.addView(
planView(inflater, plans, plan, snapshot.remotes.firstOrNull { it.instance == plan.instance }, snapshot.queuedBackup(plan))
)
}
findViewById<View>(R.id.plans_label).visibility = if (snapshot?.plans.isNullOrEmpty()) View.GONE else View.VISIBLE

Expand All @@ -140,7 +148,13 @@ class MainActivity : Activity() {
findViewById<View>(R.id.repos_label).visibility = if (snapshot?.repos.isNullOrEmpty()) View.GONE else View.VISIBLE
}

private fun planView(inflater: LayoutInflater, parent: LinearLayout, plan: PlanState, remote: RemoteState?): View {
private fun planView(
inflater: LayoutInflater,
parent: LinearLayout,
plan: PlanState,
remote: RemoteState?,
queuedBackup: Pair<QueuedOp, Int>?,
): View {
val view = inflater.inflate(R.layout.item_plan, parent, false)
view.findViewById<ImageView>(R.id.plan_dot).setColorFilter(Format.healthColor(this, plan.health))
view.findViewById<TextView>(R.id.plan_name).text = plan.id
Expand All @@ -162,6 +176,7 @@ class MainActivity : Activity() {
plan.activeBackup != null ->
listOfNotNull("Backup läuft gerade", Format.percent(plan.activeBackup)).joinToString(" · ")
plan.running -> "Backup läuft gerade"
queuedBackup != null -> "Backup ${Format.waiting(this, queuedBackup.first, queuedBackup.second)} in der Warteschlange"
plan.nextBackupMs != null -> "Nächstes Backup: ${Format.dateTime(this, plan.nextBackupMs)}"
else -> "Kein Zeitplan"
}
Expand All @@ -187,7 +202,7 @@ class MainActivity : Activity() {
view.findViewById<Button>(R.id.plan_backup).apply {
// Backrest offers no API to start a backup on a remote instance.
visibility = if (plan.isRemote) View.GONE else View.VISIBLE
isEnabled = !plan.running
isEnabled = !plan.running && queuedBackup == null
setOnClickListener { confirmBackup(plan.id) }
}
return view
Expand Down Expand Up @@ -219,6 +234,15 @@ class MainActivity : Activity() {
return view
}

private fun queuedView(inflater: LayoutInflater, parent: LinearLayout, op: QueuedOp, position: Int): View {
val view = inflater.inflate(R.layout.item_queued, parent, false)
view.findViewById<TextView>(R.id.queued_title).text = op.title
view.findViewById<TextView>(R.id.queued_position).text = "#$position"
view.findViewById<TextView>(R.id.queued_info).text =
"Fällig ${Format.dateTime(this, op.dueMs)} · wartet seit ${Format.duration(System.currentTimeMillis() - op.dueMs)}"
return view
}

private fun confirmCancel(op: RunningOp) {
AlertDialog.Builder(this)
.setTitle("Abbrechen?")
Expand Down
77 changes: 75 additions & 2 deletions app/src/main/java/at/daschmidt/backrestwidget/Models.kt
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,49 @@ data class RunningOp(
}
}

/**
* An operation that is due but still waits in Backrest's task queue. Backrest
* runs one task at a time, so e.g. a long repository check delays every backup
* scheduled meanwhile. Future runs (start time not reached yet) are not queued.
*/
data class QueuedOp(
val id: Long,
val kind: OpKind,
/** Plan ID, null for repository tasks under Backrest's "_system_" pseudo plan. */
val planId: String?,
val repoId: String,
/** Scheduled start time: the operation has been waiting since then. */
val dueMs: Long,
val instance: String = "",
) {
val title: String get() = if (planId != null) "${kind.label} · $planId" else "${kind.label} · Repo $repoId"

companion object {
fun from(op: JSONObject, nowMs: Long): QueuedOp? {
if (OpStatus.parse(op.opt("status")) != OpStatus.PENDING) return null
val kind = OpKind.of(op)
if (kind == OpKind.INDEX) return null
val due = op.longOrNull("unixTimeStartMs") ?: return null
if (due > nowMs) return null
return QueuedOp(
id = op.longOrNull("id") ?: return null,
kind = kind,
planId = op.optString("planId").takeUnless { it.isEmpty() || it.startsWith("_") },
repoId = op.optString("repoId"),
dueMs = due,
instance = op.optString("instanceId"),
)
}

/** Due operations of this server (remote instances run their own queue), in expected run order. */
fun fromOperations(list: JSONObject?, nowMs: Long, remoteInstances: Set<String>): List<QueuedOp> =
list?.optJSONArray("operations").objects().mapNotNull { from(it, nowMs) }
.filter { it.instance !in remoteInstances }
.distinctBy { it.id }
.sortedWith(compareBy({ it.dueMs }, { it.id }))
}
}

/** A failed operation other than a backup, e.g. prune, check, forget or a hook. */
data class FailedTask(
val id: Long,
Expand Down Expand Up @@ -213,7 +256,16 @@ data class Snapshot(
val running: List<RunningOp> = emptyList(),
/** Remote instances of a multihost server. Their plans are part of [plans]. */
val remotes: List<RemoteState> = emptyList(),
/** Due operations waiting in the task queue, in expected run order. */
val queued: List<QueuedOp> = emptyList(),
) {
/** The queued backup of a plan and its 1-based position in the queue, if it waits. */
fun queuedBackup(plan: PlanState): Pair<QueuedOp, Int>? {
if (plan.isRemote) return null
val index = queued.indexOfFirst { it.kind == OpKind.BACKUP && it.planId == plan.id }
return if (index < 0) null else queued[index] to index + 1
}

/** Whether an operation runs on a remote instance rather than on the server itself. */
fun isRemote(op: RunningOp): Boolean = remotes.any { it.instance == op.instance }

Expand Down Expand Up @@ -243,6 +295,16 @@ data class Snapshot(
}
}))
put("running", JSONArray(running.map { it.toJson() }))
put("queued", JSONArray(queued.map { q ->
JSONObject().apply {
put("id", q.id)
put("kind", q.kind.name)
put("planId", q.planId ?: "")
put("repoId", q.repoId)
put("dueMs", q.dueMs)
put("instance", q.instance)
}
}))
put("remotes", JSONArray(remotes.map { r ->
JSONObject().apply {
put("instance", r.instance)
Expand Down Expand Up @@ -295,7 +357,17 @@ data class Snapshot(
bytesAdded30d = r.optLong("bytesAdded30d"),
)
}
return Snapshot(o.getLong("fetchedAtMs"), plans, repos, running, remotes)
val queued = o.optJSONArray("queued").objects().map { q ->
QueuedOp(
id = q.getLong("id"),
kind = OpKind.valueOf(q.getString("kind")),
planId = q.optString("planId").ifEmpty { null },
repoId = q.optString("repoId"),
dueMs = q.getLong("dueMs"),
instance = q.optString("instance"),
)
}
return Snapshot(o.getLong("fetchedAtMs"), plans, repos, running, remotes, queued)
}

/**
Expand Down Expand Up @@ -336,7 +408,8 @@ data class Snapshot(
val id = s.optString("id").ifEmpty { return@mapNotNull null }
RepoState(id, s.longOrNull("protectedBytes")?.takeIf { it > 0 }, s.longOrNull("bytesAddedLast30days") ?: 0)
}.sortedBy { it.id.lowercase() }
return Snapshot(nowMs, plans + remotePlans, repos, running, remotes)
val queued = QueuedOp.fromOperations(operations, nowMs, remoteIds)
return Snapshot(nowMs, plans + remotePlans, repos, running, remotes, queued)
}

/** Derive a remote plan's state from its synced operations (the summary dashboard only covers local plans). */
Expand Down
12 changes: 12 additions & 0 deletions app/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,18 @@
android:layout_height="wrap_content"
android:orientation="vertical" />

<TextView
android:id="@+id/queued_label"
style="@style/SectionLabel"
android:text="@string/queued"
android:visibility="gone" />

<LinearLayout
android:id="@+id/queued"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />

<TextView
android:id="@+id/plans_label"
style="@style/SectionLabel"
Expand Down
31 changes: 31 additions & 0 deletions app/src/main/res/layout/item_queued.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/Card"
android:orientation="vertical">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">

<TextView
android:id="@+id/queued_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="@color/text_primary"
android:textSize="16sp"
android:textStyle="bold" />

<TextView
android:id="@+id/queued_position"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/status_warning"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>

<TextView android:id="@+id/queued_info" style="@style/Secondary" />
</LinearLayout>
1 change: 1 addition & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<string name="no_data">Noch keine Daten</string>
<string name="plans">Pläne</string>
<string name="running">Läuft gerade</string>
<string name="queued">Wartet in der Warteschlange</string>
<string name="cancel_operation">Abbrechen</string>
<string name="repos">Repositories</string>
<string name="start_backup">Backup starten</string>
Expand Down
28 changes: 28 additions & 0 deletions app/src/test/java/at/daschmidt/backrestwidget/SnapshotTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,34 @@ class RunningOperationsTest {
assertEquals(s, Snapshot.fromJson(s.toJson()))
}

@Test
fun dueOperationsWaitInQueue() {
val dashboard = JSONObject("""{"planSummaries":[{"id":"home"},{"id":"photos"},{"id":"idle"}]}""")
val ops = JSONObject(
"""{"operations":[
{"id":"10","instanceId":"server","planId":"_system_","repoId":"pics","status":"STATUS_INPROGRESS","unixTimeStartMs":"1500","operationCheck":{}},
{"id":"11","instanceId":"server","planId":"photos","repoId":"pics","status":"STATUS_PENDING","unixTimeStartMs":"1800","operationBackup":{}},
{"id":"12","instanceId":"server","planId":"home","repoId":"local","status":"STATUS_PENDING","unixTimeStartMs":"1000","operationBackup":{}},
{"id":"13","instanceId":"server","planId":"idle","repoId":"local","status":"STATUS_PENDING","unixTimeStartMs":"9000","operationBackup":{}},
{"id":"14","instanceId":"vps","planId":"system","repoId":"vps","status":"STATUS_PENDING","unixTimeStartMs":"1200","operationBackup":{}},
{"id":"15","instanceId":"server","planId":"_system_","repoId":"local","status":"STATUS_PENDING","unixTimeStartMs":"1000","operationStats":{}}
]}"""
)
val remote = RemoteState("vps", "connected", null, listOf("system"))
val s = Snapshot.fromDashboard(dashboard, 2000, ops, listOf(remote))
// future runs and the remote instance's own queue are not waiting here; order by due time
assertEquals(listOf(12L, 15L, 11L), s.queued.map { it.id })
assertEquals("Statistik · Repo local", s.queued[1].title)
val home = s.queuedBackup(s.plans.first { it.id == "home" })!!
assertEquals(12L, home.first.id)
assertEquals(1, home.second)
assertEquals(3, s.queuedBackup(s.plans.first { it.id == "photos" })!!.second)
assertNull(s.queuedBackup(s.plans.first { it.id == "idle" }))
assertNull(s.queuedBackup(s.plans.first { it.isRemote }))
assertEquals("Prüfung läuft · 3 warten", Format.overall(s))
assertEquals(s, Snapshot.fromJson(s.toJson()))
}

@Test
fun withoutOperationsNothingRuns() {
val s = Snapshot.fromDashboard(JSONObject("""{"planSummaries":[{"id":"a"}]}"""), 0, null)
Expand Down
Loading