Files is a file manager, and the viewer draws a file by what it is
CI / check (push) Canceled after 0s

Files listed and showed text. It now does what the web's explorer does,
through the server's /api/v2/files routes: upload (the system picker,
several at once, each streamed from where it is with its progress, one
request a file so a 413 for one does not take the others), new folder, new
text file (never over one that is there), rename, move and copy through a
folder picker that is walked rather than typed into, delete to the trash,
a long press to choose and a bar that moves, copies, downloads, shares or
deletes all that is chosen through /files/batch -- which answers path by
path, and what it refused is said in its own sentences. The trash: list,
restore, remove for good, empty. A file's versions: list, restore.

Leaving the instance: a download goes into a document the person chose
(ACTION_CREATE_DOCUMENT), streamed, several things or a folder as the
server's zip. Open with and Share hand another app a copy in the private
cache through the FileProvider the camera already uses (one more
cache-path, read-only, per grant); the copies go when Files is left, when
the app starts and at sign-out. No permission is added.

The viewer goes by file_kind. Text kinds as before, now editable up to the
server's 1 MB: a save says the sha it opened, a 409 shows the server's
sentence with Reload and Save anyway, and leaving with unsaved text asks.
The text being edited lives in a ViewModel: a megabyte does not fit a saved
instance state. A picture is copied to the cache, decoded with its edge and
pixel count capped whatever the file claims, and zooms and pans. A PDF is
drawn page by page by the platform's PdfRenderer from a cache copy. Sound
and video are played by the platform's MediaPlayer through a
MediaDataSource that asks the app's own HTTP client for each piece with a
Range request: the token stays in the Authorization header and the player
is never given an address, so no player library is added. CSV and TSV are a
grid with a row and column cap; a notebook is its cells' text, outputs as
plain text only. Archives, 3D models and binaries are their details with
Download, Open with and Share. An SVG is its source: the app has no WebView
and draws nothing a file could script. Nothing is rendered as HTML.

The share sheet has a third place to send to: Save to Files, into a folder
chosen with the same picker; shared text is kept as a note.

Strings: 61 new keys, 49 worded as the server's explorer words them and
translated from its catalogues at the pinned commit, 12 the app's own in
all eight languages.

An instance without these routes still lists and shows text; what it
cannot do says so.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-18 21:24:39 +00:00
1 parent 6e24f6f370
commit 5d1e36868c
32 files changed
+4618 -138

No files matched your search

@@ -1,6 +1,7 @@
package eu.llembas.android.api
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlinx.serialization.KSerializer
@@ -22,6 +23,7 @@ import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import java.io.IOException
import java.io.OutputStream
import java.util.concurrent.TimeUnit
import kotlin.coroutines.resumeWithException
@@ -600,6 +602,181 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
return call(authed(url.toString()).get().build(), FileContent.serializer())
}
// --- The file manager's writes, the trash, versions and bytes ---------------------------------
// Each write answers the listing of the directory it changed; a refusal is the tree's own
// sentence (400), a path that cannot be read a 404, and both come back as an ApiException.
private fun filesUrl(path: String, vararg query: Pair<String, String?>): String = "$v2/files$path".toHttpUrl().newBuilder()
.apply { query.forEach { (name, value) -> if (value != null) addQueryParameter(name, value) } }
.build()
.toString()
suspend fun makeFolder(dir: String, name: String): FileListing = send(
"POST",
"/files/mkdir",
buildJsonObject {
put("path", dir)
put("name", name)
},
)
suspend fun renameFile(path: String, name: String): FileListing = send(
"POST",
"/files/rename",
buildJsonObject {
put("path", path)
put("name", name)
},
)
/** Copy [path] into the directory [to]; the answer's `copied` says what the copy is called. */
suspend fun copyFile(path: String, to: String, name: String? = null): FileListing = send(
"POST",
"/files/copy",
buildJsonObject {
put("path", path)
put("to", to)
name?.let { put("name", it) }
},
)
/**
* Move or copy [paths] into the directory [to], or delete them (to the trash): `op` is
* `move`, `copy` or `delete`. Each path is done by itself, so the answer is read for what
* failed even though the request succeeded.
*/
suspend fun batchFiles(op: String, paths: List<String>, to: String? = null): BatchAnswer = send(
"POST",
"/files/batch",
buildJsonObject {
put("op", op)
put("paths", JsonArray(paths.map { JsonPrimitive(it) }))
to?.let { put("to", it) }
},
)
/**
* Save a text file. [base] is the `sha` the file had when it was opened: when it holds
* something else by now the server writes nothing and this throws [SaveConflict] with its
* sentence, unless [force]. Without a [base] nothing is compared, and a path with no file
* makes one.
*/
suspend fun saveFile(path: String, text: String, base: String? = null, force: Boolean = false): FileContent = withContext(Dispatchers.IO) {
val body = buildJsonObject {
put("path", path)
put("text", text)
base?.takeIf { it.isNotBlank() }?.let { put("base", it) }
if (force) put("force", true)
}
http.newCall(authed("$v2/files/content").put(body.toString().toRequestBody(JSON)).build()).await().use { response ->
val said = runCatching { response.body?.string().orEmpty() }.getOrDefault("")
if (response.code == 409) {
val conflict = runCatching { LembasJson.parseToJsonElement(said) as? JsonObject }.getOrNull() ?: JsonObject(emptyMap())
if ((conflict["conflict"] as? JsonPrimitive)?.content == "true") {
throw SaveConflict(refusal(said).orEmpty(), (conflict["sha"] as? JsonPrimitive)?.takeUnless { it is JsonNull }?.content.orEmpty())
}
}
if (!response.isSuccessful) throw ApiException(response.code, refusal(said) ?: "The server answered ${response.code}.")
LembasJson.decodeFromString(FileContent.serializer(), said)
}
}
suspend fun trash(): TrashList = get("/files/trash")
suspend fun restoreTrashed(id: String): TrashList = send("POST", "/files/restore", buildJsonObject { put("id", id) })
/** Remove for good: the one thing named, or with no [id] everything in the trash. */
suspend fun removeTrashed(id: String? = null): TrashList = call(authed(filesUrl("/trash", "id" to id)).delete().build(), TrashList.serializer())
suspend fun fileVersions(path: String): FileVersions = call(authed(filesUrl("/versions", "path" to path)).get().build(), FileVersions.serializer())
/** Make an older version the file again, as a new version: nothing is lost. */
suspend fun restoreVersion(path: String, version: String): FileVersions = send(
"POST",
"/files/versions/restore",
buildJsonObject {
put("path", path)
put("version", version)
},
)
/**
* Upload one file into the directory [dir], streamed: [body] writes the file's bytes as they
* are read, so a large file is never held in memory. A file over the instance's limit is a
* 413 whose sentence names it.
*/
suspend fun uploadFile(dir: String, name: String, body: RequestBody): FileListing {
val form = MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("files", name, body).build()
return call(authed(filesUrl("/upload", "path" to dir)).post(form).build(), FileListing.serializer())
}
/**
* The request for a file's bytes (`/files/raw`), or for [range] of them. The token goes in
* the Authorization header, as on every call: the address names the path and nothing else.
*/
fun rawFile(path: String, range: LongRange? = null, inline: Boolean = false): Request = authed(
filesUrl(
"/raw",
"path" to path,
"inline" to if (inline) "1" else null,
),
)
.header("Accept", "*/*")
.apply { range?.let { header("Range", "bytes=${it.first}-${it.last}") } }
.get()
.build()
/** The request for [paths] (files and folders) as one zip. */
fun zipFiles(paths: List<String>): Request = authed("$v2/files/zip")
.header("Accept", "*/*")
.post(buildJsonObject { put("paths", JsonArray(paths.map { JsonPrimitive(it) })) }.toString().toRequestBody(JSON))
.build()
/**
* Run [request] and copy what it answers into [out] as it comes, saying how far it is
* ([progress]: bytes so far, and the total when the server said one, else -1). At most
* [most] bytes are taken: more than that is refused as a 413, with nothing more read.
*/
suspend fun download(request: Request, out: OutputStream, most: Long = Long.MAX_VALUE, progress: (done: Long, total: Long) -> Unit = { _, _ -> }): Long =
withContext(Dispatchers.IO) {
http.newCall(request).await().use { response ->
if (!response.isSuccessful) throw ApiException(response.code, detail(response))
val body = response.body ?: throw ApiException(response.code, "")
val total = body.contentLength()
if (total > most) throw ApiException(413, "")
val buffer = ByteArray(64 * 1024)
var done = 0L
body.byteStream().use { stream ->
while (true) {
ensureActive()
val n = stream.read(buffer)
if (n < 0) break
done += n
if (done > most) throw ApiException(413, "")
out.write(buffer, 0, n)
progress(done, total)
}
}
out.flush()
done
}
}
/**
* The bytes `[from, to]` of a file, for a player or a table's first rows: a `Range` request,
* blocking, on whatever thread asks (never the main one). A server that answers the whole
* file to a range that does not start at 0 is refused rather than read from the wrong place.
*/
fun rawBytes(path: String, from: Long, to: Long): ByteArray = http.newCall(rawFile(path, from..to)).execute().use { response ->
if (!response.isSuccessful) throw ApiException(response.code, detail(response))
if (response.code != 206 && from > 0) throw ApiException(416, "")
val want = to - from + 1
response.body!!.source().use { source ->
source.request(want)
source.buffer.readByteArray(minOf(source.buffer.size, want))
}
}
/** A file of the tree in the web UI's own viewer (`/files/view`), for what the app does not draw. */
fun webFile(path: String): String = "$base/files/view".toHttpUrl().newBuilder().addQueryParameter("path", path).build().toString()
@@ -0,0 +1,284 @@
package eu.llembas.android.api
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import java.io.IOException
// The person's files as a file manager needs them: the shapes of the trash, the versions and a
// batch (`contract/files_*.json`, `file_versions.json`, `file_save_conflict.json`), and what the
// app decides from a file's kind without a phone: which viewer, a table's rows, a notebook's cells.
/** One thing in the trash: restored or removed for good by its [id]. */
@Serializable
data class TrashItem(
val id: String = "",
val name: String = "",
val path: String = "",
val kind: String = "file",
val size: Long = 0,
@SerialName("trashed_at") val trashedAt: String? = null,
)
/** `GET /files/trash`, and what is left after a restore ([restored]: where it went back to) or a removal. */
@Serializable
data class TrashList(val items: List<TrashItem> = emptyList(), val restored: String? = null, val removed: Int = 0)
/** One version of a file, newest first in [FileVersions]; [current] is what the file holds now. */
@Serializable
data class FileVersion(
val id: String = "",
val sha: String = "",
val size: Long = 0,
val at: String? = null,
val by: String? = null,
@SerialName("chat_id") val chatId: String? = null,
val current: Boolean = false,
)
@Serializable
data class FileVersions(val path: String = "", val sha: String = "", val versions: List<FileVersion> = emptyList())
/** One path of a batch: done ([ok], and where it is now) or refused, in the server's sentence. */
@Serializable
data class BatchResult(val path: String = "", val ok: Boolean = false, val to: String? = null, val error: String? = null)
/** `POST /files/batch`: never all-or-nothing, so [failed] is read even from a 200. */
@Serializable
data class BatchAnswer(val op: String = "", val to: String? = null, val results: List<BatchResult> = emptyList(), val done: Int = 0, val failed: Int = 0) {
/** The server's sentences for what was refused, each once, at most [most]. */
fun refusals(most: Int = 3): List<String> = results.filter { !it.ok }.mapNotNull { it.error?.ifBlank { null } }.distinct().take(most)
}
/**
* A save the server refused because the file changed since it was opened (409, `conflict: true`):
* its sentence, and the [sha] the file holds now. Nothing was written.
*/
class SaveConflict(message: String, val sha: String) : IOException(message)
/** The viewer a file gets, by the server's word for what it is. */
enum class FileView {
/** Markdown, code, text, and the source of an HTML page or an SVG: drawn as text, editable. */
Text,
Image,
Pdf,
Audio,
Video,
Table,
Notebook,
/** Nothing to draw here: what the file is, and Download, Open with, Share. */
Details,
}
object FileKinds {
/** The kinds whose text the server hands over and the app may save back. */
val TEXT = setOf("markdown", "code", "text", "html", "svg")
/**
* The viewer for a file of [kind]. A server that does not say the kind (null) is read as
* before: as text, and the content answer says when it is not. An SVG is its source -- the
* app has no WebView and draws nothing a file could script.
*/
fun viewer(kind: String?): FileView = when (kind) {
null, "", in TEXT -> FileView.Text
"image" -> FileView.Image
"pdf" -> FileView.Pdf
"audio" -> FileView.Audio
"video" -> FileView.Video
"table" -> FileView.Table
"notebook" -> FileView.Notebook
else -> FileView.Details
}
/** Whether the app offers to edit it: a text kind (a table too, as its text) the person may change. */
fun editable(kind: String?, writable: Boolean?, withheld: Boolean): Boolean = writable == true && !withheld && (kind in TEXT || kind == "table")
/** Why [name] cannot be a file's or a folder's name, as the server would refuse it; false for a good one. */
fun badName(name: String): Boolean = name.isBlank() || "/" in name || name.trim() in setOf(".", "..")
/** [name] inside the directory [dir]. */
fun child(dir: String, name: String): String = dir.trimEnd('/') + "/" + name.trim()
/** The directory a path is in; `/` for a path at the top. */
fun parent(path: String): String = path.trimEnd('/').substringBeforeLast('/', "").ifEmpty { "/" }
/** The last name of a path. */
fun name(path: String): String = path.trimEnd('/').substringAfterLast('/').ifBlank { path }
/** A name another app may be given: no separators, no control characters, never empty. */
fun safeName(name: String): String {
val kept = name.map { if (it == '/' || it == '\\' || it.isISOControl()) '_' else it }.joinToString("")
return kept.trim().trim('.').ifBlank { "file" }.takeLast(120)
}
}
/** A table's first rows and columns; [cut] when the file has more than is laid out. */
data class Table(val rows: List<List<String>>, val columns: Int, val cut: Boolean)
/**
* A CSV or TSV file as rows of cells: quoted cells, doubled quotes and line breaks inside quotes
* as RFC 4180 has them. At most [maxRows] rows of at most [maxColumns] cells are kept, each cell
* at most [maxCell] characters -- a table is for looking at, the text has all of it. [partial]:
* the text is only the file's beginning, so its last line may be half a row and is left out.
*/
fun parseTable(text: String, delimiter: Char, maxRows: Int = 500, maxColumns: Int = 40, maxCell: Int = 200, partial: Boolean = false): Table {
val rows = mutableListOf<List<String>>()
var row = mutableListOf<String>()
val cell = StringBuilder()
var quoted = false
var cut = partial
var widest = 0
var i = 0
fun endCell() {
if (row.size < maxColumns) row += cell.toString().take(maxCell) else cut = true
cell.setLength(0)
}
fun endRow(): Boolean {
endCell()
if (row.size > 1 || row[0].isNotEmpty()) {
rows += row
widest = maxOf(widest, row.size)
}
row = mutableListOf()
return rows.size < maxRows
}
var open = true
while (i < text.length) {
val c = text[i]
when {
quoted && c == '"' && i + 1 < text.length && text[i + 1] == '"' -> {
cell.append('"')
i++
}
c == '"' && (quoted || cell.isEmpty()) -> quoted = !quoted
!quoted && c == delimiter -> endCell()
!quoted && (c == '\n' || c == '\r') -> {
if (c == '\r' && i + 1 < text.length && text[i + 1] == '\n') i++
if (!endRow()) {
cut = cut || i + 1 < text.length
open = false
break
}
}
else -> if (cell.length <= maxCell) cell.append(c)
}
i++
}
// What is left after the last line break: a whole last row, unless the text was cut short.
if (open && !partial && (cell.isNotEmpty() || row.isNotEmpty())) endRow()
return Table(rows, widest, cut)
}
/** The delimiter a table file is cut by: a tab for `.tsv` (or a first line with tabs and no commas), else a comma. */
fun tableDelimiter(name: String, text: String): Char {
if (name.endsWith(".tsv", ignoreCase = true) || name.endsWith(".tab", ignoreCase = true)) return '\t'
val first = text.lineSequence().firstOrNull().orEmpty()
return if ('\t' in first && ',' !in first) {
'\t'
} else if (';' in first && ',' !in first) {
';'
} else {
','
}
}
/** One cell of a notebook, as text: its [source], and what it printed ([output], plain text only). */
data class NotebookCell(val kind: String, val source: String, val output: String = "", val count: Int? = null, val cut: Boolean = false)
/** A notebook's first cells; [more]: how many are not shown. Null from [parseNotebook]: not a notebook. */
data class Notebook(val cells: List<NotebookCell>, val more: Int = 0, val language: String = "")
/**
* A Jupyter notebook, read-only, as text and nothing else: a cell's source, and of its outputs
* only the plain text (a stream, `text/plain`, an error's name and value). HTML, pictures and
* scripts in an output are not drawn and not kept. Null for a file that is not a notebook.
*/
fun parseNotebook(text: String, maxCells: Int = 200, maxChars: Int = 20_000): Notebook? {
val root = runCatching { LembasJson.parseToJsonElement(text) as? JsonObject }.getOrNull() ?: return null
val cells = root["cells"] as? JsonArray ?: return null
fun words(of: JsonElement?): String = when (of) {
is JsonPrimitive -> if (of.isString) of.content else ""
is JsonArray -> of.joinToString("") { (it as? JsonPrimitive)?.takeIf { p -> p.isString }?.content.orEmpty() }
else -> ""
}
fun printed(cell: JsonObject): String = (cell["outputs"] as? JsonArray).orEmpty().mapNotNull { it as? JsonObject }.joinToString("") { out ->
when ((out["output_type"] as? JsonPrimitive)?.content) {
"stream" -> words(out["text"])
"error" -> listOf(words(out["ename"]), words(out["evalue"])).filter { it.isNotBlank() }.joinToString(": ") + "\n"
else -> words((out["data"] as? JsonObject)?.get("text/plain")).let { if (it.isEmpty() || it.endsWith("\n")) it else it + "\n" }
}
}.trimEnd('\n')
val language = (((root["metadata"] as? JsonObject)?.get("kernelspec") as? JsonObject)?.get("language") as? JsonPrimitive)?.content
?: ((((root["metadata"] as? JsonObject)?.get("language_info") as? JsonObject)?.get("name")) as? JsonPrimitive)?.content
val read = cells.mapNotNull { it as? JsonObject }.take(maxCells).map { cell ->
val source = words(cell["source"])
val output = printed(cell)
NotebookCell(
kind = (cell["cell_type"] as? JsonPrimitive)?.content ?: "code",
source = source.take(maxChars),
output = output.take(maxChars),
count = (cell["execution_count"] as? JsonPrimitive)?.content?.toIntOrNull(),
cut = source.length > maxChars || output.length > maxChars,
)
}
return Notebook(read, more = (cells.size - read.size).coerceAtLeast(0), language = language.orEmpty())
}
/**
* How much smaller a picture of [width] × [height] is decoded (a power of two, `inSampleSize`):
* so its longer edge is at most about [edge] and it holds at most [pixels] pixels, whatever the
* file claims. A picture of 30 000 × 30 000 is then a few megabytes in memory, not gigabytes.
*/
fun sampleFor(width: Int, height: Int, edge: Int = 2560, pixels: Long = 8_000_000): Int {
if (width <= 0 || height <= 0) return 1
var sample = 1
while (maxOf(width, height) / sample > edge || (width.toLong() / sample) * (height.toLong() / sample) > pixels) sample *= 2
return sample
}
/**
* A file read a piece at a time, for a player that seeks: [fetch] gets the bytes `[from, to]`
* (a `Range` request with the token in its header), a few blocks are kept, and a read is
* answered from the block its position is in. [length] is the file's size as the server said it.
*/
class RangeReader(private val length: Long, private val block: Int = BLOCK, private val keep: Int = 6, private val fetch: (from: Long, to: Long) -> ByteArray) {
private val blocks = object : LinkedHashMap<Long, ByteArray>(keep, 0.75f, true) {
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, ByteArray>?): Boolean = size > keep
}
/** Up to [size] bytes from [position] into [buffer] at [offset]; -1 at or past the end. */
@Synchronized
fun read(position: Long, buffer: ByteArray, offset: Int, size: Int): Int {
if (position < 0 || position >= length) return -1
if (size <= 0) return 0
val index = position / block
val start = index * block
val bytes = blocks[index] ?: fetch(start, minOf(start + block, length) - 1).also { blocks[index] = it }
val within = (position - start).toInt()
if (within >= bytes.size) return -1
val n = minOf(size, bytes.size - within)
System.arraycopy(bytes, within, buffer, offset, n)
return n
}
@Synchronized
fun close() = blocks.clear()
companion object {
const val BLOCK = 512 * 1024
}
}
@@ -563,6 +563,12 @@ data class FileEntry(
val name: String = "",
val path: String = "",
val kind: String = "file",
/**
* What the file is, read by the server from its name and its own bytes: `markdown`, `code`,
* `text`, `html`, `image`, `svg`, `pdf`, `audio`, `video`, `table`, `notebook`, `model3d`,
* `archive` or `binary`. Null for a folder, and from a server that does not say it.
*/
@SerialName("file_kind") val fileKind: String? = null,
val size: Long = 0,
val mime: String = "",
@SerialName("updated_at") val updatedAt: String? = null,
@@ -573,7 +579,13 @@ data class FileEntry(
/** A directory, through the person's own access. `parent` is null at `/`. */
@Serializable
data class FileListing(val path: String = "/", val parent: String? = null, val entries: List<FileEntry> = emptyList())
data class FileListing(
val path: String = "/",
val parent: String? = null,
val entries: List<FileEntry> = emptyList(),
/** After a copy: the new entry, under the name the server gave it (a taken name is numbered). */
val copied: FileEntry? = null,
)
/** Why a file's text did not come: `reason` is `not_text` or `too_large`; `message` says it. */
@Serializable
@@ -590,7 +602,12 @@ data class FileContent(
val size: Long = 0,
val mime: String = "",
val kind: String = "text",
/** What the file is ([FileEntry.fileKind]); null from a server that does not say it. */
@SerialName("file_kind") val fileKind: String? = null,
/** Whether the person may change it; null from a server that does not say (then: no editing). */
val writable: Boolean? = null,
val language: String = "",
/** What the file holds now: sent back as a save's `base`, so a save over somebody else's change is refused. */
val sha: String = "",
val text: String = "",
val withheld: Withheld? = null,