Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -70,42 +70,55 @@ public static List<ImportEntry> parse(byte[] manifestBytes) throws Exception {
return out;
}

/** Scan a manifest-less folder: recognize what each file belongs to by its name alone. */
/** Scan a manifest-less folder: recognize what each file belongs to by its name alone. A v2 bundle
* file arrives as a relative path ("kiwix/foo.zim"): recognize and key on its basename, but keep
* the full relative path as the payload so the carrier can open it. */
public static ImportManifest scan(List<ImportCarrier.DriveFile> files) throws Exception {
List<ImportEntry> entries = new ArrayList<>();
List<String> unrecognized = new ArrayList<>();
if (files != null) {
for (ImportCarrier.DriveFile file : files) {
String name = file.name();
if (name == null || MANIFEST_NAME.equalsIgnoreCase(name)) {
String payload = file.name();
if (payload == null) {
continue;
}
String app = ImportScan.recognizeApp(name);
String base = basename(payload);
if (MANIFEST_NAME.equalsIgnoreCase(base)) {
continue;
}
String app = ImportScan.recognizeApp(base);
if (ImportScan.APP_KIWIX.equals(app)) {
entries.add(kiwixEntry(name, file.size()));
entries.add(kiwixEntry(payload, base, file.size()));
} else {
unrecognized.add(name);
unrecognized.add(payload);
}
}
}
return new ImportManifest(entries, false, unrecognized);
}

/** Synthesize a Kiwix entry from a .zim filename: dedup keys from the name, no UUID (soft). */
private static ImportEntry kiwixEntry(String name, long size) throws Exception {
String[] p = ImportScan.parseZimFilename(name);
String stem = name.toLowerCase(java.util.Locale.US).endsWith(".zim")
? name.substring(0, name.length() - 4) : name;
/** The file name after the last path separator (the item's own handle), for a flat or nested name. */
private static String basename(String path) {
int slash = path.lastIndexOf('/');
return slash >= 0 ? path.substring(slash + 1) : path;
}

/** Synthesize a Kiwix entry from a .zim basename: dedup keys from the name, no UUID (soft). The
* payload is the drive-relative path, the identity localRef is the basename. */
private static ImportEntry kiwixEntry(String payload, String base, long size) throws Exception {
String[] p = ImportScan.parseZimFilename(base);
String stem = base.toLowerCase(java.util.Locale.US).endsWith(".zim")
? base.substring(0, base.length() - 4) : base;
JSONObject line = new JSONObject()
.put("creator", p[0]).put("lang", p[1]).put("flavour", p[2]);
JSONObject dedup = new JSONObject()
.put("line", line).put("build", JSONObject.NULL)
.put("version", p[3]).put("idKind", "SOFT");
JSONObject identity = new JSONObject().put("localRef", name).put("dedup", dedup);
JSONObject identity = new JSONObject().put("localRef", base).put("dedup", dedup);
JSONObject entry = new JSONObject()
.put("app", ImportScan.APP_KIWIX).put("kind", "zim")
.put("title", stem).put("bytes", size)
.put("identity", identity).put("payload", name);
return new ImportEntry(ImportScan.APP_KIWIX, name, stem, size, name, entry.toString());
.put("identity", identity).put("payload", payload);
return new ImportEntry(ImportScan.APP_KIWIX, base, stem, size, payload, entry.toString());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,22 +24,35 @@

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
* One SAF document tree as an {@link ExportCarrier}. The tree Uri comes from
* {@code ACTION_OPEN_DOCUMENT_TREE} and must already carry a persisted permission.
*
* <p>The bundle is laid out human-navigable: each item's archive goes in a per-app subfolder
* ({@code kiwix/}, {@code kolibri/}, {@code calibre/}) with {@code manifest.json} at the root. A write
* overwrites any existing file of the same name (manifest or item), so a re-export leaves exactly one
* of each, never a {@code manifest (1).json} / {@code name (1).tar} copy that SAF would make on a clash.
*/
public final class SafExportCarrier implements ExportCarrier {

private static final String MANIFEST_NAME = "manifest.json";
private static final String MIME_JSON = "application/json";
private static final String MIME_BINARY = "application/octet-stream";
private static final String MIME_DIR = DocumentsContract.Document.MIME_TYPE_DIR;

private final ContentResolver resolver;
private final Uri treeUri;
private final Uri treeDocUri;

/** app subfolder name -> its document Uri, created/looked-up once per run. */
private final Map<String, Uri> subfolders = new HashMap<>();

public SafExportCarrier(Context context, Uri treeUri) {
this.resolver = context.getContentResolver();
this.treeUri = treeUri;
this.treeDocUri = DocumentsContract.buildDocumentUriUsingTree(
treeUri, DocumentsContract.getTreeDocumentId(treeUri));
}
Expand All @@ -51,26 +64,84 @@ public String destinationLabel() {
}

@Override
public PayloadSink openPayload(String desiredName) throws IOException {
Uri file = createDocument(MIME_BINARY, desiredName);
public PayloadSink openPayload(String subfolder, String desiredName) throws IOException {
boolean nested = subfolder != null && !subfolder.isEmpty();
Uri parent = nested ? ensureSubfolder(subfolder) : treeDocUri;
deleteExisting(parent, desiredName); // overwrite, so a retry leaves no "name (1)" copy
Uri file = createDocument(parent, MIME_BINARY, desiredName);
OutputStream out = openOutput(file);
// SAF may rename on a collision; record the name actually stored so the manifest matches.
// SAF may still adjust the name; record the stored name (relative to the bundle root) so the
// manifest payload points at the real file.
String actual = queryDisplayName(file);
return new PayloadSink(out, actual != null ? actual : desiredName);
String stored = actual != null ? actual : desiredName;
return new PayloadSink(out, nested ? subfolder + "/" + stored : stored);
}

@Override
public OutputStream openManifest() throws IOException {
return openOutput(createDocument(MIME_JSON, MANIFEST_NAME));
deleteExisting(treeDocUri, MANIFEST_NAME); // one authoritative manifest, never "manifest (1)"
return openOutput(createDocument(treeDocUri, MIME_JSON, MANIFEST_NAME));
}

/** Create the per-app subfolder once (reuse it if it is already on the drive). */
private Uri ensureSubfolder(String name) throws IOException {
Uri cached = subfolders.get(name);
if (cached != null) {
return cached;
}
Uri existing = findChild(treeDocUri, name, true);
Uri dir = existing != null ? existing : createDocument(treeDocUri, MIME_DIR, name);
subfolders.put(name, dir);
return dir;
}

/** Delete a child of {@code parent} whose display name matches, so the next create does not clash. */
private void deleteExisting(Uri parent, String name) {
Uri child = findChild(parent, name, false);
if (child != null) {
try {
DocumentsContract.deleteDocument(resolver, child);
} catch (Exception ignored) {
// best-effort: if the delete fails, createDocument may fall back to a renamed copy
}
}
}

/** The document Uri of a child of {@code parent} with the given display name, or null. */
private Uri findChild(Uri parent, String name, boolean wantDir) {
String parentId = DocumentsContract.getDocumentId(parent);
Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, parentId);
String[] columns = {
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
DocumentsContract.Document.COLUMN_MIME_TYPE,
};
try (Cursor c = resolver.query(childrenUri, columns, null, null, null)) {
while (c != null && c.moveToNext()) {
String childName = c.getString(1);
if (!name.equals(childName)) {
continue;
}
boolean isDir = MIME_DIR.equals(c.getString(2));
if (wantDir == isDir) {
return DocumentsContract.buildDocumentUriUsingTree(treeUri, c.getString(0));
}
}
} catch (Exception ignored) {
// fall through to null
}
return null;
}

private Uri createDocument(String mime, String name) throws IOException {
private Uri createDocument(Uri parent, String mime, String name) throws IOException {
try {
Uri uri = DocumentsContract.createDocument(resolver, treeDocUri, mime, name);
Uri uri = DocumentsContract.createDocument(resolver, parent, mime, name);
if (uri == null) {
throw new IOException("Could not create " + name + " on the destination");
}
return uri;
} catch (IOException e) {
throw e;
} catch (Exception e) {
// Includes a SecurityException if the grant was revoked, or a provider failure.
throw new IOException("Could not create " + name + ": " + e.getMessage(), e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,13 @@
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

/**
* One SAF document tree as an {@link ImportCarrier}. The tree Uri comes from
Expand All @@ -40,6 +44,10 @@ public final class SafImportCarrier implements ImportCarrier {
private static final String MANIFEST_NAME = "manifest.json";
/** A manifest larger than this is treated as absent: the real index is a few KB. */
private static final long MANIFEST_MAX_BYTES = 8L * 1024 * 1024;
private static final String MIME_DIR = DocumentsContract.Document.MIME_TYPE_DIR;
/** The per-app subfolders a v2 bundle lays items in; walked one level for the no-manifest scan. */
private static final Set<String> APP_SUBFOLDERS = new HashSet<>(
Arrays.asList("kiwix", "kolibri", "calibre"));

private final ContentResolver resolver;
private final Uri treeUri;
Expand Down Expand Up @@ -105,21 +113,84 @@ public List<DriveFile> listFiles() throws IOException {
public InputStream openPayload(String name) throws IOException {
index();
String id = docIds.get(name);
if (id == null) {
// A v2 payload path ("app/file") whose folder the index did not pre-walk: walk it directly.
int slash = name.indexOf('/');
if (slash > 0) {
id = resolveNestedId(name.substring(0, slash), name.substring(slash + 1));
}
}
if (id == null) {
throw new IOException("File not found on the drive: " + name);
}
return openStream(DocumentsContract.buildDocumentUriUsingTree(treeUri, id));
}

/** List the folder's direct children once (name + size + document id). */
/**
* Index the bundle once: files directly in the chosen folder by bare name (a flat pre-v2 bundle),
* plus files one level down in each per-app subfolder by relative path ("app/file", a v2 bundle).
* Both forms land in the same map, so {@code openPayload} and the no-manifest scan resolve either.
*/
private void index() throws IOException {
if (docIds != null) {
return;
}
Map<String, String> ids = new LinkedHashMap<>();
List<DriveFile> found = new ArrayList<>();
Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(
treeUri, DocumentsContract.getTreeDocumentId(treeUri));
String rootId = DocumentsContract.getTreeDocumentId(treeUri);
for (String[] row : listChildren(rootId)) {
String id = row[0];
String name = row[1];
if (name == null) {
continue;
}
if (MIME_DIR.equals(row[3])) {
// Walk one level into a known app subfolder; index its files by "app/file".
if (APP_SUBFOLDERS.contains(name.toLowerCase(Locale.US))) {
for (String[] sub : listChildren(id)) {
String subName = sub[1];
if (subName == null || MIME_DIR.equals(sub[3])) {
continue;
}
String rel = name + "/" + subName;
ids.put(rel, sub[0]);
found.add(new DriveFile(rel, parseSize(sub[2])));
}
}
continue;
}
ids.put(name, id);
found.add(new DriveFile(name, parseSize(row[2])));
}
this.docIds = ids;
this.files = found;
}

/** Resolve "dir/child" by walking into the named subfolder (one level), for a folder the index did
* not pre-walk. Returns the child's document id, or null. */
private String resolveNestedId(String dir, String child) throws IOException {
String dirId = null;
for (String[] row : listChildren(DocumentsContract.getTreeDocumentId(treeUri))) {
if (dir.equals(row[1]) && MIME_DIR.equals(row[3])) {
dirId = row[0];
break;
}
}
if (dirId == null) {
return null;
}
for (String[] row : listChildren(dirId)) {
if (child.equals(row[1]) && !MIME_DIR.equals(row[3])) {
return row[0];
}
}
return null;
}

/** One children query, each row as {docId, displayName, size, mimeType}. */
private List<String[]> listChildren(String parentDocId) throws IOException {
List<String[]> rows = new ArrayList<>();
Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, parentDocId);
String[] columns = {
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
Expand All @@ -131,23 +202,24 @@ private void index() throws IOException {
throw new IOException("Could not read the selected folder");
}
while (c.moveToNext()) {
String id = c.getString(0);
String name = c.getString(1);
long size = c.isNull(2) ? 0L : c.getLong(2);
String mime = c.getString(3);
if (name == null || DocumentsContract.Document.MIME_TYPE_DIR.equals(mime)) {
continue; // files only: sub-folders are not part of a flat bundle
}
ids.put(name, id);
found.add(new DriveFile(name, size));
rows.add(new String[]{
c.getString(0), c.getString(1),
c.isNull(2) ? "0" : Long.toString(c.getLong(2)), c.getString(3)});
}
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException("Could not read the selected folder: " + e.getMessage(), e);
}
this.docIds = ids;
this.files = found;
return rows;
}

private static long parseSize(String s) {
try {
return Long.parseLong(s);
} catch (NumberFormatException e) {
return 0L;
}
}

private InputStream openStream(Uri docUri) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,23 @@
*
* <p>Only {@code java.io} crosses this boundary: no Android, no SAF type. The carrier chooses the
* final name for a payload (a destination may rename on a collision), so {@link #openPayload}
* reports the name actually used, which the manifest then records.
* reports the name actually used (relative to the bundle root), which the manifest then records.
*/
public interface ExportCarrier {

/** A short, human name of the chosen destination (e.g. the folder name), for the UI. */
String destinationLabel();

/** Open a writable stream for one payload file; reports the name the destination stored. */
PayloadSink openPayload(String desiredName) throws IOException;
/**
* Open a writable stream for one payload file inside the bundle, under a per-app {@code subfolder}
* (e.g. {@code kiwix}); a null or empty subfolder writes at the bundle root. An existing file of
* the same name in that folder is overwritten (replaced), never left as a {@code name (1)} copy.
* Reports the stored name relative to the bundle root ({@code subfolder/name}), for the manifest.
*/
PayloadSink openPayload(String subfolder, String desiredName) throws IOException;

/** Open a writable stream for the top-level {@code manifest.json}. */
/** Open a writable stream for the top-level {@code manifest.json}, overwriting any existing one so
* the bundle has exactly one authoritative manifest (never a {@code manifest (1).json} copy). */
OutputStream openManifest() throws IOException;

/** An open payload stream plus the name the destination actually stored it under. */
Expand Down
Loading
Loading