From 08c535b95018cfb3fa03d49a05a4ddc95336936c Mon Sep 17 00:00:00 2001 From: "Luis Guzman (AppDevForAll)" Date: Fri, 23 Oct 2026 01:31:27 -0600 Subject: [PATCH] K2GO-427 feat(contentexchange): delete selected content to reclaim space Wire the content manager Delete action: a destructive confirm, then a foreground service that removes each selected item on the box through DELETE /v1/content/{app}/{localRef}, accumulating reclaimed bytes and refreshing the manager (list + used/free) on settle. Layered feature package (DeleteJob/DeleteResult/ContentDeleteSource + CxCoreDeleteSource + DeleteSession/ContentDeleteService/progress fragment), per-item queue with per-item retry. No SAF and no new permission: delete touches the box, not a drive. Strings parked in strings_untranslated.xml for the closing l10n PR. --- controller/app/src/main/AndroidManifest.xml | 9 + .../data/CxCoreDataSource.java | 32 ++ .../data/CxCoreDeleteSource.java | 42 +++ .../domain/ContentDeleteSource.java | 17 ++ .../contentexchange/domain/DeleteJob.java | 159 ++++++++++ .../contentexchange/domain/DeleteResult.java | 40 +++ .../ContentDeleteProgressFragment.java | 145 +++++++++ .../presentation/ContentDeleteService.java | 284 ++++++++++++++++++ .../presentation/ContentManagerFragment.java | 80 ++++- .../presentation/DeleteSession.java | 172 +++++++++++ .../k2go/notifications/NotificationIds.java | 1 + .../layout/fragment_k2go_content_delete.xml | 118 ++++++++ .../main/res/values/strings_untranslated.xml | 16 +- .../contentexchange/domain/DeleteJobTest.java | 98 ++++++ 14 files changed, 1210 insertions(+), 3 deletions(-) create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreDeleteSource.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentDeleteSource.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/DeleteJob.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/DeleteResult.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentDeleteProgressFragment.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentDeleteService.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/DeleteSession.java create mode 100644 controller/app/src/main/res/layout/fragment_k2go_content_delete.xml create mode 100644 controller/app/src/test/java/org/appdevforall/k2go/contentexchange/domain/DeleteJobTest.java diff --git a/controller/app/src/main/AndroidManifest.xml b/controller/app/src/main/AndroidManifest.xml index 284b027d1..f0aef1def 100644 --- a/controller/app/src/main/AndroidManifest.xml +++ b/controller/app/src/main/AndroidManifest.xml @@ -230,6 +230,15 @@ android:value="Exports selected library content to a user-chosen drive through the co-located server REST engine." /> + + + + diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreDataSource.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreDataSource.java index 9d236a47a..101e0f6a0 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreDataSource.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreDataSource.java @@ -37,6 +37,9 @@ public final class CxCoreDataSource { private static final int CONNECT_TIMEOUT_MS = 5000; private static final int READ_TIMEOUT_MS = 20000; + /** Delete blocks on the box's own delete (Kolibri deletechannel, Kiwix reindex), which can run + * well past the read-side timeout, so it waits longer than a plain read. */ + private static final int DELETE_READ_TIMEOUT_MS = 120000; /** {@code GET /v1/apps} -> {@code {"apps": [...]}}. */ public JSONObject getApps() throws Exception { @@ -58,6 +61,15 @@ public JSONObject postExportPlan(JSONObject body) throws Exception { return postJson(V1 + "/export/plan", body); } + /** + * {@code DELETE /v1/content/{app}/{localRef}} -> {@code {ok, freedBytes}} on success or + * {@code {ok:false, reason}} on an adapter failure. Path segments are percent-encoded (the core + * decodes them). A 4xx/5xx (e.g. 404 for an item already gone) throws, like the other calls. + */ + public JSONObject deleteContent(String app, String localRef) throws Exception { + return deleteJson(V1 + "/content/" + encodeSegment(app) + "/" + encodeSegment(localRef)); + } + /** * {@code GET /v1/export/item/{app}/{localRef}} -> the item's streaming archive. The core sends a * chunked response with no Content-Length; the caller streams the body and closes the returned @@ -112,6 +124,26 @@ private static JSONObject postJson(String urlStr, JSONObject body) throws Except } } + private static JSONObject deleteJson(String urlStr) throws Exception { + HttpURLConnection c = (HttpURLConnection) new URL(urlStr).openConnection(); + try { + c.setUseCaches(false); + c.setConnectTimeout(CONNECT_TIMEOUT_MS); + c.setReadTimeout(DELETE_READ_TIMEOUT_MS); + c.setRequestMethod("DELETE"); + c.setRequestProperty("Accept", "application/json"); + int code = c.getResponseCode(); + boolean ok = code >= 200 && code < 400; + String text = readAll(ok ? c.getInputStream() : c.getErrorStream()); + if (!ok) { + throw new Exception("HTTP " + code + ": " + text); + } + return new JSONObject(text.isEmpty() ? "{}" : text); + } finally { + c.disconnect(); + } + } + private static JSONObject getJson(String urlStr) throws Exception { HttpURLConnection c = (HttpURLConnection) new URL(urlStr).openConnection(); try { diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreDeleteSource.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreDeleteSource.java new file mode 100644 index 000000000..5a673899f --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreDeleteSource.java @@ -0,0 +1,42 @@ +/* + * ============================================================================ + * Name : CxCoreDeleteSource.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-427. Data-layer implementation of the delete source port against + * cx-core (through dash-node's /v1 relay): DELETE /v1/content/{app}/{localRef}. + * Maps the core JSON {ok, freedBytes} | {ok:false, reason} onto the domain + * DeleteResult, so the domain stays JSON-free. + * ============================================================================ + */ +package org.appdevforall.k2go.contentexchange.data; + +import org.appdevforall.k2go.contentexchange.domain.ContentDeleteSource; +import org.appdevforall.k2go.contentexchange.domain.DeleteResult; +import org.appdevforall.k2go.contentexchange.domain.ItemRef; +import org.json.JSONObject; + +/** + * Deletes one item on the box and maps the response to {@link DeleteResult}. + * + *

Stateless and thread-confined to the delete worker. A transport failure (box unreachable, a + * 4xx/5xx) throws; a reached box that could not delete the item returns {@code {ok:false, reason}}, + * which maps to {@link DeleteResult#failure}. + */ +public final class CxCoreDeleteSource implements ContentDeleteSource { + + private final CxCoreDataSource dataSource; + + public CxCoreDeleteSource(CxCoreDataSource dataSource) { + this.dataSource = dataSource; + } + + @Override + public DeleteResult delete(ItemRef ref) throws Exception { + JSONObject response = dataSource.deleteContent(ref.app(), ref.localRef()); + if (response.optBoolean("ok", false)) { + return DeleteResult.ok(response.optLong("freedBytes", 0L)); + } + return DeleteResult.failure(response.optString("reason", response.optString("error", ""))); + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentDeleteSource.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentDeleteSource.java new file mode 100644 index 000000000..0442949d6 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentDeleteSource.java @@ -0,0 +1,17 @@ +package org.appdevforall.k2go.contentexchange.domain; + +/** + * Domain port for the BOX side of a delete: remove one item from the box and report what it + * reclaimed. The Data layer implements it against the core REST API (through dash-node's + * {@code /v1/*} relay: {@code DELETE /v1/content/{app}/{localRef}}); the domain never learns the + * transport or the JSON shape. + * + *

The box owns the real deletion (it delegates to each app's own delete, never removes files + * blindly), so there is no client-side "is this deletable" rule to duplicate here: the item address + * is all this port needs. Must be called off the main thread. + */ +public interface ContentDeleteSource { + + /** Delete one item on the box. Returns the outcome; throws only when the box is unreachable. */ + DeleteResult delete(ItemRef ref) throws Exception; +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/DeleteJob.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/DeleteJob.java new file mode 100644 index 000000000..b4848b743 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/DeleteJob.java @@ -0,0 +1,159 @@ +package org.appdevforall.k2go.contentexchange.domain; + +/** + * The pure state of one delete run: a per-item status plus the bytes each delete reclaimed, and the + * derived overall progress. The service mutates it as it drains the queue; the UI reads the derived + * figures. No Android, no IO: unit-testable on a plain JVM. + * + *

Delete is atomic per item (the box removes the item or it fails), so there is no within-item + * byte progress like the export copy has: overall progress is settled-item count, not a byte ratio. + * The item is the unit of resume (ADR "Resilience"): a failed item is re-queued and re-done on its + * own; the rest are untouched. The arrays are indexed by the original request order and set to one + * length in {@link #begin}, so the UI can never read a length mismatch. + */ +public final class DeleteJob { + + public static final int PENDING = 0; + public static final int ACTIVE = 1; + public static final int DONE = 2; + public static final int FAILED = 3; + + private int[] status = new int[0]; + /** Bytes reclaimed per item, as the box reported for each successful delete. */ + private long[] freed = new long[0]; + private int index = -1; + + /** Start a run over {@code count} items, all PENDING. */ + public void begin(int count) { + int n = Math.max(0, count); + status = new int[n]; + freed = new long[n]; + index = -1; + } + + public int size() { + return status.length; + } + + public int status(int i) { + return i >= 0 && i < status.length ? status[i] : FAILED; + } + + public long freed(int i) { + return i >= 0 && i < freed.length ? freed[i] : 0L; + } + + /** The item currently being deleted, or -1 when none is active. */ + public int index() { + return index; + } + + /** The first item still waiting, or -1 when the queue is drained. */ + public int firstPending() { + for (int i = 0; i < status.length; i++) { + if (status[i] == PENDING) { + return i; + } + } + return -1; + } + + public void setActive(int i) { + if (i >= 0 && i < status.length) { + status[i] = ACTIVE; + index = i; + } + } + + /** Mark item {@code i} deleted and record the bytes the box reclaimed for it. */ + public void setDone(int i, long freedBytes) { + if (i >= 0 && i < status.length) { + status[i] = DONE; + freed[i] = Math.max(0L, freedBytes); + } + } + + public void setFailed(int i) { + if (i >= 0 && i < status.length) { + status[i] = FAILED; + freed[i] = 0L; + } + } + + /** Re-queue every failed item (reset its reclaimed figure) for a retry. Returns how many changed. */ + public int requeueFailed() { + int changed = 0; + for (int i = 0; i < status.length; i++) { + if (status[i] == FAILED) { + status[i] = PENDING; + freed[i] = 0L; + changed++; + } + } + return changed; + } + + public boolean hasFailed() { + for (int st : status) { + if (st == FAILED) { + return true; + } + } + return false; + } + + public int doneCount() { + return count(DONE); + } + + public int failedCount() { + return count(FAILED); + } + + private int count(int target) { + int c = 0; + for (int st : status) { + if (st == target) { + c++; + } + } + return c; + } + + /** No item is still pending or active (the run has settled; some may have failed). */ + public boolean isSettled() { + if (status.length == 0) { + return false; + } + for (int st : status) { + if (st == PENDING || st == ACTIVE) { + return false; + } + } + return true; + } + + /** Every item was deleted successfully. */ + public boolean allDone() { + return status.length > 0 && doneCount() == status.length; + } + + /** Total bytes reclaimed across the items deleted so far. */ + public long freedTotal() { + long t = 0L; + for (long f : freed) { + t += f; + } + return t; + } + + /** Overall percent by settled-item count (delete has no within-item byte progress). */ + public int overallPercent() { + int n = status.length; + if (n == 0) { + return 0; + } + int settled = doneCount() + failedCount(); + return (int) Math.min(100L, (long) settled * 100L / n); + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/DeleteResult.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/DeleteResult.java new file mode 100644 index 000000000..6cdd07e42 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/DeleteResult.java @@ -0,0 +1,40 @@ +package org.appdevforall.k2go.contentexchange.domain; + +/** + * The outcome of deleting one item: success with the bytes the box reclaimed, or failure with a + * reason. Immutable value object. Pure domain type: the Data layer maps the core JSON + * {@code {ok, freedBytes} | {ok:false, reason}} onto it, so the domain never learns the JSON shape. + */ +public final class DeleteResult { + + private final boolean ok; + private final long freedBytes; + private final String reason; + + private DeleteResult(boolean ok, long freedBytes, String reason) { + this.ok = ok; + this.freedBytes = freedBytes; + this.reason = reason; + } + + public static DeleteResult ok(long freedBytes) { + return new DeleteResult(true, Math.max(0L, freedBytes), ""); + } + + public static DeleteResult failure(String reason) { + return new DeleteResult(false, 0L, reason != null ? reason : ""); + } + + public boolean ok() { + return ok; + } + + /** Bytes reclaimed by this delete (0 when it failed, or when the box reported no figure). */ + public long freedBytes() { + return freedBytes; + } + + public String reason() { + return reason; + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentDeleteProgressFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentDeleteProgressFragment.java new file mode 100644 index 000000000..e2f57abe2 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentDeleteProgressFragment.java @@ -0,0 +1,145 @@ +/* + * ============================================================================ + * Name : ContentDeleteProgressFragment.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-427. Observes the ContentDeleteService session and renders the delete progress + * (overall settled-count bar + the item in flight), then the settled state (done or + * partial) with the total space reclaimed and Retry / Finish. Reads state only; all + * work is the foreground service's. + * ============================================================================ + */ +package org.appdevforall.k2go.contentexchange.presentation; + +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.fragment.app.Fragment; + +import com.google.android.material.progressindicator.LinearProgressIndicator; + +import org.appdevforall.k2go.R; +import org.appdevforall.k2go.contentexchange.domain.DeleteJob; +import org.appdevforall.k2go.util.ByteFormatter; + +public class ContentDeleteProgressFragment extends Fragment { + + private TextView overallLabel; + private LinearProgressIndicator overallBar; + private TextView overallDetail; + private TextView itemLabel; + private LinearProgressIndicator itemBar; + private TextView message; + private Button cancel; + private Button retry; + private Button finish; + + private final DeleteSession session = ContentDeleteService.session(); + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle s) { + View root = inflater.inflate(R.layout.fragment_k2go_content_delete, container, false); + overallLabel = root.findViewById(R.id.k2go_cxd_overall_label); + overallBar = root.findViewById(R.id.k2go_cxd_overall_bar); + overallDetail = root.findViewById(R.id.k2go_cxd_overall_detail); + itemLabel = root.findViewById(R.id.k2go_cxd_item_label); + itemBar = root.findViewById(R.id.k2go_cxd_item_bar); + message = root.findViewById(R.id.k2go_cxd_message); + cancel = root.findViewById(R.id.k2go_cxd_cancel); + retry = root.findViewById(R.id.k2go_cxd_retry); + finish = root.findViewById(R.id.k2go_cxd_finish); + + cancel.setOnClickListener(v -> ContentDeleteService.cancel(requireContext())); + retry.setOnClickListener(v -> ContentDeleteService.retry(requireContext())); + finish.setOnClickListener(v -> { + ContentDeleteService.finishSession(); + goBack(); + }); + return root; + } + + @Override + public void onResume() { + super.onResume(); + session.setListener(() -> { + if (isAdded()) { + render(); + } + }); + render(); + } + + @Override + public void onPause() { + super.onPause(); + session.setListener(null); + } + + private void render() { + // A cleared / absent session means the run finished and was dismissed: leave this screen. + if (!session.hasSession()) { + goBack(); + return; + } + boolean running = session.isRunning(); + String error = session.errorMessage(); + + overallBar.setProgressCompat(session.overallPercent(), true); + overallLabel.setText(getString(R.string.k2go_cx_delete_overall_fmt, session.overallPercent())); + overallDetail.setText(getString(R.string.k2go_cx_delete_reclaimed_fmt, + ByteFormatter.humanBytes(session.freedTotal()))); + + renderCurrentItem(running); + renderSettled(running, error); + + cancel.setVisibility(running ? View.VISIBLE : View.GONE); + boolean settled = !running; + retry.setVisibility(settled && session.canRetry() ? View.VISIBLE : View.GONE); + finish.setVisibility(settled ? View.VISIBLE : View.GONE); + } + + private void renderCurrentItem(boolean running) { + int i = session.index(); + if (running && i >= 0 && session.status(i) == DeleteJob.ACTIVE) { + itemLabel.setVisibility(View.VISIBLE); + itemBar.setVisibility(View.VISIBLE); + itemLabel.setText(session.label(i)); + } else { + itemLabel.setVisibility(View.GONE); + itemBar.setVisibility(View.GONE); + } + } + + private void renderSettled(boolean running, String error) { + if (running) { + message.setVisibility(View.GONE); + return; + } + int done = session.doneCount(); + int total = session.itemCount(); + String text; + if (error != null) { + text = error; + } else if (session.allDone()) { + text = getString(R.string.k2go_cx_delete_done_fmt, done, + ByteFormatter.humanBytes(session.freedTotal())); + } else { + text = getString(R.string.k2go_cx_delete_partial_fmt, done, total); + } + message.setText(text); + message.setVisibility(View.VISIBLE); + } + + private void goBack() { + if (isAdded()) { + requireActivity().getOnBackPressedDispatcher().onBackPressed(); + } + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentDeleteService.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentDeleteService.java new file mode 100644 index 000000000..7af060bc1 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentDeleteService.java @@ -0,0 +1,284 @@ +/* + * ============================================================================ + * Name : ContentDeleteService.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-427. Foreground service that drains the delete queue: per selected item, call + * the core DELETE /v1/content/{app}/{localRef} and accumulate the bytes it reclaimed. + * Reuses the download-service pattern (foreground specialUse + per-item queue + retry + * + notification). Simpler than export: the box owns the deletion, so there is no SAF + * destination, no staging, no byte copy: each item is one atomic call. The item is the + * unit of resume (per-item retry of a failed delete). + * ============================================================================ + */ +package org.appdevforall.k2go.contentexchange.presentation; + +import android.app.Notification; +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.os.Build; +import android.os.IBinder; + +import androidx.annotation.Nullable; +import androidx.core.app.NotificationCompat; +import androidx.core.content.ContextCompat; + +import org.appdevforall.k2go.R; +import org.appdevforall.k2go.contentexchange.data.CxCoreDataSource; +import org.appdevforall.k2go.contentexchange.data.CxCoreDeleteSource; +import org.appdevforall.k2go.contentexchange.domain.ContentDeleteSource; +import org.appdevforall.k2go.contentexchange.domain.DeleteJob; +import org.appdevforall.k2go.contentexchange.domain.DeleteResult; +import org.appdevforall.k2go.contentexchange.domain.ItemRef; +import org.appdevforall.k2go.notifications.NotificationIds; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public final class ContentDeleteService extends Service { + + public static final String ACTION_START = "org.appdevforall.k2go.CONTENT_DELETE_START"; + public static final String ACTION_RETRY = "org.appdevforall.k2go.CONTENT_DELETE_RETRY"; + public static final String ACTION_CANCEL = "org.appdevforall.k2go.CONTENT_DELETE_CANCEL"; + + public static final String EXTRA_APPS = "apps"; + public static final String EXTRA_LOCAL_REFS = "localRefs"; + public static final String EXTRA_LABELS = "labels"; + + private static final String CHANNEL_ID = "content_delete_channel"; + private static final int NOTIFICATION_ID = NotificationIds.CONTENT_DELETE; + + /** The single run state the progress fragment observes. */ + private static final DeleteSession SESSION = new DeleteSession(); + + static DeleteSession session() { + return SESSION; + } + + private final ExecutorService worker = Executors.newSingleThreadExecutor(); + + // ---- static control surface (the fragment calls these) ------------------------------------- + + public static void start(Context ctx, ItemRef[] refs, String[] labels) { + String[] apps = new String[refs.length]; + String[] locals = new String[refs.length]; + for (int i = 0; i < refs.length; i++) { + apps[i] = refs[i].app(); + locals[i] = refs[i].localRef(); + } + Intent i = new Intent(ctx, ContentDeleteService.class).setAction(ACTION_START) + .putExtra(EXTRA_APPS, apps) + .putExtra(EXTRA_LOCAL_REFS, locals) + .putExtra(EXTRA_LABELS, labels); + ContextCompat.startForegroundService(ctx, i); + } + + public static void retry(Context ctx) { + if (SESSION.canRetry()) { + ContextCompat.startForegroundService(ctx, + new Intent(ctx, ContentDeleteService.class).setAction(ACTION_RETRY)); + } + } + + public static void cancel(Context ctx) { + ContextCompat.startForegroundService(ctx, + new Intent(ctx, ContentDeleteService.class).setAction(ACTION_CANCEL)); + } + + /** Clear a settled session (the "Finish" button). Safe to call when nothing is running. */ + public static void finishSession() { + SESSION.clear(); + } + + @Override + public void onCreate() { + super.onCreate(); + createChannel(); + } + + @Nullable + @Override + public IBinder onBind(Intent intent) { + return null; + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + String action = intent != null ? intent.getAction() : null; + + if (ACTION_CANCEL.equals(action)) { + SESSION.markCancelled(); + if (SESSION.isRunning()) { + // A run is draining: the worker sees the flag, finishes the delete in flight (a sent + // DELETE cannot be aborted), exits the loop, and clears + stops itself, so the job is + // only ever mutated from the worker thread. Re-assert foreground to satisfy this + // delivery's start-foreground obligation while the worker winds down. + startForeground(NOTIFICATION_ID, buildNotification(currentLabel())); + } else { + // Nothing is draining (the run already settled): tear down here. + SESSION.clear(); + stopForeground(true); + stopSelf(); + } + return START_NOT_STICKY; + } + + if (SESSION.isRunning()) { + return START_NOT_STICKY; // a duplicate start while draining: ignore + } + + if (ACTION_RETRY.equals(action)) { + if (!SESSION.canRetry()) { + stopSelf(); + return START_NOT_STICKY; + } + SESSION.requeueFailed(); // flip failed items back to pending + SESSION.setRunning(true); + startForeground(NOTIFICATION_ID, buildNotification(null)); + worker.execute(this::drain); + return START_NOT_STICKY; + } + + // START: a fresh run from the intent. + if (intent == null) { + stopSelf(); + return START_NOT_STICKY; + } + final ItemRef[] refs = readRefs(intent); + if (refs.length == 0) { + stopSelf(); + return START_NOT_STICKY; + } + SESSION.begin(refs, intent.getStringArrayExtra(EXTRA_LABELS)); + startForeground(NOTIFICATION_ID, buildNotification(null)); + worker.execute(this::drain); + return START_NOT_STICKY; + } + + // ---- the run ------------------------------------------------------------------------------- + + /** + * Drain the pending items: delete each on the box and accumulate the reclaimed bytes. + * + *

v1 limitation (accepted): the run state is in-memory, so a process death mid-run loses it + * (no cross-process-death resume). v1 does within-run per-item retry only. A delete call cannot + * be interrupted mid-flight (the box runs the app's own delete), so cancel lands after the item + * in flight finishes. + */ + private void drain() { + ContentDeleteSource source = new CxCoreDeleteSource(new CxCoreDataSource()); + DeleteJob job = SESSION.job(); + + for (int i = job.firstPending(); i >= 0; i = job.firstPending()) { + if (SESSION.isCancelled()) { + break; + } + ItemRef ref = SESSION.refAt(i); + job.setActive(i); + SESSION.publish(); + notifyNow(); + + if (ref == null || isBlank(ref.app()) || isBlank(ref.localRef())) { + job.setFailed(i); // defensive: an unaddressable item never reaches the box + SESSION.publish(); + continue; + } + try { + DeleteResult result = source.delete(ref); + if (result.ok()) { + job.setDone(i, result.freedBytes()); + } else { + job.setFailed(i); + } + } catch (Exception e) { + job.setFailed(i); // box unreachable or a non-2xx: skip it, keep going + } + SESSION.publish(); + } + + if (SESSION.isCancelled()) { + SESSION.clear(); + stopForeground(true); + stopSelf(); + return; + } + + SESSION.setRunning(false); + SESSION.publish(); + stopForeground(true); + stopSelf(); + } + + // ---- helpers ------------------------------------------------------------------------------- + + private static ItemRef[] readRefs(Intent intent) { + String[] apps = intent.getStringArrayExtra(EXTRA_APPS); + String[] locals = intent.getStringArrayExtra(EXTRA_LOCAL_REFS); + if (apps == null || locals == null || apps.length != locals.length) { + return new ItemRef[0]; + } + ItemRef[] refs = new ItemRef[apps.length]; + for (int i = 0; i < apps.length; i++) { + refs[i] = new ItemRef(apps[i], locals[i]); + } + return refs; + } + + private static boolean isBlank(String s) { + return s == null || s.isEmpty(); + } + + // ---- notification -------------------------------------------------------------------------- + + private void notifyNow() { + NotificationManager m = getSystemService(NotificationManager.class); + if (m != null) { + m.notify(NOTIFICATION_ID, buildNotification(currentLabel())); + } + } + + @Nullable + private String currentLabel() { + int i = SESSION.index(); + return i >= 0 ? SESSION.label(i) : null; + } + + private Notification buildNotification(@Nullable String contentText) { + Intent cancel = new Intent(this, ContentDeleteService.class).setAction(ACTION_CANCEL); + PendingIntent cancelIntent = PendingIntent.getService(this, 1, cancel, + PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); + String text = contentText != null && !contentText.isEmpty() + ? contentText : getString(R.string.k2go_cx_delete_notif_text); + return new NotificationCompat.Builder(this, CHANNEL_ID) + .setContentTitle(getString(R.string.k2go_cx_delete_notif_title)) + .setContentText(text) + .setSmallIcon(android.R.drawable.ic_menu_delete) + .setOngoing(true) + .setPriority(NotificationCompat.PRIORITY_LOW) + .setOnlyAlertOnce(true) + .addAction(0, getString(R.string.k2go_dash_cancel), cancelIntent) + .build(); + } + + private void createChannel() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + NotificationChannel channel = new NotificationChannel( + CHANNEL_ID, getString(R.string.k2go_cx_delete_channel_name), + NotificationManager.IMPORTANCE_LOW); + NotificationManager manager = getSystemService(NotificationManager.class); + if (manager != null) { + manager.createNotificationChannel(channel); + } + } + } + + @Override + public void onDestroy() { + worker.shutdownNow(); + super.onDestroy(); + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerFragment.java index e704cacd7..e577d074b 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerFragment.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerFragment.java @@ -7,7 +7,9 @@ * grouped by app, each item with its size, plus total used and the * free disk, with per-item multi-select. The EXPORT action is wired * (pick a drive via SAF, then write the open-format bundle through the - * foreground service); Share / Delete are later slices and stay disabled. + * foreground service) and the DELETE action is wired (confirm, then remove each + * selected item on the box through the foreground service, refreshing the list and + * reclaimed space on settle); Share is a later slice and stays disabled. * ============================================================================ */ package org.appdevforall.k2go.contentexchange.presentation; @@ -60,6 +62,11 @@ public class ContentManagerFragment extends Fragment { private View actionBar; private TextView selectionLabel; private Button exportButton; + private Button deleteButton; + + /** Set when a delete run is launched, so the manager reloads the list (and reclaimed space) when + * it next resumes. Cleared once the reload runs and the run has settled. */ + private boolean deleteLaunched; /** The folder picker; its result carries the drive/folder the user chose for the export. */ private ActivityResultLauncher openTree; @@ -73,10 +80,13 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c actionBar = root.findViewById(R.id.k2go_cx_actionbar); selectionLabel = root.findViewById(R.id.k2go_cx_selection_label); exportButton = root.findViewById(R.id.k2go_cx_export); + deleteButton = root.findViewById(R.id.k2go_cx_delete); openTree = registerForActivityResult(new ActivityResultContracts.OpenDocumentTree(), this::onTreePicked); exportButton.setEnabled(true); exportButton.setOnClickListener(v -> onExportClicked()); + deleteButton.setEnabled(true); + deleteButton.setOnClickListener(v -> onDeleteClicked()); TextView back = root.findViewById(R.id.k2go_cx_back); back.setText(getString(R.string.k2go_back_link)); @@ -108,6 +118,20 @@ public void toggle(String selectionId) { return root; } + @Override + public void onResume() { + super.onResume(); + // After a delete run, the box content changed: reload so deleted items disappear and the + // used/free figures update. Keep the flag while the run is still draining, so returning + // again reloads the now-further-along state. + if (deleteLaunched) { + viewModel.load(); + if (!ContentDeleteService.session().isRunning()) { + deleteLaunched = false; + } + } + } + private void render(ContentManagerUiState st) { if (st == null) { return; @@ -183,7 +207,7 @@ private String freeLine() { : getString(R.string.k2go_cx_free_unavailable); } - /** Updates the bottom action bar from the selection. Buttons stay disabled (slice 1). */ + /** Updates the bottom action bar from the selection. Export and Delete act; Share is pending. */ private void renderSelection(SelectionSummary sel) { if (sel == null || sel.isEmpty()) { actionBar.setVisibility(View.GONE); @@ -272,6 +296,58 @@ private void showProgress() { .commit(); } + // ---- delete -------------------------------------------------------------------------------- + + /** Delete: if a run is already active, just show it; otherwise confirm and start. */ + private void onDeleteClicked() { + if (ContentDeleteService.session().hasSession()) { + showDeleteProgress(); + return; + } + List selected = viewModel.selectedItems(); + if (selected.isEmpty()) { + return; + } + confirmAndDelete(selected); + } + + /** Destructive confirm: name the count and the space reclaimed, and make the removal unambiguous. */ + private void confirmAndDelete(List selected) { + long total = 0L; + for (ContentItem item : selected) { + total += Math.max(0L, item.bytes()); + } + String message = getString(R.string.k2go_cx_delete_confirm_fmt, + selected.size(), ByteFormatter.humanBytes(total)); + new MaterialAlertDialogBuilder(requireContext()) + .setTitle(R.string.k2go_cx_delete_confirm_title) + .setMessage(message) + .setNegativeButton(R.string.k2go_dash_cancel, null) + .setPositiveButton(R.string.k2go_cx_action_delete, (d, w) -> startDelete(selected)) + .show(); + } + + private void startDelete(List selected) { + ItemRef[] refs = new ItemRef[selected.size()]; + String[] labels = new String[selected.size()]; + for (int i = 0; i < selected.size(); i++) { + refs[i] = new ItemRef(selected.get(i).app(), selected.get(i).localRef()); + String title = selected.get(i).title(); + labels[i] = title != null && !title.isEmpty() ? title : selected.get(i).localRef(); + } + ContentDeleteService.start(requireContext(), refs, labels); + viewModel.clearSelection(); + deleteLaunched = true; + showDeleteProgress(); + } + + private void showDeleteProgress() { + requireActivity().getSupportFragmentManager().beginTransaction() + .replace(R.id.k2go_setup_host, new ContentDeleteProgressFragment()) + .addToBackStack(null) + .commit(); + } + /** Friendly app label; falls back to the raw adapter key for an unknown app. */ private String appDisplayName(String app) { if (app == null) { diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/DeleteSession.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/DeleteSession.java new file mode 100644 index 000000000..9b5e4cb73 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/DeleteSession.java @@ -0,0 +1,172 @@ +/* + * ============================================================================ + * Name : DeleteSession.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-427. The one delete-run state the progress UI observes and the foreground + * service mutates. Encapsulated (no public mutable fields, not a static grab-bag): + * the service owns the single instance and the fragment reads it through getters, + * mirroring the export / download session pattern. Holds the pure DeleteJob plus the + * request and labels. Simpler than the export session: no plan phase, no destination, + * no SAF grant, no speed/ETA (delete is atomic per item, not a byte copy). + * ============================================================================ + */ +package org.appdevforall.k2go.contentexchange.presentation; + +import android.os.Handler; +import android.os.Looper; + +import org.appdevforall.k2go.contentexchange.domain.DeleteJob; +import org.appdevforall.k2go.contentexchange.domain.ItemRef; + +final class DeleteSession { + + /** Pinged on the main thread whenever the run state changes. */ + interface Listener { + void onUpdate(); + } + + private final Handler main = new Handler(Looper.getMainLooper()); + private final DeleteJob job = new DeleteJob(); + + private Listener listener; + + private volatile boolean running = false; + private volatile boolean cancelled = false; + private String errorMessage; + + private ItemRef[] refs = new ItemRef[0]; + private String[] labels = new String[0]; + + void setListener(Listener l) { + this.listener = l; + } + + // ---- service-side mutation ----------------------------------------------------------------- + + /** Start a run over the requested items: delete begins immediately (no plan phase). */ + void begin(ItemRef[] request, String[] itemLabels) { + this.refs = request != null ? request : new ItemRef[0]; + this.labels = itemLabels != null && itemLabels.length == this.refs.length + ? itemLabels : new String[this.refs.length]; + this.errorMessage = null; + this.cancelled = false; + this.running = true; + job.begin(this.refs.length); + publish(); + } + + void fail(String message) { + this.errorMessage = message; + this.running = false; + publish(); + } + + void setRunning(boolean value) { + this.running = value; + } + + /** Request cancellation: flip the flag only. The worker owns teardown (clear + stop) once it + * sees the flag, so the job is mutated from one thread. Delete of a single item cannot be + * interrupted mid-call, so cancel takes effect after the item in flight finishes. */ + void markCancelled() { + this.cancelled = true; + } + + int requeueFailed() { + return job.requeueFailed(); + } + + void clear() { + running = false; + cancelled = false; + errorMessage = null; + refs = new ItemRef[0]; + labels = new String[0]; + job.begin(0); + publish(); + } + + DeleteJob job() { + return job; + } + + ItemRef refAt(int i) { + return i >= 0 && i < refs.length ? refs[i] : null; + } + + ItemRef[] refs() { + return refs; + } + + boolean isCancelled() { + return cancelled; + } + + void publish() { + main.post(() -> { + if (listener != null) { + listener.onUpdate(); + } + }); + } + + // ---- UI-side reads ------------------------------------------------------------------------- + + boolean isRunning() { + return running; + } + + boolean hasSession() { + return refs.length > 0; + } + + boolean isSettled() { + return !running && job.isSettled(); + } + + boolean allDone() { + return job.allDone(); + } + + boolean hasFailed() { + return job.hasFailed(); + } + + /** A settled run with work still left (failed items to re-try). */ + boolean canRetry() { + return !running && itemCount() > 0 && !job.allDone(); + } + + String errorMessage() { + return errorMessage; + } + + int itemCount() { + return job.size(); + } + + int index() { + return job.index(); + } + + String label(int i) { + return i >= 0 && i < labels.length ? labels[i] : ""; + } + + int status(int i) { + return job.status(i); + } + + int doneCount() { + return job.doneCount(); + } + + int overallPercent() { + return job.overallPercent(); + } + + long freedTotal() { + return job.freedTotal(); + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/notifications/NotificationIds.java b/controller/app/src/main/java/org/appdevforall/k2go/notifications/NotificationIds.java index 7d5de95e0..ef9199e13 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/notifications/NotificationIds.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/notifications/NotificationIds.java @@ -38,6 +38,7 @@ private NotificationIds() {} public static final int INSTALL_MODULE_FAILURE = 13; // InstallNotifications (dismissible "install failed") public static final int FORGEJO_SEED = 14; // ForgejoSeedService public static final int CONTENT_EXPORT = 15; // ContentExportService (K2GO-427) + public static final int CONTENT_DELETE = 16; // ContentDeleteService (K2GO-427) // High range: single-purpose notifications that re-alert in place (they replace, never stack), // kept well away from the low range. Listed here too so the one source stays complete. diff --git a/controller/app/src/main/res/layout/fragment_k2go_content_delete.xml b/controller/app/src/main/res/layout/fragment_k2go_content_delete.xml new file mode 100644 index 000000000..e0bf3c879 --- /dev/null +++ b/controller/app/src/main/res/layout/fragment_k2go_content_delete.xml @@ -0,0 +1,118 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + +