Share pictures and files in chat, the way TeamSpeak 6 does

A shared file goes to the sender's myTeamSpeak cloud storage, and an
ordinary text message carries TeamSpeak 6's ts.file.myts pointer to it, so
TeamSpeak 6 users see the file and we see theirs. Pictures show inline
through the description picture cache, other files as a link to save;
logged history shows them too. Sharing and fetching need a myTeamSpeak
sign-in.

Desktop: share button, drop or paste files and pictures, a picture viewer.
Android: attach from the system picker, tap to view or save.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-09 11:23:25 +00:00
co-authored by Claude Opus 5.5
parent 1bb788b501
commit ad9dfa5be0
32 changed files with 1834 additions and 66 deletions
@@ -1,5 +1,6 @@
package com.ts3client.android
import android.net.Uri
import com.ts3client.contacts.ContactType
import com.ts3client.net.ChannelNode
import com.ts3client.net.ConnectionStats
@@ -9,7 +10,6 @@ import com.ts3client.net.ban.BanEntry
import com.ts3client.net.ban.BanRule
import com.ts3client.net.ConnectionListener.ChatScope
import com.ts3client.session.ServerSession
import com.ts3client.text.BBCode
import com.ts3client.text.ChatHtml
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -303,14 +303,26 @@ class ServerController internal constructor(
fun closePrivateChat(key: ChatKey.Private) = _chats.update { it.close(key) }
fun send(key: ChatKey, text: String) {
when (key) {
ChatKey.Server -> session.sendChat(ChatScope.SERVER, 0, text)
ChatKey.Channel -> session.sendChat(ChatScope.CHANNEL, 0, text)
is ChatKey.Private -> session.sendChat(ChatScope.PRIVATE, key.clientId, text)
}
fun send(key: ChatKey, text: String) = session.sendChat(scope(key), peer(key), text)
/** Shares the file at [uri] in a chat, through myTeamSpeak; failures are told in the chat or as errors. */
suspend fun sendFile(key: ChatKey, uri: Uri) {
app.openShared(uri)
.onSuccess { session.sendAttachment(scope(key), peer(key), app.attachments, it.data, it.size, it.name) }
.onFailure { app.error(it.message ?: "Could not read the file") }
}
private fun scope(key: ChatKey) = when (key) {
ChatKey.Server -> ChatScope.SERVER
ChatKey.Channel -> ChatScope.CHANNEL
is ChatKey.Private -> ChatScope.PRIVATE
}
private fun peer(key: ChatKey) = if (key is ChatKey.Private) key.clientId else 0
/** Where files shared on this server lie; empty before it is known. */
private val room: String get() = conn.serverUniqueId().orEmpty()
fun markRead(key: ChatKey) {
if (_chats.value[key]?.unread == true) _chats.update { chats -> chats.update(key) { it.copy(unread = false) } }
}
@@ -335,7 +347,7 @@ class ServerController internal constructor(
}
private fun setHistory(key: ChatKey, title: String, entries: List<String>) {
val lines = entries.map(ChatHtml::logEntry).filter { it.isNotEmpty() }
val lines = entries.map { ChatHtml.logEntry(it, room) }.filter { it.isNotEmpty() }
.map { ChatLine(lineIds.incrementAndGet(), it) }
_chats.update { chats -> chats.update(key, title) { it.copy(lines = lines) } }
}
@@ -397,9 +409,9 @@ class ServerController internal constructor(
override fun onOwnChat(scope: ChatScope, peerClientId: Int, peerName: String, text: String) {
val self = conn.model.getClient(conn.selfClientId)?.nickname ?: app.settings.nickname
val html = ChatHtml.message(conn.selfClientId, conn.selfUniqueId, "$self (you)", text)
val html = ChatHtml.message(conn.selfClientId, conn.selfUniqueId, "$self (you)", text, room)
append(key(scope, peerClientId), peerName, html)
if (scope == ChatScope.PRIVATE) app.notifier.sent(id, peerClientId, BBCode.toPlain(text))
if (scope == ChatScope.PRIVATE) app.notifier.sent(id, peerClientId, ChatHtml.plainMessage(text))
}
override fun onStatus(status: String) {}
@@ -437,9 +449,9 @@ class ServerController internal constructor(
override fun onIconsUpdated() = images.loaded()
override fun onChat(scope: ChatScope, fromClientId: Int, fromUniqueId: String?, fromName: String, message: String) {
append(key(scope, fromClientId), fromName, ChatHtml.message(fromClientId, fromUniqueId, fromName, message))
append(key(scope, fromClientId), fromName, ChatHtml.message(fromClientId, fromUniqueId, fromName, message, room))
if (scope == ChatScope.PRIVATE && !app.foreground) {
app.notifier.received(id, fromClientId, fromName, BBCode.toPlain(message))
app.notifier.received(id, fromClientId, fromName, ChatHtml.plainMessage(message))
}
}
@@ -460,7 +472,7 @@ class ServerController internal constructor(
override fun onPoke(fromName: String, message: String) = app.poked(fromName, message)
override fun onServerLog(message: String) = append(ChatKey.Server, "", ChatHtml.serverLog(message))
override fun onServerLogHtml(html: String) = append(ChatKey.Server, "", ChatHtml.logEntry(html))
override fun onServerLogHtml(html: String) = append(ChatKey.Server, "", ChatHtml.logEntry(html, room))
}
private fun key(scope: ChatScope, peerClientId: Int): ChatKey = when (scope) {
@@ -7,6 +7,7 @@ import android.content.pm.PackageManager
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.provider.OpenableColumns
import com.ts3client.android.audio.AndroidAudioBackend
import com.ts3client.android.audio.AudioRoute
import com.ts3client.audio.AudioDevice
@@ -17,9 +18,11 @@ import com.ts3client.config.IdentityStore
import com.ts3client.config.Settings
import com.ts3client.contacts.Contact
import com.ts3client.contacts.ContactStore
import com.ts3client.myts.ChatAttachment
import com.ts3client.myts.ChatAttachments
import com.ts3client.myts.MyTeamSpeak
import com.ts3client.net.HostButton
import com.ts3client.myts.MyTeamSpeakLogin
import com.ts3client.net.HostButton
import com.ts3client.session.SelfState
import com.ts3client.session.ServerSession
import com.ts3client.session.Sessions
@@ -37,6 +40,8 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.util.concurrent.atomic.AtomicInteger
/** What the app shows of a connection and the local client on it. */
@@ -59,6 +64,9 @@ data class SessionState(
val self: SelfState = SelfState.DISCONNECTED,
)
/** A file to share in chat, open for reading. */
internal class SharedFile(val name: String, val size: Long, val data: InputStream)
/** Something that happened once, for the UI to tell the user about. */
sealed interface SessionEvent {
data class Poke(val from: String, val message: String) : SessionEvent
@@ -204,6 +212,7 @@ class SessionController(private val context: Context) {
servers.forEach(ServerController::leaving)
ServerSession.shutdownAll(servers.map { it.session })
contactStore.flush()
attachments.close()
}
fun server(id: Int): ServerController? = _servers.value.firstOrNull { it.id == id }
@@ -326,10 +335,67 @@ class SessionController(private val context: Context) {
val myTeamSpeak: MyTeamSpeakLogin = MyTeamSpeakLogin.load()
private val importer = TeamSpeakImporter(identityStore, bookmarkStore, settings)
private val _myTeamSpeakSignedIn = MutableStateFlow(myTeamSpeak.isSignedIn)
val myTeamSpeakSignedIn: StateFlow<Boolean> = _myTeamSpeakSignedIn
/** Files shared in chat, kept in the myTeamSpeak account's cloud storage. */
internal val attachments = ChatAttachments(myTeamSpeak).also {
pictures.addSource(ChatAttachment.SCHEME, it::fetchPicture)
}
suspend fun signInMyTeamSpeak(email: String, password: String): MyTeamSpeak.Account =
withContext(Dispatchers.IO) { myTeamSpeak.signIn(email, password) }
.also {
_myTeamSpeakSignedIn.value = true
// Shared pictures that could not be had signed out.
pictures.retryFailed()
}
suspend fun fetchMyTeamSpeak(): MyTeamSpeak.Account = withContext(Dispatchers.IO) { myTeamSpeak.fetch() }
suspend fun fetchMyTeamSpeak(): MyTeamSpeak.Account =
try {
withContext(Dispatchers.IO) { myTeamSpeak.fetch() }
} finally {
// A sign-in the server no longer takes has signed out.
_myTeamSpeakSignedIn.value = myTeamSpeak.isSignedIn
}
suspend fun signOutMyTeamSpeak() {
myTeamSpeak.signOut()
_myTeamSpeakSignedIn.value = false
withContext(Dispatchers.IO) { attachments.close() }
}
/** Fetches a file shared in chat whole. */
suspend fun downloadAttachment(ref: ChatAttachment.Ref): ByteArray =
withContext(Dispatchers.IO) { attachments.download(ref, ChatAttachments.MAX_UPLOAD_BYTES) }
/** Fetches a file shared in chat into [uri], e.g. one the user picked to save it as. */
suspend fun saveAttachment(ref: ChatAttachment.Ref, uri: Uri) {
val data = downloadAttachment(ref)
withContext(Dispatchers.IO) {
val out = context.contentResolver.openOutputStream(uri) ?: throw IOException("Could not write the file")
out.use { it.write(data) }
}
}
/** A file picked to share in chat, or why it cannot be. */
internal suspend fun openShared(uri: Uri): Result<SharedFile> = withContext(Dispatchers.IO) {
runCatching {
val resolver = context.contentResolver
val (name, size) = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE),
null, null, null)?.use { c ->
if (!c.moveToFirst()) null
else c.getString(0).orEmpty() to (if (c.isNull(1)) -1L else c.getLong(1))
} ?: ("" to -1L)
when {
size < 0 -> throw IOException("Could not read the file's size")
size > ChatAttachments.MAX_UPLOAD_BYTES ->
throw IOException("Files over ${ChatAttachments.MAX_UPLOAD_BYTES shr 20} MB cannot be shared")
}
val data = resolver.openInputStream(uri) ?: throw IOException("Could not read the file")
SharedFile(name.ifBlank { uri.lastPathSegment ?: "file" }, size, data)
}
}
fun isImported(item: SyncItem): Boolean = importer.isPresent(item)
@@ -32,6 +32,12 @@ class WebPictures(cacheDir: File, private val settings: Settings) {
downloads.addListener { _version.update { it + 1 } }
}
/** Fetches pictures whose addresses start with [scheme] from [source] rather than the web. */
fun addSource(scheme: String, source: PictureDownloads.Source) = downloads.addSource(scheme, source)
/** Asks again for the pictures that could not be had. */
fun retryFailed() = downloads.retryFailed()
/** Whether pictures are shown at all, rather than links to them. */
val enabled: Boolean get() = settings.descriptionPictures
@@ -0,0 +1,102 @@
package com.ts3client.android.ui
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.webkit.MimeTypeMap
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.ts3client.android.ChatKey
import com.ts3client.android.ServerController
import com.ts3client.android.SessionController
import com.ts3client.myts.ChatAttachment
import com.ts3client.myts.MyTsException
import kotlinx.coroutines.launch
import java.io.IOException
/** What the chat does with shared files: [open] one it links to, [share] one into a conversation. */
class AttachmentActions(val open: (String) -> Unit, val share: () -> Unit)
/**
* Shared files for [server]'s chat: a picture opens full size, anything else is saved where
* the user picks; sharing picks a file to send into the conversation [shown] gives.
*/
@Composable
fun rememberAttachmentActions(
vm: SessionController,
server: ServerController,
snackbar: SnackbarHostState,
shown: ChatKey,
): AttachmentActions {
val scope = rememberCoroutineScope()
val signedIn by vm.myTeamSpeakSignedIn.collectAsStateWithLifecycle()
val key by rememberUpdatedState(shown)
val viewer = LocalPictureViewer.current
val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit }
var saving by rememberSaveable { mutableStateOf<String?>(null) }
val saver = rememberLauncherForActivityResult(SaveAs) { uri ->
val ref = ChatAttachment.Ref.parse(saving)
saving = null
if (uri == null || ref == null) return@rememberLauncherForActivityResult
scope.launch {
val error = try {
vm.saveAttachment(ref, uri)
null
} catch (e: MyTsException) {
e.message
} catch (e: IOException) {
e.message
}
snackbar.showSnackbar(if (error == null) "Saved ${ref.fileName}." else "Could not save ${ref.fileName}: $error")
}
}
val picker = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
if (uri != null) scope.launch { server.sendFile(key, uri) }
}
return AttachmentActions(
open = open@{ href ->
val ref = ChatAttachment.Ref.parse(href) ?: return@open
when {
!signedIn -> tell(SIGN_IN)
ref.isImage() && viewer != null -> viewer(ViewedPicture(ref.fileName.substringBeforeLast('.')) {
vm.pictures.data(href) ?: runCatching { vm.downloadAttachment(ref) }.getOrNull()
})
else -> {
saving = href
saver.launch(ref.fileName)
}
}
},
share = { if (signedIn) picker.launch("*/*") else tell(SIGN_IN) },
)
}
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. */
private object SaveAs : ActivityResultContract<String, Uri?>() {
override fun createIntent(context: Context, input: String): Intent {
val extension = input.substringAfterLast('.', "").lowercase()
val type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: "application/octet-stream"
return Intent(Intent.ACTION_CREATE_DOCUMENT)
.addCategory(Intent.CATEGORY_OPENABLE)
.setType(type)
.putExtra(Intent.EXTRA_TITLE, input)
}
override fun parseResult(resultCode: Int, intent: Intent?): Uri? =
intent?.data.takeIf { resultCode == Activity.RESULT_OK }
}
@@ -16,6 +16,7 @@ import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.filled.AttachFile
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Badge
import androidx.compose.material3.FilterChip
@@ -62,6 +63,8 @@ fun ChatPane(
onSelect: (ChatKey) -> Unit,
onClose: (ChatKey.Private) -> Unit,
onSend: (String) -> Unit,
/** Picks a file to share in [selected]. */
onAttach: () -> Unit,
onLink: (String) -> Unit,
modifier: Modifier = Modifier,
/** The lines to show, when not all of [selected]'s. */
@@ -95,6 +98,9 @@ fun ChatPane(
}
}
Row(Modifier.padding(8.dp), verticalAlignment = Alignment.CenterVertically) {
IconButton(onClick = onAttach, enabled = canSend) {
Icon(Icons.Filled.AttachFile, "Share file")
}
OutlinedTextField(
draft, { drafts[draftKey] = it },
Modifier.weight(1f).onPreviewKeyEvent { e ->
@@ -31,6 +31,7 @@ import androidx.compose.ui.text.fromHtml
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.ts3client.android.WebPictures
import com.ts3client.myts.ChatAttachment
import com.ts3client.text.BBCode
import com.ts3client.text.ChatHtml
import com.ts3client.text.TextQuery
@@ -195,8 +196,7 @@ private fun WebPicture(image: Piece.Image, style: TextStyle, onLink: (String) ->
.widthIn(max = picture.width.dp)
.aspectRatio(picture.width.toFloat() / picture.height.coerceAtLeast(1))
.then(if (viewer != null) Modifier.clickable {
val openLink = image.href?.let { href -> { onLink(href) } }
viewer(ViewedPicture(pictureName(image.url), image.url, openLink) { pictures.data(image.url) })
viewer(viewedPicture(image, onLink) { pictures.data(image.url) })
} else if (image.href != null) Modifier.clickable { onLink(image.href) } else Modifier),
)
}
@@ -204,13 +204,21 @@ private fun WebPicture(image: Piece.Image, style: TextStyle, onLink: (String) ->
}
}
/** [image] to open full size; a file shared in chat has no address to copy or link to follow but itself. */
private fun viewedPicture(image: Piece.Image, onLink: (String) -> Unit, read: suspend () -> ByteArray?): ViewedPicture {
val attachment = ChatAttachment.Ref.parse(image.url)
if (attachment != null) return ViewedPicture(attachment.fileName.substringBeforeLast('.'), read = read)
val openLink = image.href?.let { href -> { onLink(href) } }
return ViewedPicture(pictureName(image.url), image.url, openLink, read = read)
}
/** The picture's address as a link behind [iconKey], then the link it sat in, if any, so neither is lost. */
@Composable
private fun PictureLink(iconKey: String, image: Piece.Image, style: TextStyle, onLink: (String) -> Unit) {
val color = linkColor()
val text = remember(image, color) {
val links = listOfNotNull(image.url, image.href?.takeIf { it != image.url })
chatText(links.joinToString(" ") { "<a href=\"${BBCode.escape(it)}\">${BBCode.escape(BBCode.shortAddress(it))}</a>" }, color, onLink)
chatText(links.joinToString(" ") { "<a href=\"${BBCode.escape(it)}\">${BBCode.escape(linkText(it))}</a>" }, color, onLink)
}
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
PackIcon(iconKey, "Picture", size = 16.dp)
@@ -218,6 +226,9 @@ private fun PictureLink(iconKey: String, image: Piece.Image, style: TextStyle, o
}
}
/** A shared file goes by its name, anything else by its address. */
private fun linkText(url: String): String = ChatAttachment.Ref.parse(url)?.fileName ?: BBCode.shortAddress(url)
/**
* HTML without rules as styled text. Android's parser knows no stylesheets, tables,
* numbered lists, font sizes or `align`, so the classes [ChatHtml] marks lines with become
@@ -160,7 +160,7 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
OutlinedButton(onClick = {
login.signOut()
scope.launch { vm.signOutMyTeamSpeak() }
signedIn = false
rows = emptyList()
all = emptyList()
@@ -77,6 +77,7 @@ import com.ts3client.android.SessionState
import com.ts3client.android.TreeFind
import com.ts3client.android.findIn
import com.ts3client.config.Settings
import com.ts3client.myts.ChatAttachment
import com.ts3client.text.TsLink
private val ChatKeySaver = Saver<ChatKey, String>(
@@ -151,9 +152,11 @@ fun ServerScreen(
}
val uriHandler = LocalUriHandler.current
val attachments = rememberAttachmentActions(vm, server, snackbar, conversation.key)
val onLink: (String) -> Unit = { href ->
val ref = TsLink.parse(href)
when {
ChatAttachment.isHref(href) -> attachments.open(href)
ref == null -> runCatching { uriHandler.openUri(href) }
ref.client -> { clientSheet = ref.id; clientSheetFromTree = false }
else -> channelSheet = ref.id
@@ -315,6 +318,7 @@ fun ServerScreen(
server.closePrivateChat(key)
},
onSend = { server.send(conversation.key, it) },
onAttach = attachments.share,
onLink = onLink,
modifier = Modifier.weight(1f),
lines = chatLines,