Android: browse a channel's files
Browse files on the channel sheet walks the channel's folders: download to where the user picks, upload a document, new folder, rename, delete. Transfers go through cache files and outlive the page, with progress and cancel; a locked channel asks for its password first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,132 @@
|
|||||||
|
package com.ts3client.android
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.Uri
|
||||||
|
import android.provider.OpenableColumns
|
||||||
|
import com.ts3client.net.TeamspeakConnection
|
||||||
|
import com.ts3client.net.filetransfer.FileTransfer
|
||||||
|
import com.ts3client.net.filetransfer.RemoteFile
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.File
|
||||||
|
import java.io.IOException
|
||||||
|
import java.util.concurrent.atomic.AtomicLong
|
||||||
|
|
||||||
|
/** One upload or download as the file browser shows it. */
|
||||||
|
data class TransferRow(
|
||||||
|
val id: Long,
|
||||||
|
val name: String,
|
||||||
|
val upload: Boolean,
|
||||||
|
val channelId: Int,
|
||||||
|
/** The directory an upload goes into, to list again once it is there. */
|
||||||
|
val directory: String,
|
||||||
|
val transferred: Long,
|
||||||
|
val total: Long,
|
||||||
|
val state: FileTransfer.State,
|
||||||
|
val error: String?,
|
||||||
|
) {
|
||||||
|
val done: Boolean get() = state != FileTransfer.State.PENDING && state != FileTransfer.State.ACTIVE
|
||||||
|
val progress: Float get() = if (total > 0) (transferred.toFloat() / total).coerceIn(0f, 1f) else 0f
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The channel file transfers of one server. Transfers go through files of our own in the cache,
|
||||||
|
* as the core reads and writes plain files: a download is copied where the user picked once
|
||||||
|
* complete, an upload is copied out of the picked document first. They outlive the browser page.
|
||||||
|
*/
|
||||||
|
class FileTransfers internal constructor(private val context: Context, private val conn: () -> TeamspeakConnection) {
|
||||||
|
|
||||||
|
private val ids = AtomicLong()
|
||||||
|
private val handles = HashMap<Long, FileTransfer>()
|
||||||
|
|
||||||
|
private val _rows = MutableStateFlow(emptyList<TransferRow>())
|
||||||
|
val rows: StateFlow<List<TransferRow>> = _rows
|
||||||
|
|
||||||
|
/** Downloads [file] into the document at [target]. */
|
||||||
|
fun download(channelId: Int, password: String, file: RemoteFile, target: Uri) {
|
||||||
|
val temp = File.createTempFile("download", null, context.cacheDir)
|
||||||
|
val row = add(file.name, upload = false, channelId, file.parentPath, file.size)
|
||||||
|
start(row, temp, onComplete = {
|
||||||
|
context.contentResolver.openOutputStream(target)?.use { out -> temp.inputStream().use { it.copyTo(out) } }
|
||||||
|
?: throw IOException("Could not write the file")
|
||||||
|
}) { listener -> conn().downloadFile(channelId, password, file.fullPath, temp, listener) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Uploads the document at [source] into [directory] (ending in "/"), replacing a file of the same name. */
|
||||||
|
suspend fun upload(channelId: Int, password: String, directory: String, source: Uri) {
|
||||||
|
val (name, temp) = withContext(Dispatchers.IO) { copyIn(source) }
|
||||||
|
val row = add(name, upload = true, channelId, directory, temp.length())
|
||||||
|
start(row, temp, onComplete = {}) { listener ->
|
||||||
|
conn().uploadFile(channelId, password, directory + name, temp, true, listener)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cancel(id: Long) {
|
||||||
|
synchronized(handles) { handles[id] }?.cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clearFinished() = _rows.update { rows -> rows.filterNot { it.done } }
|
||||||
|
|
||||||
|
private fun add(name: String, upload: Boolean, channelId: Int, directory: String, total: Long): TransferRow {
|
||||||
|
val row = TransferRow(ids.incrementAndGet(), name, upload, channelId, directory, 0, total,
|
||||||
|
FileTransfer.State.PENDING, null)
|
||||||
|
_rows.update { it + row }
|
||||||
|
return row
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs a transfer through [temp], which goes once it is done with; [onComplete] finishes a successful one. */
|
||||||
|
private fun start(row: TransferRow, temp: File, onComplete: () -> Unit,
|
||||||
|
begin: (FileTransfer.Listener) -> FileTransfer) {
|
||||||
|
var lastUpdate = 0L
|
||||||
|
val listener = FileTransfer.Listener { t ->
|
||||||
|
val now = System.nanoTime()
|
||||||
|
// Progress comes per buffer; the list need not redraw that often.
|
||||||
|
if (!t.isDone && now - lastUpdate < UPDATE_NANOS) return@Listener
|
||||||
|
lastUpdate = now
|
||||||
|
var error = t.errorMessage
|
||||||
|
if (t.state == FileTransfer.State.COMPLETED) {
|
||||||
|
error = runCatching(onComplete).exceptionOrNull()?.let { it.message ?: "Could not save the file" }
|
||||||
|
}
|
||||||
|
if (t.isDone) {
|
||||||
|
temp.delete()
|
||||||
|
synchronized(handles) { handles.remove(row.id) }
|
||||||
|
}
|
||||||
|
val state = if (error != null) FileTransfer.State.FAILED else t.state
|
||||||
|
update(row.id) { it.copy(transferred = t.transferredBytes, total = maxOf(t.totalBytes, 0), state = state, error = error) }
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
val handle = begin(listener)
|
||||||
|
synchronized(handles) { if (!handle.isDone) handles[row.id] = handle }
|
||||||
|
} catch (e: RuntimeException) {
|
||||||
|
temp.delete()
|
||||||
|
update(row.id) { it.copy(state = FileTransfer.State.FAILED, error = e.message ?: "Not connected") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun update(id: Long, change: (TransferRow) -> TransferRow) =
|
||||||
|
_rows.update { rows -> rows.map { if (it.id == id) change(it) else it } }
|
||||||
|
|
||||||
|
private fun copyIn(uri: Uri): Pair<String, File> {
|
||||||
|
val resolver = context.contentResolver
|
||||||
|
val name = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->
|
||||||
|
if (c.moveToFirst()) c.getString(0) else null
|
||||||
|
}?.takeIf { it.isNotBlank() } ?: uri.lastPathSegment ?: "file"
|
||||||
|
val temp = File.createTempFile("upload", null, context.cacheDir)
|
||||||
|
try {
|
||||||
|
resolver.openInputStream(uri)?.use { input -> temp.outputStream().use { input.copyTo(it) } }
|
||||||
|
?: throw IOException("Could not read the file")
|
||||||
|
} catch (e: IOException) {
|
||||||
|
temp.delete()
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
// A server path takes no slashes in a file name.
|
||||||
|
return name.replace('/', '_') to temp
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val UPDATE_NANOS = 200_000_000L
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ import com.ts3client.net.Details
|
|||||||
import com.ts3client.net.GroupChoice
|
import com.ts3client.net.GroupChoice
|
||||||
import com.ts3client.net.ban.BanEntry
|
import com.ts3client.net.ban.BanEntry
|
||||||
import com.ts3client.net.ban.BanRule
|
import com.ts3client.net.ban.BanRule
|
||||||
|
import com.ts3client.net.filetransfer.RemoteFile
|
||||||
import com.ts3client.net.ConnectionListener.ChatScope
|
import com.ts3client.net.ConnectionListener.ChatScope
|
||||||
import com.ts3client.session.ServerLink
|
import com.ts3client.session.ServerLink
|
||||||
import com.ts3client.session.ServerSession
|
import com.ts3client.session.ServerSession
|
||||||
@@ -214,6 +215,28 @@ class ServerController internal constructor(
|
|||||||
suspend fun deleteChannel(channelId: Int): String? =
|
suspend fun deleteChannel(channelId: Int): String? =
|
||||||
suspendCoroutine { done -> conn.deleteChannel(channelId, true) { done.resume(it) } }
|
suspendCoroutine { done -> conn.deleteChannel(channelId, true) { done.resume(it) } }
|
||||||
|
|
||||||
|
// ---- files ----
|
||||||
|
|
||||||
|
val files = app.fileTransfers { conn }
|
||||||
|
|
||||||
|
/** The files in a directory of a channel's repository; empty for an empty one. */
|
||||||
|
suspend fun listFiles(channelId: Int, password: String, path: String): Result<List<RemoteFile>> =
|
||||||
|
withContext(Dispatchers.IO) { runCatching { conn.listFiles(channelId, password, path) } }
|
||||||
|
|
||||||
|
/** Each of these answers null once done, else why not. */
|
||||||
|
suspend fun createDirectory(channelId: Int, password: String, path: String): String? =
|
||||||
|
fileCall { conn.createDirectory(channelId, password, path) }
|
||||||
|
|
||||||
|
suspend fun deleteFile(channelId: Int, password: String, path: String): String? =
|
||||||
|
fileCall { conn.deleteFile(channelId, password, path) }
|
||||||
|
|
||||||
|
suspend fun renameFile(channelId: Int, password: String, from: String, to: String): String? =
|
||||||
|
fileCall { conn.renameFile(channelId, password, from, to) }
|
||||||
|
|
||||||
|
private suspend fun fileCall(call: () -> Unit): String? = withContext(Dispatchers.IO) {
|
||||||
|
runCatching(call).exceptionOrNull()?.let { it.message ?: it.javaClass.simpleName }
|
||||||
|
}
|
||||||
|
|
||||||
// ---- moderation ----
|
// ---- moderation ----
|
||||||
|
|
||||||
val canKickFromChannel: Boolean get() = session.canKickFromChannel()
|
val canKickFromChannel: Boolean get() = session.canKickFromChannel()
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ import com.ts3client.myts.ChatAttachments
|
|||||||
import com.ts3client.myts.MyTeamSpeak
|
import com.ts3client.myts.MyTeamSpeak
|
||||||
import com.ts3client.myts.MyTeamSpeakLogin
|
import com.ts3client.myts.MyTeamSpeakLogin
|
||||||
import com.ts3client.net.HostButton
|
import com.ts3client.net.HostButton
|
||||||
|
import com.ts3client.net.TeamspeakConnection
|
||||||
import com.ts3client.session.SelfState
|
import com.ts3client.session.SelfState
|
||||||
import com.ts3client.session.ServerLink
|
import com.ts3client.session.ServerLink
|
||||||
import com.ts3client.session.ServerSession
|
import com.ts3client.session.ServerSession
|
||||||
@@ -88,6 +89,7 @@ class SessionController(private val context: Context) {
|
|||||||
private val shortcuts = BookmarkShortcuts(context, icons)
|
private val shortcuts = BookmarkShortcuts(context, icons)
|
||||||
val pictures = WebPictures(context.cacheDir, settings)
|
val pictures = WebPictures(context.cacheDir, settings)
|
||||||
internal val cacheDir: File get() = context.cacheDir
|
internal val cacheDir: File get() = context.cacheDir
|
||||||
|
internal fun fileTransfers(conn: () -> TeamspeakConnection) = FileTransfers(context, conn)
|
||||||
private val bookmarkStore = Bookmarks.load()
|
private val bookmarkStore = Bookmarks.load()
|
||||||
internal val identityStore = IdentityStore.load(settings)
|
internal val identityStore = IdentityStore.load(settings)
|
||||||
val identities = IdentityManager(context, identityStore, settings, bookmarkStore) {
|
val identities = IdentityManager(context, identityStore, settings, bookmarkStore) {
|
||||||
|
|||||||
@@ -87,7 +87,7 @@ fun rememberAttachmentActions(
|
|||||||
private const val SIGN_IN = "Sign in to myTeamSpeak to share files"
|
private const val SIGN_IN = "Sign in to myTeamSpeak to share files"
|
||||||
|
|
||||||
/** Asks where to save a file of the given name, typed by its extension. */
|
/** Asks where to save a file of the given name, typed by its extension. */
|
||||||
private object SaveAs : ActivityResultContract<String, Uri?>() {
|
internal object SaveAs : ActivityResultContract<String, Uri?>() {
|
||||||
override fun createIntent(context: Context, input: String): Intent {
|
override fun createIntent(context: Context, input: String): Intent {
|
||||||
val extension = input.substringAfterLast('.', "").lowercase()
|
val extension = input.substringAfterLast('.', "").lowercase()
|
||||||
val type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: "application/octet-stream"
|
val type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: "application/octet-stream"
|
||||||
|
|||||||
@@ -0,0 +1,239 @@
|
|||||||
|
package com.ts3client.android.ui
|
||||||
|
|
||||||
|
import android.text.format.DateUtils
|
||||||
|
import android.text.format.Formatter
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Close
|
||||||
|
import androidx.compose.material.icons.filled.MoreVert
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
|
import androidx.compose.material3.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.LinearProgressIndicator
|
||||||
|
import androidx.compose.material3.ListItem
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.SnackbarHostState
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import com.ts3client.android.ServerController
|
||||||
|
import com.ts3client.android.TransferRow
|
||||||
|
import com.ts3client.net.filetransfer.FileTransfer
|
||||||
|
import com.ts3client.net.filetransfer.RemoteFile
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
/** A channel's file repository: folders to walk, files to download, upload, rename and delete. */
|
||||||
|
@Composable
|
||||||
|
fun FilesScreen(server: ServerController, channelId: Int, channelName: String, password: String, onBack: () -> Unit) {
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
val snackbar = remember { SnackbarHostState() }
|
||||||
|
var path by rememberSaveable { mutableStateOf("/") }
|
||||||
|
var files by remember { mutableStateOf<List<RemoteFile>?>(null) }
|
||||||
|
var failure by remember { mutableStateOf<String?>(null) }
|
||||||
|
var reloads by remember { mutableIntStateOf(0) }
|
||||||
|
val transfers by server.files.rows.collectAsStateWithLifecycle()
|
||||||
|
var downloading by remember { mutableStateOf<RemoteFile?>(null) }
|
||||||
|
var creatingFolder by remember { mutableStateOf(false) }
|
||||||
|
var renaming by remember { mutableStateOf<RemoteFile?>(null) }
|
||||||
|
var deleting by remember { mutableStateOf<RemoteFile?>(null) }
|
||||||
|
|
||||||
|
LaunchedEffect(path, reloads) {
|
||||||
|
failure = null
|
||||||
|
server.listFiles(channelId, password, path)
|
||||||
|
.onSuccess { list -> files = list.sortedWith(compareBy({ !it.isDirectory }, { it.name.lowercase() })) }
|
||||||
|
.onFailure { files = emptyList(); failure = it.message ?: "Could not list the files" }
|
||||||
|
}
|
||||||
|
// An upload into the folder on screen shows up once it is there.
|
||||||
|
val uploadedHere = transfers.count { it.upload && it.channelId == channelId && it.directory == path && it.state == FileTransfer.State.COMPLETED }
|
||||||
|
LaunchedEffect(uploadedHere) { if (uploadedHere > 0) reloads++ }
|
||||||
|
|
||||||
|
val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit }
|
||||||
|
val act = { call: suspend () -> String? ->
|
||||||
|
scope.launch {
|
||||||
|
val error = call()
|
||||||
|
if (error != null) snackbar.showSnackbar(error) else reloads++
|
||||||
|
}
|
||||||
|
Unit
|
||||||
|
}
|
||||||
|
|
||||||
|
val saver = rememberLauncherForActivityResult(SaveAs) { uri ->
|
||||||
|
val file = downloading
|
||||||
|
downloading = null
|
||||||
|
if (uri != null && file != null) server.files.download(channelId, password, file, uri)
|
||||||
|
}
|
||||||
|
val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||||
|
if (uri != null) scope.launch {
|
||||||
|
runCatching { server.files.upload(channelId, password, path, uri) }
|
||||||
|
.onFailure { tell("Could not read the file: ${it.message}") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
SubScreen(channelName, onBack = { if (path == "/") onBack() else path = parentOf(path) }, snackbar = snackbar, actions = {
|
||||||
|
IconButton(onClick = { creatingFolder = true }) { PackIcon("ADD_FOLDER", "New folder") }
|
||||||
|
IconButton(onClick = { picker.launch(arrayOf("*/*")) }) { PackIcon("UPLOAD", "Upload") }
|
||||||
|
IconButton(onClick = { reloads++ }) { PackIcon(listOf("FILE_REFRESH", "REFRESH"), "Refresh") }
|
||||||
|
}) { padding ->
|
||||||
|
Column(Modifier.padding(padding).fillMaxSize()) {
|
||||||
|
Row(Modifier.fillMaxWidth().padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
IconButton(onClick = { path = parentOf(path) }, enabled = path != "/") { PackIcon("FILE_UP", "Up") }
|
||||||
|
Text(path, Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||||
|
style = MaterialTheme.typography.bodyMedium)
|
||||||
|
}
|
||||||
|
HorizontalDivider()
|
||||||
|
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||||
|
val list = files
|
||||||
|
when {
|
||||||
|
list == null -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||||
|
list.isEmpty() -> Text(failure ?: "No files", Modifier.align(Alignment.Center).padding(24.dp),
|
||||||
|
color = if (failure != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
else -> LazyColumn {
|
||||||
|
items(list, key = { it.fullPath }) { file ->
|
||||||
|
FileRow(file,
|
||||||
|
onOpen = {
|
||||||
|
if (file.isDirectory) path = file.fullPath + "/"
|
||||||
|
else { downloading = file; saver.launch(file.name) }
|
||||||
|
},
|
||||||
|
onRename = { renaming = file },
|
||||||
|
onDelete = { deleting = file })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (transfers.isNotEmpty()) Transfers(transfers, server.files::cancel, server.files::clearFinished)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (creatingFolder) {
|
||||||
|
TextPrompt("New folder", "Name", "Create", onDismiss = { creatingFolder = false }, onConfirm = { name ->
|
||||||
|
creatingFolder = false
|
||||||
|
if (name.isNotBlank()) act { server.createDirectory(channelId, password, path + name.trim()) }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
renaming?.let { file ->
|
||||||
|
TextPrompt("Rename", "Name", "Rename", initial = file.name, onDismiss = { renaming = null }, onConfirm = { name ->
|
||||||
|
renaming = null
|
||||||
|
if (name.isNotBlank() && name != file.name) {
|
||||||
|
act { server.renameFile(channelId, password, file.fullPath, file.parentPath + name.trim()) }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
deleting?.let { file ->
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { deleting = null },
|
||||||
|
title = { Text("Delete ${file.name}?") },
|
||||||
|
text = if (file.isDirectory) ({ Text("Everything in the folder goes with it.") }) else null,
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = {
|
||||||
|
deleting = null
|
||||||
|
act { server.deleteFile(channelId, password, file.fullPath) }
|
||||||
|
}) { Text("Delete") }
|
||||||
|
},
|
||||||
|
dismissButton = { TextButton(onClick = { deleting = null }) { Text("Cancel") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parentOf(path: String): String {
|
||||||
|
val trimmed = path.removeSuffix("/")
|
||||||
|
val slash = trimmed.lastIndexOf('/')
|
||||||
|
return if (slash <= 0) "/" else trimmed.substring(0, slash + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun FileRow(file: RemoteFile, onOpen: () -> Unit, onRename: () -> Unit, onDelete: () -> Unit) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
var menu by remember { mutableStateOf(false) }
|
||||||
|
val modified = if (file.lastModifiedEpochSec > 0) {
|
||||||
|
DateUtils.formatDateTime(context, file.lastModifiedEpochSec * 1000,
|
||||||
|
DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_ABBREV_MONTH)
|
||||||
|
} else null
|
||||||
|
ListItem(
|
||||||
|
headlineContent = { Text(file.name, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||||
|
supportingContent = {
|
||||||
|
Text(listOfNotNull(if (file.isDirectory) null else Formatter.formatShortFileSize(context, file.size), modified)
|
||||||
|
.joinToString(" · "))
|
||||||
|
},
|
||||||
|
leadingContent = { PackIcon(if (file.isDirectory) listOf("FOLDER") else listOf("FILE", "FILETRANSFER"), null) },
|
||||||
|
trailingContent = {
|
||||||
|
Box {
|
||||||
|
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "File options") }
|
||||||
|
DropdownMenu(menu, { menu = false }) {
|
||||||
|
if (!file.isDirectory) DropdownMenuItem({ Text("Download") }, onClick = { menu = false; onOpen() })
|
||||||
|
DropdownMenuItem({ Text("Rename") }, onClick = { menu = false; onRename() })
|
||||||
|
DropdownMenuItem({ Text("Delete") }, onClick = { menu = false; onDelete() })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
modifier = Modifier.clickable(onClick = onOpen),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The transfers under way and done, newest last. */
|
||||||
|
@Composable
|
||||||
|
private fun Transfers(rows: List<TransferRow>, onCancel: (Long) -> Unit, onClear: () -> Unit) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
Surface(tonalElevation = 3.dp) {
|
||||||
|
Column(Modifier.fillMaxWidth().heightIn(max = 220.dp)) {
|
||||||
|
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text("Transfers", Modifier.weight(1f), style = MaterialTheme.typography.titleSmall)
|
||||||
|
if (rows.any { it.done }) TextButton(onClick = onClear) { Text("Clear finished") }
|
||||||
|
}
|
||||||
|
LazyColumn {
|
||||||
|
items(rows, key = { it.id }) { row ->
|
||||||
|
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 4.dp, bottom = 4.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
PackIcon(if (row.upload) "UPLOAD" else "DOWNLOAD", null)
|
||||||
|
Column(Modifier.weight(1f).padding(horizontal = 12.dp)) {
|
||||||
|
Text(row.name, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium)
|
||||||
|
when (row.state) {
|
||||||
|
FileTransfer.State.PENDING, FileTransfer.State.ACTIVE ->
|
||||||
|
LinearProgressIndicator({ row.progress }, Modifier.fillMaxWidth().padding(vertical = 4.dp))
|
||||||
|
else -> Text(status(row, context), style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = if (row.state == FileTransfer.State.FAILED) MaterialTheme.colorScheme.error
|
||||||
|
else MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!row.done) IconButton(onClick = { onCancel(row.id) }) { Icon(Icons.Default.Close, "Cancel") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun status(row: TransferRow, context: android.content.Context): String = when (row.state) {
|
||||||
|
FileTransfer.State.COMPLETED -> (if (row.upload) "Uploaded" else "Downloaded") + " · " +
|
||||||
|
Formatter.formatShortFileSize(context, row.total)
|
||||||
|
FileTransfer.State.CANCELLED -> "Cancelled"
|
||||||
|
else -> row.error ?: "Failed"
|
||||||
|
}
|
||||||
@@ -106,6 +106,14 @@ private val ChannelEditSaver = Saver<ChannelEdit?, IntArray>(
|
|||||||
restore = { ChannelEdit(it[0], it[1]) },
|
restore = { ChannelEdit(it[0], it[1]) },
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/** A channel whose files are browsed, with the password they take. */
|
||||||
|
private data class FilesOf(val channelId: Int, val name: String, val password: String)
|
||||||
|
|
||||||
|
private val FilesOfSaver = Saver<FilesOf?, List<Any>>(
|
||||||
|
save = { f -> f?.let { listOf(it.channelId, it.name, it.password) } },
|
||||||
|
restore = { FilesOf(it[0] as Int, it[1] as String, it[2] as String) },
|
||||||
|
)
|
||||||
|
|
||||||
/** A connection: the channel tree and the chat, with the voice controls underneath. */
|
/** A connection: the channel tree and the chat, with the voice controls underneath. */
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
@@ -144,6 +152,9 @@ fun ServerScreen(
|
|||||||
val bookmarkHere = { channelId: Int -> server.bookmark(channelId)?.let { onEditBookmark(BookmarkEdit(-1, it)) } }
|
val bookmarkHere = { channelId: Int -> server.bookmark(channelId)?.let { onEditBookmark(BookmarkEdit(-1, it)) } }
|
||||||
var banList by rememberSaveable { mutableStateOf(false) }
|
var banList by rememberSaveable { mutableStateOf(false) }
|
||||||
var channelEdit by rememberSaveable(stateSaver = ChannelEditSaver) { mutableStateOf<ChannelEdit?>(null) }
|
var channelEdit by rememberSaveable(stateSaver = ChannelEditSaver) { mutableStateOf<ChannelEdit?>(null) }
|
||||||
|
var files by rememberSaveable(stateSaver = FilesOfSaver) { mutableStateOf<FilesOf?>(null) }
|
||||||
|
/** A locked channel whose files are wanted, while its password is asked for. */
|
||||||
|
var filesLocked by remember { mutableStateOf<Int?>(null) }
|
||||||
var deletingChannel by remember { mutableStateOf<Int?>(null) }
|
var deletingChannel by remember { mutableStateOf<Int?>(null) }
|
||||||
var connectionInfo by rememberSaveable { mutableStateOf<Int?>(null) }
|
var connectionInfo by rememberSaveable { mutableStateOf<Int?>(null) }
|
||||||
/** The client to move, while a channel for them is being picked. */
|
/** The client to move, while a channel for them is being picked. */
|
||||||
@@ -231,6 +242,10 @@ fun ServerScreen(
|
|||||||
ChannelEditScreen(server, it, onDone = { channelEdit = null })
|
ChannelEditScreen(server, it, onDone = { channelEdit = null })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
files?.let {
|
||||||
|
FilesScreen(server, it.channelId, it.name, it.password, onBack = { files = null })
|
||||||
|
return
|
||||||
|
}
|
||||||
connectionInfo?.let { id ->
|
connectionInfo?.let { id ->
|
||||||
ConnectionInfoScreen(server, id, tree.client(id), onBack = { connectionInfo = null })
|
ConnectionInfoScreen(server, id, tree.client(id), onBack = { connectionInfo = null })
|
||||||
return
|
return
|
||||||
@@ -397,6 +412,10 @@ fun ServerScreen(
|
|||||||
onJoin = { join(channel); channelSheet = null },
|
onJoin = { join(channel); channelSheet = null },
|
||||||
onSubscribe = { server.setSubscribed(id, it); channelSheet = null },
|
onSubscribe = { server.setSubscribed(id, it); channelSheet = null },
|
||||||
onBookmark = { channelSheet = null; bookmarkHere(id) },
|
onBookmark = { channelSheet = null; bookmarkHere(id) },
|
||||||
|
onFiles = {
|
||||||
|
channelSheet = null
|
||||||
|
if (channel.locked) filesLocked = id else files = FilesOf(id, channel.name, "")
|
||||||
|
},
|
||||||
onCreateSub = if (server.canCreateChannels) ({ channelSheet = null; channelEdit = ChannelEdit(0, id) }) else null,
|
onCreateSub = if (server.canCreateChannels) ({ channelSheet = null; channelEdit = ChannelEdit(0, id) }) else null,
|
||||||
onEdit = if (server.canEditChannels) ({ channelSheet = null; channelEdit = ChannelEdit(id) }) else null,
|
onEdit = if (server.canEditChannels) ({ channelSheet = null; channelEdit = ChannelEdit(id) }) else null,
|
||||||
onDelete = if (server.canDeleteChannels) ({ channelSheet = null; deletingChannel = id }) else null,
|
onDelete = if (server.canDeleteChannels) ({ channelSheet = null; deletingChannel = id }) else null,
|
||||||
@@ -413,6 +432,16 @@ fun ServerScreen(
|
|||||||
onConfirm = { joinLocked = null; server.joinChannel(id, it) },
|
onConfirm = { joinLocked = null; server.joinChannel(id, it) },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
filesLocked?.let { id ->
|
||||||
|
TextPrompt(
|
||||||
|
title = "Files of ${tree.channel(id)?.name.orEmpty()}",
|
||||||
|
label = "Channel password",
|
||||||
|
confirm = "Open",
|
||||||
|
password = true,
|
||||||
|
onDismiss = { filesLocked = null },
|
||||||
|
onConfirm = { filesLocked = null; files = FilesOf(id, tree.channel(id)?.name.orEmpty(), it) },
|
||||||
|
)
|
||||||
|
}
|
||||||
deletingChannel?.let { id ->
|
deletingChannel?.let { id ->
|
||||||
val channel = tree.channel(id)
|
val channel = tree.channel(id)
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
|
|||||||
@@ -141,6 +141,7 @@ fun ChannelSheet(
|
|||||||
onJoin: () -> Unit,
|
onJoin: () -> Unit,
|
||||||
onSubscribe: (Boolean) -> Unit,
|
onSubscribe: (Boolean) -> Unit,
|
||||||
onBookmark: () -> Unit,
|
onBookmark: () -> Unit,
|
||||||
|
onFiles: () -> Unit,
|
||||||
/** Each null when we may not. */
|
/** Each null when we may not. */
|
||||||
onCreateSub: (() -> Unit)?,
|
onCreateSub: (() -> Unit)?,
|
||||||
onEdit: (() -> Unit)?,
|
onEdit: (() -> Unit)?,
|
||||||
@@ -159,6 +160,7 @@ fun ChannelSheet(
|
|||||||
} else {
|
} else {
|
||||||
Action("SUBSCRIBE_TO_CHANNEL", "Subscribe") { onSubscribe(true) }
|
Action("SUBSCRIBE_TO_CHANNEL", "Subscribe") { onSubscribe(true) }
|
||||||
}
|
}
|
||||||
|
Action("FILETRANSFER", "Browse files", onClick = onFiles)
|
||||||
Action("BOOKMARK_ADD", "Add to bookmarks", onClick = onBookmark)
|
Action("BOOKMARK_ADD", "Add to bookmarks", onClick = onBookmark)
|
||||||
onCreateSub?.let { Action("CHANNEL_CREATE_SUB", "Create sub-channel", onClick = it) }
|
onCreateSub?.let { Action("CHANNEL_CREATE_SUB", "Create sub-channel", onClick = it) }
|
||||||
onEdit?.let { Action("CHANNEL_EDIT", "Edit channel", onClick = it) }
|
onEdit?.let { Action("CHANNEL_EDIT", "Edit channel", onClick = it) }
|
||||||
|
|||||||
Reference in New Issue
Block a user