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
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,65 @@ private val rePhone = Regex("^(?:(?:\\+\\d{1,3}[ .-]?)?(?:\\(\\d{3}\\)[ .-]?|\\d

fun isPathText(t: String) = !t.startsWith("http") && !t.contains("://") && (rePath.matches(t) || reFile.matches(t) || FileFetch.shareRoute(t) != null)
fun pathLink(p: String) = PATH_SCHEME + p
fun pathOf(url: String): String? = if (url.startsWith(PATH_SCHEME)) url.removePrefix(PATH_SCHEME) else null
fun pathOf(url: String): String? = if (url.startsWith(PATH_SCHEME)) url.removePrefix(PATH_SCHEME) else fileUrlPath(url)

private fun decodePercent(s: String): String {
val out = java.io.ByteArrayOutputStream(s.length)
var i = 0
while (i < s.length) {
val c = s[i]
if (c == '%' && i + 2 < s.length) {
val hi = s[i + 1].digitToIntOrNull(16)
val lo = s[i + 2].digitToIntOrNull(16)
if (hi != null && lo != null) {
out.write((hi shl 4) or lo)
i += 3
continue
}
}
out.write(c.toString().toByteArray(Charsets.UTF_8))
i++
}
return out.toString(Charsets.UTF_8.name())
}

private val reLineFrag = Regex("^L\\d{1,6}(?:-L?\\d{1,6})?$")
private val reWinSlashDrive = Regex("^/[A-Za-z]:/.*")
private val reWinDrive = Regex("^[A-Za-z]:/.*")

/** Decodes a `file://` URL into a hub filesystem path (preserving `#L<line>` anchors, stripping other fragments/queries and `localhost`). */
fun fileUrlPath(s: String): String? {
val t = s.trim()
if (!t.startsWith("file://", ignoreCase = true)) return null
var rest = t.substring(7)
if (rest.startsWith("localhost/")) rest = rest.removePrefix("localhost")
var anchor = ""
val hash = rest.indexOf('#')
if (hash >= 0) {
val frag = rest.substring(hash + 1)
rest = rest.substring(0, hash)
if (reLineFrag.matches(frag)) anchor = "#$frag"
}
val q = rest.indexOf('?')
if (q >= 0) rest = rest.substring(0, q)
var decoded = decodePercent(rest)
if (reWinSlashDrive.matches(decoded)) decoded = decoded.substring(1)
if (decoded.isEmpty() || !(decoded.startsWith("/") || decoded.startsWith("~/") || reWinDrive.matches(decoded))) return null
return decoded + anchor
}

/** Converts a markdown link destination into a link target (`bppath:` for `file://` and hub paths, otherwise the URL). */
fun linkTargetUrl(raw: String): String {
val trimmed = raw.trim()
val url = if (trimmed.startsWith("<") && trimmed.indexOf('>', 1) > 0) {
trimmed.substring(1, trimmed.indexOf('>', 1))
} else {
trimmed.substringBefore(' ').removePrefix("<").removeSuffix(">")
}
fileUrlPath(url)?.let { return pathLink(it) }
if (isPathText(url)) return pathLink(url)
return url
}

private fun boundary(s: String, i: Int) = i == 0 || s[i - 1].isWhitespace() || s[i - 1] in "([{<\"'`,;:"

Expand Down Expand Up @@ -45,13 +103,18 @@ fun autoLink(s: String, i: Int): LinkHit? {
return null
}

/** An http(s):// or backplane:// address that starts at s[i] (trailing marks and an unmatched ) stay out). */
/** An http(s)://, backplane:// or file:// address that starts at s[i] (trailing marks and an unmatched ) stay out). */
fun webLink(s: String, i: Int): LinkHit? {
if (i > 0 && s[i - 1].isLetterOrDigit()) return null
if (!(s.startsWith("http://", i) || s.startsWith("https://", i) || s.startsWith("backplane://", i))) return null
val isFile = s.startsWith("file://", i, ignoreCase = true)
val isWeb = s.startsWith("http://", i, ignoreCase = true) || s.startsWith("https://", i, ignoreCase = true)
val isBp = s.startsWith("backplane://", i)
if (!(isFile || isWeb || isBp)) return null
var e = i; while (e < s.length && !s[e].isWhitespace() && s[e] !in "<>\"'") e++
while (e > i && s[e - 1] in ".,;:!?)]}*_") { if (s[e - 1] == ')' && s.substring(i, e).count { it == '(' } >= s.substring(i, e).count { it == ')' }) break; e-- }
return LinkHit(e, s.substring(i, e))
val raw = s.substring(i, e)
if (isFile) return fileUrlPath(raw)?.let { LinkHit(e, pathLink(it)) }
return LinkHit(e, raw)
}

/** Plain text cut into runs (text, link or null): a message that is not Markdown (a user's, a room post). */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ fun DataClient.openLink(url: String, thread: String) {
"project" -> LinkTarget(LinkTarget.Kind.PROJECT, r.optString("project"))
"room" -> LinkTarget(LinkTarget.Kind.ROOM, r.optString("room"))
"file" -> LinkTarget(LinkTarget.Kind.FILE, r.optString("thread"), r.optString("path"), r.optInt("line"))
"download" -> { MdLinks.ctx?.let { c -> Downloads.file(c, DFileLink(r.optString("path"), r.optString("name"), r.optLong("size", -1L), "download"), thread) }; null }
"settings" -> LinkTarget(LinkTarget.Kind.SETTINGS, r.optString("page"))
else -> {
// a file the reply lists that no viewer here opens is downloaded instead
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,9 @@ object MdLinks {
var thread: String = ""
fun open(url: String) {
val c = ctx
val scheme = url.substringBefore(':', "")
val scheme = url.substringBefore(':', "").lowercase()
when {
url.startsWith(PATH_SCHEME) || scheme == "backplane" || scheme == BuildConfig.URL_SCHEME -> DataClient.openLink(url, thread)
url.startsWith(PATH_SCHEME) || scheme == "backplane" || scheme == BuildConfig.URL_SCHEME.lowercase() || scheme == "file" -> DataClient.openLink(url, thread)
scheme == "http" || scheme == "https" || scheme == "mailto" -> c?.let { runCatching { it.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)) } }
scheme == "tel" -> c?.let { runCatching { it.startActivity(android.content.Intent(android.content.Intent.ACTION_DIAL, android.net.Uri.parse(url)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)) } }
}
Expand Down Expand Up @@ -203,7 +203,8 @@ private fun AnnotatedString.Builder.inl(s: String, p: MdPalette, depth: Int, cx:
if (e > 0) {
val inner = s.substring(i + n, e).trim('`').let { if (it.startsWith(" ") && it.endsWith(" ") && it.isNotBlank()) it.trim() else it }
val code: AnnotatedString.Builder.() -> Unit = { withStyle(SpanStyle(fontFamily = BpMono, color = p.code, background = p.codeBg, fontSize = 12.5.sp)) { append(inner) } }
if (isPathText(inner)) link(pathLink(inner), p) { code() } else code()
val codeTarget = fileUrlPath(inner)?.let { pathLink(it) } ?: if (isPathText(inner)) pathLink(inner) else null
if (codeTarget != null) link(codeTarget, p) { code() } else code()
cx?.look?.inline(inner)?.let { piece -> appendInlineContent("cp${cx.pieces.size}", " "); cx.pieces.add(piece) }
i = e + n; continue
}
Expand All @@ -217,7 +218,7 @@ private fun AnnotatedString.Builder.inl(s: String, p: MdPalette, depth: Int, cx:
var pd = 0; var k = close + 1; var end = -1
while (k < s.length) { if (s[k] == '(') pd++ else if (s[k] == ')') { pd--; if (pd == 0) { end = k; break } }; k++ }
if (end > 0) {
val url = s.substring(close + 2, end).trim().removePrefix("<").substringBefore(' ').removeSuffix(">").let { if (isPathText(it)) pathLink(it) else it }
val url = linkTargetUrl(s.substring(close + 2, end))
val label = s.substring(st + 1, close)
link(url, p) { if (c == '!') append(label.ifEmpty { url }) else inl(label, p, depth + 1, cx) }
i = end + 1; continue
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,10 @@ fun DataRoot() {
Page.Home -> HomeScreen({ page = Page.Thread(it) }, { page = Page.Settings }, { page = Page.Hub(Page.Home) }, { page = Page.Folders() }, { page = Page.New(it) }, { page = Page.Swarm(it) }) { page = Page.Room(it) }
is Page.Term -> { BackHandler { page = p.from }; TermFull(p.key, Msg.palette_terminal) { page = p.from } }
is Page.Terms -> { BackHandler { page = p.from }; TermsScreen(p.project, { page = p.from }) { page = Page.Term(it, p) } }
is Page.Viewer -> { BackHandler { page = Page.Thread(p.id) }; DataClient.threads.firstOrNull { it.id == p.id }?.let { ViewerScreen(it, p.file, p.line) { page = Page.Thread(p.id) } }
is Page.Viewer -> { BackHandler { page = Page.Thread(p.id) }
val viewerThread = DataClient.threads.firstOrNull { it.id == p.id }
?: if (p.file.isNotEmpty()) DThread(id = p.id, project = "", title = p.file.substringAfterLast('/'), state = "idle", updatedAt = 0L, pinned = false, settled = false, archived = false, provider = "", model = "", preview = "", waiting = 0) else null
viewerThread?.let { ViewerScreen(it, p.file, p.line) { page = Page.Thread(p.id) } }
?: Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() } } // never a blank page while the thread list comes
is Page.Room -> { BackHandler { page = Page.Home }; RoomScreen(p.room) { page = Page.Home } }
is Page.Thread -> { BackHandler { page = p.from ?: Page.Home }; CompositionLocalProvider(LocalOpenSub provides { k -> page = Page.Sub(p.id, k) }) { ThreadScreen(p.id, { page = Page.Viewer(p.id) }, { page = Page.Hub(p) }, { page = Page.Thread(it) }, { page = Page.Settings }) { page = p.from ?: Page.Home } } }
Expand Down
22 changes: 17 additions & 5 deletions mobile/android/app/src/main/java/dev/backplane/mobile/Downloads.kt
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,11 @@ object Downloads {
File(c.cacheDir, "downloads").listFiles()?.forEach { d -> if (d !in live && d.lastModified() < day) d.deleteRecursively() }
}

private fun mime(name: String) = MimeTypeMap.getSingleton().getMimeTypeFromExtension(name.substringAfterLast('.', "").lowercase()) ?: "application/octet-stream"
private fun mime(name: String): String {
val ext = name.substringAfterLast('.', "").lowercase()
if (ext == "pdf") return "application/pdf"
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext) ?: "application/octet-stream"
}

/** A copy in the phone's Downloads: MediaStore from Android 10, the app's own Downloads folder before it. */
private fun saveToDownloads(c: Context, f: File) {
Expand All @@ -136,13 +140,21 @@ object Downloads {
private fun uri(c: Context, f: File): Uri = androidx.core.content.FileProvider.getUriForFile(c, c.packageName + ".files", f)
fun open(c: Context, r: DownloadRow) {
val f = r.file ?: return
val i = Intent(Intent.ACTION_VIEW).setDataAndType(uri(c, f), mime(f.name)).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
runCatching { c.startActivity(Intent.createChooser(i, f.name).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }.onFailure { DataClient.say(Msg.android_download_noapp) }
val u = uri(c, f)
val i = Intent(Intent.ACTION_VIEW).setDataAndType(u, mime(f.name))
.apply { clipData = android.content.ClipData.newRawUri(f.name, u) }
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
val chooser = Intent.createChooser(i, f.name).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION)
runCatching { c.startActivity(chooser) }.onFailure { DataClient.say(Msg.android_download_noapp) }
}
fun send(c: Context, r: DownloadRow) {
val f = r.file ?: return
val i = Intent(Intent.ACTION_SEND).setType(mime(f.name)).putExtra(Intent.EXTRA_STREAM, uri(c, f)).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
runCatching { c.startActivity(Intent.createChooser(i, f.name).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
val u = uri(c, f)
val i = Intent(Intent.ACTION_SEND).setType(mime(f.name)).putExtra(Intent.EXTRA_STREAM, u)
.apply { clipData = android.content.ClipData.newRawUri(f.name, u) }
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
val chooser = Intent.createChooser(i, f.name).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION)
runCatching { c.startActivity(chooser) }
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,17 @@ object FileFetch {
/** A name safe to be a file's: no folder in it, never `.` or `..`. */
fun safeName(n: String): String { val t = n.replace('/', '_').replace('\\', '_').trim(); return if (t.isEmpty() || t == "." || t == "..") "download" else t }

/** A path as a link carries it, without the line it points at (`a.rs:12`, `a.rs:3:4`, `a.rs#L4-L9`). */
fun bare(p: String): String = lineTail.replace(p, "")
/** A path as a link carries it, without `file://`, fragment, query, or the line it points at (`a.rs:12`, `a.rs:3:4`, `a.rs#L4-L9`). */
fun bare(p: String): String {
val s = fileUrlPath(p)?.substringBefore('#') ?: p.trim()
return lineTail.replace(s, "")
}

/** The file of [files] a tapped path names, in the message's spelling. */
fun find(p: String, files: List<DFileLink>): DFileLink? { val b = bare(p); return files.firstOrNull { it.path == p || it.path == b } }
fun find(p: String, files: List<DFileLink>): DFileLink? {
val b = bare(p)
return files.firstOrNull { it.path == p || it.path == b || bare(it.path) == b }
}

/** A thread of another machine (`<link>~<id>`) is named on the request; this hub's own thread is not. */
fun far(thread: String) = thread.contains('~')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import org.junit.Test
// Files of the hub's machine (docs/file-links.md): which link is a file to download, its address, and how a stopped download goes on
class FileFetchTest {
private val tok = "0123456789abcdef0123456789abcdef0123456789abcdef"
private val files = listOf(DFileLink("/home/user/p/mfg/gerbers.zip", "gerbers.zip", 123, "download"), DFileLink("~/p/board.kicad_pcb", "board.kicad_pcb", 9, "view"))
private val files = listOf(DFileLink("/home/user/p/mfg/gerbers.zip", "gerbers.zip", 123, "download"), DFileLink("~/p/board.kicad_pcb", "board.kicad_pcb", 9, "view"), DFileLink("/home/user/p/docs/My Doc.pdf", "My Doc.pdf", 456, "view"))

@Test fun sharesAreLinks() {
assertEquals("/s/$tok/gerbers.zip", FileFetch.shareRoute("/s/$tok/gerbers.zip"))
Expand All @@ -32,6 +32,9 @@ class FileFetchTest {

@Test fun aTappedPathFindsItsFile() {
assertEquals("gerbers.zip", FileFetch.find("/home/user/p/mfg/gerbers.zip", files)?.name)
assertEquals("gerbers.zip", FileFetch.find("file:///home/user/p/mfg/gerbers.zip", files)?.name)
assertEquals("My Doc.pdf", FileFetch.find("file:///home/user/p/docs/My%20Doc.pdf", files)?.name)
assertEquals("My Doc.pdf", FileFetch.find("file://localhost/home/user/p/docs/My%20Doc.pdf#page=2", files)?.name)
// a link carries the line it points at; the file is the same
assertEquals("board.kicad_pcb", FileFetch.find("~/p/board.kicad_pcb:12", files)?.name)
assertEquals("board.kicad_pcb", FileFetch.find("~/p/board.kicad_pcb:3:4", files)?.name)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,16 @@ class LinkGrammarTest {
assertEquals(listOf("backplane://thread/lab~t9|backplane://thread/lab~t9"), kinds("(backplane://thread/lab~t9)"))
assertEquals(listOf("backplane://conv/room%3Aabc|backplane://conv/room%3Aabc"), kinds("backplane://conv/room%3Aabc"))
}
@Test fun file_urls() {
assertEquals("/home/user/proj/docs/Parts List.pdf", fileUrlPath("file:///home/user/proj/docs/Parts%20List.pdf"))
assertEquals("/home/user/proj/docs/Spec Sheet.pdf", fileUrlPath("file://localhost/home/user/proj/docs/Spec%20Sheet.pdf#page=2"))
assertEquals("/home/user/proj/src/main.rs#L40-L50", fileUrlPath("file:///home/user/proj/src/main.rs#L40-L50"))
assertEquals("/home/user/proj/docs/Parts List.pdf", pathOf("file:///home/user/proj/docs/Parts%20List.pdf"))
assertEquals("bppath:/home/user/proj/docs/My Doc (Final).pdf", linkTargetUrl("file:///home/user/proj/docs/My%20Doc%20(Final).pdf"))
assertEquals("bppath:/home/user/proj/docs/Parts List.pdf", linkTargetUrl("<file:///home/user/proj/docs/Parts List.pdf>"))
assertEquals(
listOf("bppath:/home/user/proj/docs/Parts List.pdf|file:///home/user/proj/docs/Parts%20List.pdf"),
kinds("see file:///home/user/proj/docs/Parts%20List.pdf now"),
)
}
}
Loading
Loading