|
1 | 1 | package dev.opencode.mobile.data.remote |
2 | 2 |
|
3 | 3 | import dev.opencode.mobile.data.remote.dto.ApiLocatedEnvelope |
| 4 | +import dev.opencode.mobile.data.remote.dto.FileContentDto |
4 | 5 | import dev.opencode.mobile.data.remote.dto.FileNodeDto |
5 | 6 | import dev.opencode.mobile.data.remote.dto.PathDto |
6 | 7 | import dev.opencode.mobile.data.remote.dto.V2FsEntryDto |
@@ -11,7 +12,20 @@ import dev.opencode.mobile.network.applyLocationDirectory |
11 | 12 | import io.ktor.client.HttpClient |
12 | 13 | import io.ktor.client.call.body |
13 | 14 | import io.ktor.client.request.get |
| 15 | +import io.ktor.client.request.header |
14 | 16 | import io.ktor.client.request.parameter |
| 17 | +import io.ktor.client.request.prepareGet |
| 18 | +import io.ktor.client.statement.HttpResponse |
| 19 | +import io.ktor.client.statement.bodyAsChannel |
| 20 | +import io.ktor.client.statement.bodyAsText |
| 21 | +import io.ktor.http.HttpHeaders |
| 22 | +import io.ktor.http.HttpStatusCode |
| 23 | +import io.ktor.http.appendEncodedPathSegments |
| 24 | +import io.ktor.http.isSuccess |
| 25 | +import io.ktor.utils.io.ByteReadChannel |
| 26 | +import io.ktor.utils.io.readAvailable |
| 27 | +import kotlinx.serialization.json.Json |
| 28 | +import java.io.ByteArrayOutputStream |
15 | 29 |
|
16 | 30 | class FilesystemApi private constructor( |
17 | 31 | private val httpClient: ClientProvider, |
@@ -42,7 +56,204 @@ class FilesystemApi private constructor( |
42 | 56 | }.body<ApiLocatedEnvelope<List<V2FsEntryDto>>>() |
43 | 57 | .data |
44 | 58 |
|
| 59 | + // File Browser: `directory`/location stays the worktree so the server keeps one instance; |
| 60 | + // only `path` varies. |
| 61 | + |
| 62 | + /** v1 `GET /file`; [relativeDirectory] `"."` lists the worktree root. */ |
| 63 | + suspend fun listProjectEntries( |
| 64 | + worktree: String, |
| 65 | + relativeDirectory: String, |
| 66 | + ): List<FileNodeDto> = |
| 67 | + httpClient |
| 68 | + .get() |
| 69 | + .get("file") { |
| 70 | + parameter("path", relativeDirectory.ifEmpty { "." }) |
| 71 | + applyDirectory(worktree) |
| 72 | + }.successBody() |
| 73 | + |
| 74 | + /** v1 `GET /find/file`: fuzzy file paths relative to [worktree]. */ |
| 75 | + suspend fun findProjectFiles( |
| 76 | + worktree: String, |
| 77 | + query: String, |
| 78 | + limit: Int, |
| 79 | + ): List<String> = |
| 80 | + httpClient |
| 81 | + .get() |
| 82 | + .get("find/file") { |
| 83 | + parameter("query", query) |
| 84 | + parameter("dirs", "false") |
| 85 | + parameter("limit", limit) |
| 86 | + applyDirectory(worktree) |
| 87 | + }.successBody() |
| 88 | + |
| 89 | + /** |
| 90 | + * v1 `GET /file/content`. The server has no size cap, so reading stops past [maxBodyBytes] |
| 91 | + * and reports [V1FileContentResponse.TooLarge]. |
| 92 | + */ |
| 93 | + suspend fun readProjectFile( |
| 94 | + worktree: String, |
| 95 | + relativePath: String, |
| 96 | + maxBodyBytes: Int, |
| 97 | + ): V1FileContentResponse = |
| 98 | + httpClient |
| 99 | + .get() |
| 100 | + .prepareGet("file/content") { |
| 101 | + parameter("path", relativePath) |
| 102 | + applyDirectory(worktree) |
| 103 | + }.execute { response -> |
| 104 | + response.requireSuccess() |
| 105 | + val read = response.bodyAsChannel().readCapped(maxBodyBytes) |
| 106 | + if (read.exceeded) { |
| 107 | + V1FileContentResponse.TooLarge |
| 108 | + } else { |
| 109 | + V1FileContentResponse.Content(json.decodeFromString(read.bytes.decodeToString())) |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + /** v2 `GET /api/fs/list`; a blank [relativeDirectory] lists the location root. */ |
| 114 | + suspend fun listProjectEntriesV2( |
| 115 | + worktree: String, |
| 116 | + relativeDirectory: String, |
| 117 | + ): List<V2FsEntryDto> = |
| 118 | + httpClient |
| 119 | + .get() |
| 120 | + .get("api/fs/list") { |
| 121 | + relativeDirectory.takeIf { it.isNotEmpty() && it != "." }?.let { parameter("path", it) } |
| 122 | + applyLocationDirectory(worktree) |
| 123 | + }.successBody<ApiLocatedEnvelope<List<V2FsEntryDto>>>() |
| 124 | + .data |
| 125 | + |
| 126 | + /** v2 `GET /api/fs/find` for files only. */ |
| 127 | + suspend fun findProjectFilesV2( |
| 128 | + worktree: String, |
| 129 | + query: String, |
| 130 | + limit: Int, |
| 131 | + ): List<V2FsEntryDto> = |
| 132 | + httpClient |
| 133 | + .get() |
| 134 | + .get("api/fs/find") { |
| 135 | + parameter("query", query) |
| 136 | + parameter("type", "file") |
| 137 | + parameter("limit", limit) |
| 138 | + applyLocationDirectory(worktree) |
| 139 | + }.successBody<ApiLocatedEnvelope<List<V2FsEntryDto>>>() |
| 140 | + .data |
| 141 | + |
| 142 | + /** |
| 143 | + * v2 `GET /api/fs/read/<path>`: raw bytes, no envelope. Reads at most [byteLimit] + 1 bytes; |
| 144 | + * the extra byte tells the caller the file is larger. [rangeBytes] sends `Range: bytes=0-(n-1)`, |
| 145 | + * which newer servers answer with 206 and older ones ignore (200, full body). |
| 146 | + */ |
| 147 | + suspend fun readProjectFileV2( |
| 148 | + worktree: String, |
| 149 | + relativePath: String, |
| 150 | + byteLimit: Int, |
| 151 | + rangeBytes: Int?, |
| 152 | + ): V2RawFileRead = |
| 153 | + httpClient |
| 154 | + .get() |
| 155 | + .prepareGet { |
| 156 | + url { appendEncodedPathSegments(v2ReadPathSegments(relativePath)) } |
| 157 | + applyLocationDirectory(worktree) |
| 158 | + rangeBytes?.let { header(HttpHeaders.Range, "bytes=0-${it - 1}") } |
| 159 | + }.execute { response -> |
| 160 | + response.requireSuccess() |
| 161 | + val read = response.bodyAsChannel().readCapped(byteLimit) |
| 162 | + V2RawFileRead( |
| 163 | + bytes = read.bytes, |
| 164 | + exceededLimit = read.exceeded, |
| 165 | + isPartial = response.status == HttpStatusCode.PartialContent, |
| 166 | + totalBytes = |
| 167 | + response.headers[HttpHeaders.ContentRange]?.let(::contentRangeTotal) |
| 168 | + ?: response.headers[HttpHeaders.ContentLength] |
| 169 | + ?.toLongOrNull() |
| 170 | + ?.takeIf { response.status == HttpStatusCode.OK }, |
| 171 | + contentType = response.headers[HttpHeaders.ContentType]?.substringBefore(';')?.trim(), |
| 172 | + ) |
| 173 | + } |
| 174 | + |
| 175 | + private fun v2ReadPathSegments(relativePath: String): List<String> = |
| 176 | + listOf("api", "fs", "read") + encodeRelativePathSegments(relativePath) |
| 177 | + |
45 | 178 | private fun interface ClientProvider { |
46 | 179 | fun get(): HttpClient |
47 | 180 | } |
| 181 | + |
| 182 | + companion object { |
| 183 | + private val json = Json { ignoreUnknownKeys = true } |
| 184 | + |
| 185 | + /** Percent-encodes every byte outside RFC 3986 unreserved characters, per segment. */ |
| 186 | + fun encodeRelativePathSegments(relativePath: String): List<String> = |
| 187 | + relativePath |
| 188 | + .split('/') |
| 189 | + .filter { it.isNotEmpty() && it != "." } |
| 190 | + .map(::percentEncodeSegment) |
| 191 | + |
| 192 | + private fun percentEncodeSegment(segment: String): String = |
| 193 | + buildString { |
| 194 | + segment.encodeToByteArray().forEach { byte -> |
| 195 | + val char = (byte.toInt() and 0xFF).toChar() |
| 196 | + if (char.isLetterOrDigit() && char.code < 0x80 || char in "-._~") { |
| 197 | + append(char) |
| 198 | + } else { |
| 199 | + append('%') |
| 200 | + append(HEX[(byte.toInt() shr 4) and 0x0F]) |
| 201 | + append(HEX[byte.toInt() and 0x0F]) |
| 202 | + } |
| 203 | + } |
| 204 | + } |
| 205 | + |
| 206 | + /** `bytes 0-1048575/4000000` → 4000000; `*` or malformed → null. */ |
| 207 | + internal fun contentRangeTotal(header: String): Long? = header.substringAfterLast('/', "").trim().toLongOrNull() |
| 208 | + |
| 209 | + private const val HEX = "0123456789ABCDEF" |
| 210 | + } |
| 211 | +} |
| 212 | + |
| 213 | +sealed interface V1FileContentResponse { |
| 214 | + data class Content( |
| 215 | + val dto: FileContentDto, |
| 216 | + ) : V1FileContentResponse |
| 217 | + |
| 218 | + data object TooLarge : V1FileContentResponse |
| 219 | +} |
| 220 | + |
| 221 | +class V2RawFileRead( |
| 222 | + val bytes: ByteArray, |
| 223 | + val exceededLimit: Boolean, |
| 224 | + val isPartial: Boolean, |
| 225 | + val totalBytes: Long?, |
| 226 | + val contentType: String?, |
| 227 | +) |
| 228 | + |
| 229 | +private class CappedRead( |
| 230 | + val bytes: ByteArray, |
| 231 | + val exceeded: Boolean, |
| 232 | +) |
| 233 | + |
| 234 | +/** Reads up to [limit] + 1 bytes; stops early so a large body is never fully buffered. */ |
| 235 | +private suspend fun ByteReadChannel.readCapped(limit: Int): CappedRead { |
| 236 | + val output = ByteArrayOutputStream() |
| 237 | + val chunk = ByteArray(16 * 1024) |
| 238 | + var total = 0L |
| 239 | + while (total <= limit) { |
| 240 | + val wanted = minOf(chunk.size.toLong(), limit + 1L - total).toInt() |
| 241 | + val read = readAvailable(chunk, 0, wanted) |
| 242 | + if (read == -1) break |
| 243 | + if (read == 0) continue |
| 244 | + output.write(chunk, 0, read) |
| 245 | + total += read |
| 246 | + } |
| 247 | + return CappedRead(bytes = output.toByteArray(), exceeded = total > limit) |
| 248 | +} |
| 249 | + |
| 250 | +private suspend fun HttpResponse.requireSuccess() { |
| 251 | + if (!status.isSuccess()) { |
| 252 | + throw HttpBodyResponseException(this, runCatching { bodyAsText() }.getOrDefault("")) |
| 253 | + } |
| 254 | +} |
| 255 | + |
| 256 | +private suspend inline fun <reified T> HttpResponse.successBody(): T { |
| 257 | + requireSuccess() |
| 258 | + return body() |
48 | 259 | } |