From ad9dfa5be0e2b41d73346af66f37724f837b3cd9 Mon Sep 17 00:00:00 2001 From: ericek111 Date: Fri, 9 Oct 2026 11:23:25 +0000 Subject: [PATCH] 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 --- .../com/ts3client/android/ServerController.kt | 38 ++-- .../ts3client/android/SessionController.kt | 70 +++++- .../java/com/ts3client/android/WebPictures.kt | 6 + .../com/ts3client/android/ui/Attachments.kt | 102 +++++++++ .../java/com/ts3client/android/ui/ChatPane.kt | 6 + .../java/com/ts3client/android/ui/ChatText.kt | 17 +- .../ts3client/android/ui/MyTeamSpeakScreen.kt | 2 +- .../com/ts3client/android/ui/ServerScreen.kt | 4 + .../com/ts3client/myts/ChatAttachment.java | 137 ++++++++++++ .../com/ts3client/myts/ChatAttachments.java | 67 ++++++ .../java/com/ts3client/myts/MyTeamSpeak.java | 46 ++-- .../com/ts3client/myts/MyTeamSpeakLogin.java | 11 +- .../java/com/ts3client/myts/MyTsFiles.java | 183 ++++++++++++++++ .../com/ts3client/net/PictureDownloads.java | 29 ++- .../ts3client/net/TeamspeakConnection.java | 8 +- .../com/ts3client/session/ServerSession.java | 38 ++++ .../java/com/ts3client/text/ChatHtml.java | 75 ++++++- .../main/java/com/ts3client/text/Json.java | 167 ++++++++++++++ .../ts3client/myts/ChatAttachmentTest.java | 69 ++++++ .../com/ts3client/myts/MyTsFilesTest.java | 88 ++++++++ .../text/ChatHtmlAttachmentTest.java | 58 +++++ .../ui/AttachmentTransferHandler.java | 128 +++++++++++ .../ts3client/ui/ChatAttachmentActions.java | 145 +++++++++++++ .../java/com/ts3client/ui/ChatLogsPanel.java | 2 +- .../main/java/com/ts3client/ui/ChatPanel.java | 204 +++++++++++++++++- .../com/ts3client/ui/DescriptionPictures.java | 60 +++++- .../com/ts3client/ui/DesktopNotifier.java | 3 +- .../java/com/ts3client/ui/HtmlStyles.java | 3 + .../main/java/com/ts3client/ui/MainFrame.java | 32 ++- .../com/ts3client/ui/MyTeamSpeakPanel.java | 13 +- .../java/com/ts3client/ui/PictureViewer.java | 78 +++++++ .../main/java/com/ts3client/ui/ServerTab.java | 11 +- 32 files changed, 1834 insertions(+), 66 deletions(-) create mode 100644 android/app/src/main/java/com/ts3client/android/ui/Attachments.kt create mode 100644 ts3-client/core/src/main/java/com/ts3client/myts/ChatAttachment.java create mode 100644 ts3-client/core/src/main/java/com/ts3client/myts/ChatAttachments.java create mode 100644 ts3-client/core/src/main/java/com/ts3client/myts/MyTsFiles.java create mode 100644 ts3-client/core/src/main/java/com/ts3client/text/Json.java create mode 100644 ts3-client/core/src/test/java/com/ts3client/myts/ChatAttachmentTest.java create mode 100644 ts3-client/core/src/test/java/com/ts3client/myts/MyTsFilesTest.java create mode 100644 ts3-client/core/src/test/java/com/ts3client/text/ChatHtmlAttachmentTest.java create mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/AttachmentTransferHandler.java create mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ChatAttachmentActions.java create mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/PictureViewer.java diff --git a/android/app/src/main/java/com/ts3client/android/ServerController.kt b/android/app/src/main/java/com/ts3client/android/ServerController.kt index 1786a27..1c45d80 100644 --- a/android/app/src/main/java/com/ts3client/android/ServerController.kt +++ b/android/app/src/main/java/com/ts3client/android/ServerController.kt @@ -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) { - 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) { diff --git a/android/app/src/main/java/com/ts3client/android/SessionController.kt b/android/app/src/main/java/com/ts3client/android/SessionController.kt index 08b7e63..ae40af8 100644 --- a/android/app/src/main/java/com/ts3client/android/SessionController.kt +++ b/android/app/src/main/java/com/ts3client/android/SessionController.kt @@ -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 = _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 = 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) diff --git a/android/app/src/main/java/com/ts3client/android/WebPictures.kt b/android/app/src/main/java/com/ts3client/android/WebPictures.kt index 4c68cd5..f122248 100644 --- a/android/app/src/main/java/com/ts3client/android/WebPictures.kt +++ b/android/app/src/main/java/com/ts3client/android/WebPictures.kt @@ -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 diff --git a/android/app/src/main/java/com/ts3client/android/ui/Attachments.kt b/android/app/src/main/java/com/ts3client/android/ui/Attachments.kt new file mode 100644 index 0000000..e8d009a --- /dev/null +++ b/android/app/src/main/java/com/ts3client/android/ui/Attachments.kt @@ -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(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() { + 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 } +} diff --git a/android/app/src/main/java/com/ts3client/android/ui/ChatPane.kt b/android/app/src/main/java/com/ts3client/android/ui/ChatPane.kt index a8cb753..dc2778a 100644 --- a/android/app/src/main/java/com/ts3client/android/ui/ChatPane.kt +++ b/android/app/src/main/java/com/ts3client/android/ui/ChatPane.kt @@ -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 -> diff --git a/android/app/src/main/java/com/ts3client/android/ui/ChatText.kt b/android/app/src/main/java/com/ts3client/android/ui/ChatText.kt index dacda10..4f557a9 100644 --- a/android/app/src/main/java/com/ts3client/android/ui/ChatText.kt +++ b/android/app/src/main/java/com/ts3client/android/ui/ChatText.kt @@ -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(" ") { "${BBCode.escape(BBCode.shortAddress(it))}" }, color, onLink) + chatText(links.joinToString(" ") { "${BBCode.escape(linkText(it))}" }, 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 diff --git a/android/app/src/main/java/com/ts3client/android/ui/MyTeamSpeakScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/MyTeamSpeakScreen.kt index 75dbe31..9f42cd6 100644 --- a/android/app/src/main/java/com/ts3client/android/ui/MyTeamSpeakScreen.kt +++ b/android/app/src/main/java/com/ts3client/android/ui/MyTeamSpeakScreen.kt @@ -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() diff --git a/android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt index 1a4ba30..255acc5 100644 --- a/android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt +++ b/android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt @@ -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( @@ -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, diff --git a/ts3-client/core/src/main/java/com/ts3client/myts/ChatAttachment.java b/ts3-client/core/src/main/java/com/ts3client/myts/ChatAttachment.java new file mode 100644 index 0000000..040bbbc --- /dev/null +++ b/ts3-client/core/src/main/java/com/ts3client/myts/ChatAttachment.java @@ -0,0 +1,137 @@ +package com.ts3client.myts; + +import com.ts3client.text.Json; + +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Locale; +import java.util.Map; + +/** + * A file shared in chat the way TeamSpeak 6 shares one with a server that has no chat of + * its own: the file sits in the sender's myTeamSpeak cloud storage, and an ordinary text + * message carries this JSON pointer to it. TeamSpeak 6 shows such a message as the file and + * hides the text; other clients show the text. + * + *

The file lies under the sender's myTeamSpeak ID and the room it was shared in, the + * server's unique identifier, which the message does not carry: the reader supplies it. + * + * @param senderChatId the sender's TeamSpeak chat ID, {@code @:} + * @param description the text TeamSpeak 6 shows with the file; its name unless the sender wrote one + */ +public record ChatAttachment(String fileId, String senderChatId, String fileName, long fileSize, + String description) { + + private static final String TYPE = "ts.file.myts"; + /** The home server TeamSpeak 6 accounts are on; readers use only the ID before it. */ + private static final String CHAT_HOST = "chat-1.tmspk.net"; + /** What {@link #href} addresses start with. */ + public static final String SCHEME = "tsattach:"; + /** What TeamSpeak 6 shows as a picture, by the file name. */ + private static final String[] IMAGE_SUFFIXES = {".png", ".jpeg", ".jpg", ".jpe", ".svg", ".svgz", ".webp", + ".tif", ".tiff", ".gif", ".ico", ".bmp"}; + + /** A file this account shares, under the name it is shown with. */ + public static ChatAttachment of(String fileId, String senderUserId, String fileName, long fileSize) { + return new ChatAttachment(fileId, chatId(senderUserId), fileName, fileSize, fileName); + } + + /** @return the attachment {@code message} points to, or {@code null} for any other message */ + public static ChatAttachment parse(String message) { + if (message == null || !message.startsWith("{") || !message.contains(TYPE)) return null; + Map json = Json.parseObject(message); + if (json == null || !TYPE.equals(json.get("msg_type")) + || !(json.get("file_id") instanceof String fileId) || fileId.isEmpty() + || !(json.get("chat_user_id") instanceof String sender) || sender.isEmpty()) { + return null; + } + String name = json.get("file_name") instanceof String s ? s : ""; + long size = json.get("file_size") instanceof Double d ? d.longValue() : -1; + String body = json.get("body") instanceof String s ? s : ""; + return new ChatAttachment(fileId, sender, name, size, body); + } + + /** The text message to send, written as TeamSpeak 6 writes it. */ + public String toMessage() { + return "{\"msg_type\":" + Json.quote(TYPE) + + ",\"file_id\":" + Json.quote(fileId) + + ",\"chat_user_id\":" + Json.quote(senderChatId) + + ",\"file_name\":" + Json.quote(fileName) + + ",\"file_size\":" + fileSize + + ",\"body\":" + Json.quote(description) + + ",\"v2\":true}"; + } + + /** The myTeamSpeak ID the file lies under: the chat ID's local part. */ + public String senderUserId() { + int colon = senderChatId.indexOf(':'); + int from = senderChatId.startsWith("@") ? 1 : 0; + return senderChatId.substring(from, colon > from ? colon : senderChatId.length()); + } + + public boolean isImage() { + return isImageName(fileName); + } + + /** The description, when the sender wrote one rather than leaving the file name. */ + public String caption() { + return description.isBlank() || description.equals(fileName) ? "" : description; + } + + /** The address chat views link the file with, naming everything needed to fetch it. */ + public String href(String room) { + return SCHEME + encode(room) + "/" + encode(senderUserId()) + "/" + encode(fileId) + "/" + encode(fileName); + } + + /** A file as named by {@link #href}. */ + public record Ref(String room, String owner, String fileId, String fileName) { + + /** @return the file {@code href} names, or {@code null} for any other address */ + public static Ref parse(String href) { + if (href == null || !href.startsWith(SCHEME)) return null; + String[] parts = href.substring(SCHEME.length()).split("/", -1); + if (parts.length != 4) return null; + return new Ref(decode(parts[0]), decode(parts[1]), decode(parts[2]), decode(parts[3])); + } + + public boolean isImage() { + return isImageName(fileName); + } + } + + public static boolean isHref(String href) { + return href != null && href.startsWith(SCHEME); + } + + private static boolean isImageName(String fileName) { + String name = fileName.toLowerCase(Locale.ROOT); + for (String suffix : IMAGE_SUFFIXES) { + if (name.endsWith(suffix)) return true; + } + return false; + } + + /** The chat ID TeamSpeak 6 writes for a myTeamSpeak ID. */ + static String chatId(String userId) { + return "@" + padded(userId) + ":" + CHAT_HOST; + } + + /** + * A myTeamSpeak ID padded as in TeamSpeak 6's chat IDs. Files lie under the ID exactly as + * it was given when they were stored, and TeamSpeak 6 gives it padded. + */ + static String padded(String userId) { + StringBuilder id = new StringBuilder(userId); + while (id.length() % 8 != 0) id.append('='); + return id.toString(); + } + + private static String encode(String s) { + return URLEncoder.encode(s, StandardCharsets.UTF_8).replace("+", "%20"); + } + + private static String decode(String s) { + return URLDecoder.decode(s, StandardCharsets.UTF_8); + } +} diff --git a/ts3-client/core/src/main/java/com/ts3client/myts/ChatAttachments.java b/ts3-client/core/src/main/java/com/ts3client/myts/ChatAttachments.java new file mode 100644 index 0000000..92d49f9 --- /dev/null +++ b/ts3-client/core/src/main/java/com/ts3client/myts/ChatAttachments.java @@ -0,0 +1,67 @@ +package com.ts3client.myts; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Shares files in chat as TeamSpeak 6 does with servers that have no chat of their own: + * into the sender's myTeamSpeak cloud storage, pointed to by a {@link ChatAttachment} + * message. Everything here blocks on the network; call it off the UI thread. + */ +public final class ChatAttachments { + + /** Larger files are not shared: they are sent from memory-starved phones too. */ + public static final long MAX_UPLOAD_BYTES = 100L << 20; + /** Pictures larger than this are offered as files rather than shown, as TeamSpeak 6 does. */ + public static final long MAX_PREVIEW_BYTES = 5L << 20; + + private final MyTsFiles files; + + public ChatAttachments(MyTeamSpeakLogin login) { + this(new MyTsFiles(login)); + } + + ChatAttachments(MyTsFiles files) { + this.files = files; + } + + /** + * Stores a file for sharing in {@code room}, the server's unique identifier. + * + * @return the message to send in its place + */ + public ChatAttachment upload(InputStream data, long size, String fileName, String room) + throws IOException, MyTsException { + if (size > MAX_UPLOAD_BYTES) { + throw new MyTsException("Files over " + (MAX_UPLOAD_BYTES >> 20) + " MB cannot be shared", 0); + } + MyTsFiles.Upload upload = files.requestUpload(room); + MyTsFiles.put(upload.url(), data, size); + return ChatAttachment.of(upload.fileId(), upload.senderUserId(), fileName, size); + } + + /** Fetches a shared file whole. */ + public byte[] download(ChatAttachment.Ref ref, long maxBytes) throws IOException, MyTsException { + return MyTsFiles.get(files.requestDownload(ref.owner(), ref.room(), ref.fileId()), maxBytes); + } + + /** + * Fetches the file an {@link ChatAttachment#href} names, for picture caches. + * + * @return {@code null} when it cannot be had, e.g. while signed out + */ + public byte[] fetchPicture(String href, long maxBytes) throws IOException { + ChatAttachment.Ref ref = ChatAttachment.Ref.parse(href); + if (ref == null) return null; + try { + return download(ref, maxBytes); + } catch (MyTsException e) { + return null; + } + } + + /** Ends the myTeamSpeak session kept for sharing, e.g. on exit or sign-out. */ + public void close() { + files.close(); + } +} diff --git a/ts3-client/core/src/main/java/com/ts3client/myts/MyTeamSpeak.java b/ts3-client/core/src/main/java/com/ts3client/myts/MyTeamSpeak.java index a897dce..e4ef9af 100644 --- a/ts3-client/core/src/main/java/com/ts3client/myts/MyTeamSpeak.java +++ b/ts3-client/core/src/main/java/com/ts3client/myts/MyTeamSpeak.java @@ -58,6 +58,11 @@ public final class MyTeamSpeak { this(MyTsTransport.https(API)); } + /** For the other services, which share the sign-in. */ + MyTsTransport transport() { + return transport; + } + MyTeamSpeak(MyTsTransport transport) { this.transport = transport; } @@ -91,11 +96,29 @@ public final class MyTeamSpeak { /** Signs in, reads the account and signs out again: a few requests, so call it off the UI thread. */ public Account download(Credentials credentials) throws IOException, MyTsException { - String email = credentials.email(); - String loginToken = credentials.loginToken(); - byte[] accountKey = credentials.accountKey(); + Session session = signIn(credentials); + try { + if (session.keyPackage == null) throw new MyTsException("The account has no synchronisation key", 0); + byte[] itemKey; + try { + itemKey = MyTsCrypto.unwrapItemKey(credentials.accountKey(), session.keyPackage); + } catch (GeneralSecurityException e) { + throw new MyTsException("Could not unlock the account's encrypted data", e); + } + return new Account(session.info, pull(session.id, itemKey)); + } finally { + signOut(session.id); + } + } + + /** A signed-in session: the bearer token later requests carry, and who it belongs to. */ + record Session(String id, AccountInfo info, byte[] keyPackage) { + } + + /** Signs in; the caller ends the session with {@link #signOut}. */ + Session signIn(Credentials credentials) throws IOException, MyTsException { ProtobufReader reply = new ProtobufReader(transport.call("authentication", "login", - new ProtobufWriter().string(1, email).string(2, loginToken).toByteArray())); + new ProtobufWriter().string(1, credentials.email()).string(2, credentials.loginToken()).toByteArray())); byte[] keyPackage = null; String session = "", username = "", uuid = ""; @@ -123,18 +146,7 @@ public final class MyTeamSpeak { } } if (error != LOGIN_OK) throw loginError(error); - try { - if (keyPackage == null) throw new MyTsException("The account has no synchronisation key", 0); - byte[] itemKey; - try { - itemKey = MyTsCrypto.unwrapItemKey(accountKey, keyPackage); - } catch (GeneralSecurityException e) { - throw new MyTsException("Could not unlock the account's encrypted data", e); - } - return new Account(AccountInfo.of(username, uuid, userId, createdAt), pull(session, itemKey)); - } finally { - signOut(session); - } + return new Session(session, AccountInfo.of(username, uuid, userId, createdAt), keyPackage); } private List pull(String session, byte[] itemKey) throws IOException, MyTsException { @@ -194,7 +206,7 @@ public final class MyTeamSpeak { } /** Ends the session rather than leave it for the server to expire; nothing to do if that fails. */ - private void signOut(String session) { + void signOut(String session) { if (session.isEmpty()) return; try { transport.call("authentication", "deleteSession", new ProtobufWriter().string(1, session).toByteArray()); diff --git a/ts3-client/core/src/main/java/com/ts3client/myts/MyTeamSpeakLogin.java b/ts3-client/core/src/main/java/com/ts3client/myts/MyTeamSpeakLogin.java index 61fbbaf..83822bd 100644 --- a/ts3-client/core/src/main/java/com/ts3client/myts/MyTeamSpeakLogin.java +++ b/ts3-client/core/src/main/java/com/ts3client/myts/MyTeamSpeakLogin.java @@ -14,7 +14,7 @@ import java.util.Properties; * The myTeamSpeak account this client stays signed in to. Signing in keeps the * {@link MyTeamSpeak.Credentials} in the profile, private to the user, so the account * can be read again later without asking for the password; signing out forgets them. - * Each read signs in afresh, so there is no server session to keep alive. + * Each read signs in afresh; only {@link MyTsFiles} keeps a session. */ public final class MyTeamSpeakLogin { @@ -95,6 +95,15 @@ public final class MyTeamSpeakLogin { } } + /** What signs in, or {@code null} when signed out. */ + synchronized MyTeamSpeak.Credentials credentials() { + return credentials; + } + + MyTeamSpeak service() { + return service; + } + public synchronized void signOut() { credentials = null; username = ""; diff --git a/ts3-client/core/src/main/java/com/ts3client/myts/MyTsFiles.java b/ts3-client/core/src/main/java/com/ts3client/myts/MyTsFiles.java new file mode 100644 index 0000000..a1ea6cb --- /dev/null +++ b/ts3-client/core/src/main/java/com/ts3client/myts/MyTsFiles.java @@ -0,0 +1,183 @@ +package com.ts3client.myts; + +import com.ts3client.proto.ProtobufReader; +import com.ts3client.proto.ProtobufWriter; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; + +/** + * Files kept in myTeamSpeak cloud storage, as TeamSpeak 6 shares them in chat. The service + * hands out signed storage addresses: one to put a new file under this account's ID and a + * room, one to get a file someone put under theirs. Both need a signed-in account; the + * session is kept for later requests and renewed when it runs out. + * + *

The storage addresses are signed for {@code Content-Type: text/plain} whatever the file + * is, both ways; a request without it is refused. + */ +public final class MyTsFiles { + + private static final String SIGNED_TYPE = "text/plain"; + private static final int TIMEOUT_MS = 30_000; + + private static final int ERROR_NOT_ALLOWED = 107; + private static final int ERROR_SESSION_EXPIRED = 109; + + private final MyTeamSpeakLogin login; + private final MyTeamSpeak service; + private MyTeamSpeak.Session session; + private MyTeamSpeak.Credentials sessionCredentials; + + public MyTsFiles(MyTeamSpeakLogin login) { + this(login, login.service()); + } + + MyTsFiles(MyTeamSpeakLogin login, MyTeamSpeak service) { + this.login = login; + this.service = service; + } + + /** Where a new file goes. */ + public record Upload(String fileId, String senderUserId, String url) { + } + + /** Asks for a place to put a new file shared in {@code room}. */ + public Upload requestUpload(String room) throws IOException, MyTsException { + return withSession(s -> { + String userId = ChatAttachment.padded(s.info().userId()); + byte[] request = new ProtobufWriter().string(1, s.id()).string(2, userId).string(3, room).toByteArray(); + FileInfo info = FileInfo.read(service.transport().call("user", "requestUploadFile", request)); + return new Upload(info.fileId, userId, info.url); + }); + } + + /** The address a file someone shared in {@code room} can be fetched from. */ + public String requestDownload(String owner, String room, String fileId) throws IOException, MyTsException { + return withSession(s -> { + byte[] request = new ProtobufWriter().string(1, s.id()).string(2, owner).string(3, room) + .string(4, fileId).toByteArray(); + return FileInfo.read(service.transport().call("user", "requestDownloadFile", request)).url; + }); + } + + /** Stores the file at an address {@link #requestUpload} gave. */ + public static void put(String url, InputStream data, long length) throws IOException { + HttpURLConnection http = open(url); + try { + http.setRequestMethod("PUT"); + http.setDoOutput(true); + http.setFixedLengthStreamingMode(length); + try (OutputStream out = http.getOutputStream()) { + data.transferTo(out); + } + int status = http.getResponseCode(); + if (status / 100 != 2) throw new IOException("The file store answered HTTP " + status); + } finally { + http.disconnect(); + } + } + + /** + * Fetches the file at an address {@link #requestDownload} gave. + * + * @throws IOException also when the file is larger than {@code maxBytes} + */ + public static byte[] get(String url, long maxBytes) throws IOException { + HttpURLConnection http = open(url); + try { + int status = http.getResponseCode(); + if (status != HttpURLConnection.HTTP_OK) throw new IOException("The file store answered HTTP " + status); + if (http.getContentLengthLong() > maxBytes) throw new IOException("The file is too large"); + try (InputStream in = http.getInputStream()) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buf = new byte[16 << 10]; + for (int n; (n = in.read(buf)) > 0; ) { + if (out.size() + n > maxBytes) throw new IOException("The file is too large"); + out.write(buf, 0, n); + } + return out.toByteArray(); + } + } finally { + http.disconnect(); + } + } + + /** Ends the kept session, e.g. on sign-out or exit; the next request signs in again. */ + public void close() { + MyTeamSpeak.Session ended; + synchronized (this) { + ended = session; + session = null; + sessionCredentials = null; + } + if (ended != null) service.signOut(ended.id()); + } + + private interface Request { + T run(MyTeamSpeak.Session session) throws IOException, MyTsException; + } + + private T withSession(Request request) throws IOException, MyTsException { + MyTeamSpeak.Session s = session(); + try { + return request.run(s); + } catch (MyTsException e) { + if (e.code() != ERROR_SESSION_EXPIRED) throw e; + synchronized (this) { + if (session == s) session = null; + } + return request.run(session()); + } + } + + private synchronized MyTeamSpeak.Session session() throws IOException, MyTsException { + MyTeamSpeak.Credentials credentials = login.credentials(); + if (session != null && sessionCredentials == credentials) return session; + if (session != null) service.signOut(session.id()); + session = null; + if (credentials == null) throw new MyTsException("Sign in to myTeamSpeak to share files", 0); + session = service.signIn(credentials); + sessionCredentials = credentials; + if (session.info().userId().isEmpty()) throw new MyTsException("The account has no myTeamSpeak ID", 0); + return session; + } + + private static HttpURLConnection open(String url) throws IOException { + HttpURLConnection http = (HttpURLConnection) new URL(url).openConnection(); + http.setConnectTimeout(TIMEOUT_MS); + http.setReadTimeout(TIMEOUT_MS); + http.setRequestProperty("Content-Type", SIGNED_TYPE); + return http; + } + + /** The service's {@code FileInfo} reply. */ + private record FileInfo(String fileId, String url) { + + static FileInfo read(byte[] reply) throws IOException, MyTsException { + ProtobufReader r = new ProtobufReader(reply); + boolean success = false; + int error = 0; + String fileId = "", url = ""; + while (r.next()) { + switch (r.fieldNumber()) { + case 1 -> success = r.readBool(); + case 2 -> error = (int) r.readVarint(); + case 5 -> fileId = r.readString(); + case 6 -> url = r.readString(); + default -> r.skip(); + } + } + if (success && !url.isEmpty()) return new FileInfo(fileId, url); + String message = switch (error) { + case ERROR_NOT_ALLOWED -> "The file is not available"; + case ERROR_SESSION_EXPIRED -> "The myTeamSpeak session ran out"; + default -> "myTeamSpeak refused the file (error " + error + ")"; + }; + throw new MyTsException(message, error); + } + } +} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/PictureDownloads.java b/ts3-client/core/src/main/java/com/ts3client/net/PictureDownloads.java index 2f39f9c..73684e0 100644 --- a/ts3-client/core/src/main/java/com/ts3client/net/PictureDownloads.java +++ b/ts3-client/core/src/main/java/com/ts3client/net/PictureDownloads.java @@ -12,6 +12,7 @@ import java.nio.file.StandardCopyOption; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; @@ -27,6 +28,12 @@ import java.util.concurrent.Executors; */ public final class PictureDownloads { + /** Fetches the pictures whose addresses use a scheme of its own, rather than from the web. */ + public interface Source { + /** @return the picture, or {@code null} when it cannot be had */ + byte[] fetch(String url, long maxBytes) throws IOException; + } + private static final long MAX_BYTES = 8L << 20; private static final int TIMEOUT_MS = 10_000; private static final long KEEP_MS = 30L * 24 * 60 * 60 * 1000; @@ -38,6 +45,7 @@ public final class PictureDownloads { private final List listeners = new CopyOnWriteArrayList<>(); private final Set pending = ConcurrentHashMap.newKeySet(); private final Set failed = ConcurrentHashMap.newKeySet(); + private final Map sources = new ConcurrentHashMap<>(); private final ExecutorService downloads = Executors.newFixedThreadPool(2, r -> { Thread t = new Thread(r, "picture-download"); t.setDaemon(true); @@ -59,6 +67,17 @@ public final class PictureDownloads { listeners.add(listener); } + /** Fetches addresses starting with {@code scheme} (e.g. {@code "tsattach:"}) from {@code source}. */ + public void addSource(String scheme, Source source) { + sources.put(scheme, source); + } + + /** Asks again for the pictures that could not be had, e.g. once signed in to where they come from. */ + public void retryFailed() { + failed.clear(); + for (Runnable listener : listeners) listener.run(); + } + public void removeListener(Runnable listener) { listeners.remove(listener); } @@ -85,7 +104,8 @@ public final class PictureDownloads { private void download(String url, File file) { try { - byte[] data = fetch(allowed(url)); + Source source = source(url); + byte[] data = source != null ? source.fetch(url, MAX_BYTES) : fetch(allowed(url)); if (data == null) { failed.add(url); } else { @@ -103,6 +123,13 @@ public final class PictureDownloads { for (Runnable listener : listeners) listener.run(); } + private Source source(String url) { + for (Map.Entry e : sources.entrySet()) { + if (url.startsWith(e.getKey())) return e.getValue(); + } + return null; + } + /** The address as it may be fetched here: over https where plain http is not allowed. */ private String allowed(String url) { boolean http = url.regionMatches(true, 0, "http://", 0, 7); diff --git a/ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java b/ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java index 095af00..05852e1 100644 --- a/ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java +++ b/ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java @@ -1757,7 +1757,13 @@ public final class TeamspeakConnection implements TS3Listener { } } - private String serverUniqueId() { + /** + * The server's unique identifier, worked out from its key as TeamSpeak does (a guest is + * never told it); {@code null} before the server has introduced itself. + */ + public String serverUniqueId() { + LocalTeamspeakClientSocket client = this.client; + if (client == null) return null; Uid uid = client.getServerUid(); return uid == null ? null : uid.toBase64(); } diff --git a/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java b/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java index 26b932f..d3aab4a 100644 --- a/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java +++ b/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java @@ -4,6 +4,9 @@ import com.ts3client.audio.AudioBackend; import com.ts3client.config.IdentityEntry; import com.ts3client.config.IdentityStore; import com.ts3client.config.Settings; +import com.ts3client.myts.ChatAttachment; +import com.ts3client.myts.ChatAttachments; +import com.ts3client.myts.MyTsException; import com.ts3client.contacts.ContactStore; import com.ts3client.net.ChannelNode; import com.ts3client.net.ClientEntry; @@ -14,6 +17,7 @@ import com.ts3client.recording.VoiceRecorder; import com.ts3client.sound.SoundNotifier; import java.io.IOException; +import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDateTime; @@ -453,6 +457,40 @@ public final class ServerSession { } } + /** + * Shares a file in a chat as TeamSpeak 6 does: stores it in this user's myTeamSpeak + * cloud storage, then sends the message pointing to it. Runs in the background; a failure + * is reported through {@link Listener#onSystemMessage}. + * + * @param data read and closed in the background + */ + public void sendAttachment(ConnectionListener.ChatScope scope, int clientId, ChatAttachments attachments, + InputStream data, long size, String fileName) { + String room = conn.serverUniqueId(); + if (!conn.isConnected() || room == null) { + closeQuietly(data); + listener.onSystemMessage("Not connected."); + return; + } + Thread t = new Thread(() -> { + try (InputStream in = data) { + ChatAttachment attachment = attachments.upload(in, size, fileName, room); + sendChat(scope, clientId, attachment.toMessage()); + } catch (IOException | MyTsException e) { + listener.onSystemMessage("Could not share " + fileName + ": " + e.getMessage()); + } + }, "ts3-attachment-upload"); + t.setDaemon(true); + t.start(); + } + + private static void closeQuietly(InputStream in) { + try { + in.close(); + } catch (IOException ignored) { + } + } + private String peerName(int clientId) { ClientEntry c = conn.getModel().getClient(clientId); return c != null ? conn.displayName(c) : "Client " + clientId; diff --git a/ts3-client/core/src/main/java/com/ts3client/text/ChatHtml.java b/ts3-client/core/src/main/java/com/ts3client/text/ChatHtml.java index d5362ed..0eece5a 100644 --- a/ts3-client/core/src/main/java/com/ts3client/text/ChatHtml.java +++ b/ts3-client/core/src/main/java/com/ts3client/text/ChatHtml.java @@ -1,7 +1,13 @@ package com.ts3client.text; +import com.ts3client.myts.ChatAttachment; +import com.ts3client.myts.ChatAttachments; + import java.time.LocalTime; import java.time.format.DateTimeFormatter; +import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * Builds the entries a chat shows, one {@code

} of HTML each, the form TeamSpeak's own @@ -17,7 +23,13 @@ public final class ChatHtml { /** A sender that cannot be linked to. */ public static final String NAME_CLASS = "name"; + /** A file shared in chat; its link's address is a {@link ChatAttachment#href}. */ + public static final String ATTACHMENT_CLASS = "attachment"; + private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("HH:mm:ss"); + /** The text of a message in TeamSpeak's HTML log. */ + private static final Pattern LOG_TEXT = Pattern.compile("()(.*?)()", + Pattern.DOTALL); private ChatHtml() { } @@ -28,13 +40,48 @@ public final class ChatHtml { * @param text the message as sent, in BBCode */ public static String message(int fromId, String fromUniqueId, String from, String text) { + return message(fromId, fromUniqueId, from, text, ""); + } + + /** + * A chat message, showing a file shared in it as the file. + * + * @param room the unique identifier of the server the chat is on, where shared files lie + */ + public static String message(int fromId, String fromUniqueId, String from, String text, String room) { String name = BBCode.escape(from); String sender = fromId > 0 ? "" + name + "" : span(NAME_CLASS, name); - return div(span(MUTED_CLASS, stamp()) + sender + ": " + BBCode.toHtml(text)); + ChatAttachment attachment = ChatAttachment.parse(text); + String body = attachment != null ? attachment(attachment, room) : BBCode.toHtml(text); + return div(span(MUTED_CLASS, stamp()) + sender + ": " + body); + } + + /** + * A shared file: a picture shown as one, anything else as a link with its size. Without + * the room to fetch it from, only its name. + */ + public static String attachment(ChatAttachment attachment, String room) { + String name = BBCode.escape(attachment.fileName().isBlank() ? "file" : attachment.fileName()); + String caption = attachment.caption().isEmpty() ? "" : "
" + BBCode.escape(attachment.caption()); + if (room == null || room.isBlank()) return span(ATTACHMENT_CLASS, name) + caption; + String href = BBCode.escape(attachment.href(room)); + String open = ""; + if (attachment.isImage() && attachment.fileSize() <= ChatAttachments.MAX_PREVIEW_BYTES) { + return "
" + open + "
" + caption; + } + String size = attachment.fileSize() >= 0 ? " " + span(MUTED_CLASS, "(" + size(attachment.fileSize()) + ")") : ""; + return open + name + "" + size + caption; + } + + /** A message as plain text, e.g. for a notification: a shared file as its name. */ + public static String plainMessage(String text) { + ChatAttachment attachment = ChatAttachment.parse(text); + if (attachment == null) return BBCode.toPlain(text); + return attachment.caption().isEmpty() ? attachment.fileName() : attachment.caption(); } /** One of the chat's own notices: connection progress, errors, pokes. */ @@ -57,14 +104,40 @@ public final class ChatHtml { * @return the entry, or empty for one that shows nothing */ public static String logEntry(String html) { + return logEntry(html, ""); + } + + /** + * {@link #logEntry(String)}, showing a file shared in the message as the file. + * + * @param room the unique identifier of the server the log is of + */ + public static String logEntry(String html, String room) { if (html == null || html.isBlank()) return ""; String normalized = html .replaceAll("(?i)]*>", "") .replaceFirst("(?i)^\\s*\\s*$", "
"); + normalized = withAttachment(normalized, room); return normalized.startsWith(" parseObject(String text) { + if (text == null) return null; + try { + Json json = new Json(text); + json.skipSpace(); + if (json.peek() != '{') return null; + @SuppressWarnings("unchecked") + Map object = (Map) json.value(); + json.skipSpace(); + return json.pos == text.length() ? object : null; + } catch (IllegalArgumentException | IndexOutOfBoundsException malformed) { + return null; + } + } + + /** {@code s} as a JSON string literal. */ + public static String quote(String s) { + StringBuilder out = new StringBuilder(s.length() + 2).append('"'); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + switch (c) { + case '"' -> out.append("\\\""); + case '\\' -> out.append("\\\\"); + case '\n' -> out.append("\\n"); + case '\r' -> out.append("\\r"); + case '\t' -> out.append("\\t"); + default -> { + if (c < 0x20) out.append(String.format("\\u%04x", (int) c)); + else out.append(c); + } + } + } + return out.append('"').toString(); + } + + private Object value() { + skipSpace(); + char c = peek(); + return switch (c) { + case '{' -> object(); + case '[' -> array(); + case '"' -> string(); + case 't' -> literal("true", Boolean.TRUE); + case 'f' -> literal("false", Boolean.FALSE); + case 'n' -> literal("null", null); + default -> number(); + }; + } + + private Map object() { + Map object = new LinkedHashMap<>(); + pos++; + skipSpace(); + if (peek() == '}') { + pos++; + return object; + } + while (true) { + skipSpace(); + String key = string(); + skipSpace(); + expect(':'); + object.put(key, value()); + skipSpace(); + if (peek() == ',') { + pos++; + continue; + } + expect('}'); + return object; + } + } + + private List array() { + List array = new ArrayList<>(); + pos++; + skipSpace(); + if (peek() == ']') { + pos++; + return array; + } + while (true) { + array.add(value()); + skipSpace(); + if (peek() == ',') { + pos++; + continue; + } + expect(']'); + return array; + } + } + + private String string() { + expect('"'); + StringBuilder out = new StringBuilder(); + while (true) { + char c = src.charAt(pos++); + if (c == '"') return out.toString(); + if (c != '\\') { + out.append(c); + continue; + } + char e = src.charAt(pos++); + switch (e) { + case 'b' -> out.append('\b'); + case 'f' -> out.append('\f'); + case 'n' -> out.append('\n'); + case 'r' -> out.append('\r'); + case 't' -> out.append('\t'); + case 'u' -> { + out.append((char) Integer.parseInt(src.substring(pos, pos + 4), 16)); + pos += 4; + } + default -> out.append(e); + } + } + } + + private Double number() { + int start = pos; + while (pos < src.length() && "+-0123456789.eE".indexOf(src.charAt(pos)) >= 0) pos++; + if (start == pos) throw new IllegalArgumentException("Unexpected " + peek()); + return Double.valueOf(src.substring(start, pos)); + } + + private Object literal(String word, Object value) { + if (!src.startsWith(word, pos)) throw new IllegalArgumentException("Expected " + word); + pos += word.length(); + return value; + } + + private void expect(char c) { + if (peek() != c) throw new IllegalArgumentException("Expected " + c); + pos++; + } + + private char peek() { + return src.charAt(pos); + } + + private void skipSpace() { + while (pos < src.length() && Character.isWhitespace(src.charAt(pos))) pos++; + } +} diff --git a/ts3-client/core/src/test/java/com/ts3client/myts/ChatAttachmentTest.java b/ts3-client/core/src/test/java/com/ts3client/myts/ChatAttachmentTest.java new file mode 100644 index 0000000..f862e9b --- /dev/null +++ b/ts3-client/core/src/test/java/com/ts3client/myts/ChatAttachmentTest.java @@ -0,0 +1,69 @@ +package com.ts3client.myts; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ChatAttachmentTest { + + /** As TeamSpeak 6 sends it: JSON.stringify of its object, keys in this order. */ + private static final String TS6_MESSAGE = "{\"msg_type\":\"ts.file.myts\",\"file_id\":\"YWx1aW1hZWJp\"," + + "\"chat_user_id\":\"@agl7x5qxz7h7pqrfz7xyzedmlkbpstkbbkxw7gxltefsa3p7eexri===:chat-1.tmspk.net\"," + + "\"file_name\":\"cat picture.PNG\",\"file_size\":532,\"body\":\"cat picture.PNG\",\"v2\":true}"; + + @Test + void readsTheMessageTeamSpeak6Sends() { + ChatAttachment a = ChatAttachment.parse(TS6_MESSAGE); + assertEquals("YWx1aW1hZWJp", a.fileId()); + assertEquals("agl7x5qxz7h7pqrfz7xyzedmlkbpstkbbkxw7gxltefsa3p7eexri===", a.senderUserId()); + assertEquals("cat picture.PNG", a.fileName()); + assertEquals(532, a.fileSize()); + assertTrue(a.isImage()); + assertEquals("", a.caption()); + } + + @Test + void writesWhatItReads() { + assertEquals(TS6_MESSAGE, ChatAttachment.parse(TS6_MESSAGE).toMessage()); + } + + @Test + void namesItsSenderAsTeamSpeak6Does() { + ChatAttachment a = ChatAttachment.of("id", "aeqlaxceldn5xjqkgnzdd3bjsxety4k46mzr7v5sd4xwtpyv5yfm2", "a.txt", 3); + assertEquals("@aeqlaxceldn5xjqkgnzdd3bjsxety4k46mzr7v5sd4xwtpyv5yfm2===:chat-1.tmspk.net", a.senderChatId()); + assertFalse(a.isImage()); + ChatAttachment back = ChatAttachment.parse(a.toMessage()); + assertEquals(a, back); + } + + @Test + void keepsQuotesAndBracketsInNames() { + ChatAttachment a = new ChatAttachment("f", "@u:h", "say \"hi\" [b]x[/b].gif", 1, "line\nbreak"); + assertEquals(a, ChatAttachment.parse(a.toMessage())); + assertEquals("line\nbreak", a.caption()); + } + + @Test + void ignoresOtherMessages() { + assertNull(ChatAttachment.parse("hello")); + assertNull(ChatAttachment.parse("{\"msg_type\":\"ts.file.myts\"}")); + assertNull(ChatAttachment.parse("{\"msg_type\":\"other\",\"file_id\":\"a\",\"chat_user_id\":\"@b:c\"} ts.file.myts")); + assertNull(ChatAttachment.parse("{\"msg_type\":\"ts.file.myts\", broken")); + } + + @Test + void hrefNamesEverythingNeededToFetchIt() { + ChatAttachment a = ChatAttachment.parse(TS6_MESSAGE); + String href = a.href("+Tyg2JtxE8vRNZp/JiUBnmBh0MY="); + assertTrue(ChatAttachment.isHref(href)); + ChatAttachment.Ref ref = ChatAttachment.Ref.parse(href); + assertEquals("+Tyg2JtxE8vRNZp/JiUBnmBh0MY=", ref.room()); + assertEquals(a.senderUserId(), ref.owner()); + assertEquals("YWx1aW1hZWJp", ref.fileId()); + assertEquals("cat picture.PNG", ref.fileName()); + assertFalse(href.contains(" ")); + } +} diff --git a/ts3-client/core/src/test/java/com/ts3client/myts/MyTsFilesTest.java b/ts3-client/core/src/test/java/com/ts3client/myts/MyTsFilesTest.java new file mode 100644 index 0000000..b81d9ee --- /dev/null +++ b/ts3-client/core/src/test/java/com/ts3client/myts/MyTsFilesTest.java @@ -0,0 +1,88 @@ +package com.ts3client.myts; + +import com.ts3client.proto.ProtobufReader; +import com.ts3client.proto.ProtobufWriter; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class MyTsFilesTest { + + /** The account replay, plus the file service: hands out made-up addresses. */ + static final class FileServer implements MyTsTransport { + final MyTeamSpeakTest.ReplayServer accounts = new MyTeamSpeakTest.ReplayServer(); + final List requests = new ArrayList<>(); + int expireNext; + + @Override + public byte[] call(String endpoint, String method, byte[] request) throws IOException, MyTsException { + if (!endpoint.equals("user")) return accounts.call(endpoint, method, request); + accounts.calls.add(endpoint + "/" + method); + if (expireNext > 0) { + expireNext--; + return new ProtobufWriter().varint(2, 109).toByteArray(); + } + ProtobufReader r = new ProtobufReader(request); + StringBuilder fields = new StringBuilder(method); + while (r.next()) fields.append(' ').append(r.fieldNumber()).append('=').append(r.readString()); + requests.add(fields.toString()); + return new ProtobufWriter().varint(1, 1).string(5, "file1").string(6, "https://store/" + method) + .toByteArray(); + } + } + + private static MyTsFiles signedIn(File dir, FileServer server) throws Exception { + MyTeamSpeakLogin login = new MyTeamSpeakLogin(new File(dir, "myts.properties"), new MyTeamSpeak(server)); + login.signIn(MyTsCryptoTest.EMAIL, MyTsCryptoTest.PASSWORD); + server.accounts.calls.clear(); + return new MyTsFiles(login, new MyTeamSpeak(server)); + } + + @Test + void asksUnderTheAccountsIdAndKeepsTheSession(@TempDir File dir) throws Exception { + FileServer server = new FileServer(); + MyTsFiles files = signedIn(dir, server); + + MyTsFiles.Upload upload = files.requestUpload("room="); + assertEquals("file1", upload.fileId()); + assertEquals("aeqlaxcldiwt4t2qmfzihfffw3d5r2pqaejcgncfkztxrcm2vo6m2===", upload.senderUserId()); + assertEquals("https://store/requestDownloadFile", files.requestDownload("owner", "room=", "file9")); + + String session = "00000000-1111-2222-3333-444444444444"; + assertEquals(List.of("requestUploadFile 1=" + session + " 2=" + upload.senderUserId() + " 3=room=", + "requestDownloadFile 1=" + session + " 2=owner 3=room= 4=file9"), server.requests); + assertEquals(List.of("authentication/login", "user/requestUploadFile", "user/requestDownloadFile"), + server.accounts.calls); + + files.close(); + assertEquals("authentication/deleteSession", server.accounts.calls.get(3)); + } + + @Test + void signsInAgainWhenTheSessionRanOut(@TempDir File dir) throws Exception { + FileServer server = new FileServer(); + MyTsFiles files = signedIn(dir, server); + files.requestUpload("room"); + server.expireNext = 1; + server.accounts.calls.clear(); + + files.requestUpload("room"); + assertEquals(List.of("user/requestUploadFile", "authentication/login", "user/requestUploadFile"), + server.accounts.calls); + } + + @Test + void needsASignIn(@TempDir File dir) { + FileServer server = new FileServer(); + MyTeamSpeakLogin login = new MyTeamSpeakLogin(new File(dir, "myts.properties"), new MyTeamSpeak(server)); + MyTsFiles files = new MyTsFiles(login, new MyTeamSpeak(server)); + assertThrows(MyTsException.class, () -> files.requestUpload("room")); + } +} diff --git a/ts3-client/core/src/test/java/com/ts3client/text/ChatHtmlAttachmentTest.java b/ts3-client/core/src/test/java/com/ts3client/text/ChatHtmlAttachmentTest.java new file mode 100644 index 0000000..5aab69d --- /dev/null +++ b/ts3-client/core/src/test/java/com/ts3client/text/ChatHtmlAttachmentTest.java @@ -0,0 +1,58 @@ +package com.ts3client.text; + +import com.ts3client.chatlog.ChatLogScope; +import com.ts3client.chatlog.ChatLogStore; +import com.ts3client.myts.ChatAttachment; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Path; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ChatHtmlAttachmentTest { + + private static final String ROOM = "+Tyg2JtxE8vRNZp+JiUBnmBh0MY="; + private static final ChatAttachment PICTURE = ChatAttachment.of("f1", "abc", "cat.png", 532); + private static final ChatAttachment FILE = ChatAttachment.of("f2", "abc", "notes <1>.txt", 3 << 20); + + @Test + void showsAPictureAsOne() { + String html = ChatHtml.message(5, "uid", "alice", PICTURE.toMessage(), ROOM); + assertTrue(html.contains(""), html); + assertFalse(html.contains("msg_type"), html); + } + + @Test + void showsAnyOtherFileAsALinkWithItsSize() { + String html = ChatHtml.message(5, "uid", "alice", FILE.toMessage(), ROOM); + assertTrue(html.contains("href=\"" + FILE.href(ROOM) + "\">notes <1>.txt"), html); + assertTrue(html.contains("(3.0 MB)"), html); + } + + @Test + void namesTheFileWhereItCannotBeFetched() { + String html = ChatHtml.message(5, "uid", "alice", PICTURE.toMessage()); + assertFalse(html.contains(" history = logs.channelHtmlHistory(); + String html = ChatHtml.logEntry(history.get(history.size() - 1), ROOM); + assertTrue(html.contains(""), html); + assertFalse(html.contains("msg_type"), html); + } + + @Test + void previewsAFileByItsName() { + assertEquals("cat.png", ChatHtml.plainMessage(PICTURE.toMessage())); + assertEquals("hi", ChatHtml.plainMessage("[b]hi[/b]")); + } +} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/AttachmentTransferHandler.java b/ts3-client/swing/src/main/java/com/ts3client/ui/AttachmentTransferHandler.java new file mode 100644 index 0000000..bc462ee --- /dev/null +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/AttachmentTransferHandler.java @@ -0,0 +1,128 @@ +package com.ts3client.ui; + +import javax.swing.JComponent; +import javax.swing.TransferHandler; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.Transferable; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +/** + * Takes files and pictures dropped or pasted onto a chat view as files to share, and leaves + * everything else (text, client links) to the component's own handler. + */ +final class AttachmentTransferHandler extends TransferHandler { + + interface Sink { + /** @return whether the files were taken */ + boolean files(List files); + + boolean image(BufferedImage image); + } + + /** How file managers that Java does not translate hand over files. */ + private static final DataFlavor URI_LIST = flavor("text/uri-list;class=java.lang.String"); + + private final TransferHandler delegate; + private final Sink sink; + + AttachmentTransferHandler(TransferHandler delegate, Sink sink) { + this.delegate = delegate; + this.sink = sink; + } + + @Override + public boolean canImport(TransferSupport support) { + if (isFiles(support.getDataFlavors()) || isPicture(support.getDataFlavors())) return true; + return delegate != null && delegate.canImport(support); + } + + @Override + public boolean importData(TransferSupport support) { + DataFlavor[] flavors = support.getDataFlavors(); + Transferable t = support.getTransferable(); + try { + if (isFiles(flavors)) { + List files = files(t); + if (!files.isEmpty()) return sink.files(files); + } else if (isPicture(flavors)) { + return sink.image(buffered((Image) t.getTransferData(DataFlavor.imageFlavor))); + } + } catch (UnsupportedFlavorException | IOException e) { + return false; + } + return delegate != null && delegate.importData(support); + } + + @Override + public int getSourceActions(JComponent c) { + return delegate == null ? NONE : delegate.getSourceActions(c); + } + + @Override + public void exportToClipboard(JComponent comp, Clipboard clip, int action) { + if (delegate != null) delegate.exportToClipboard(comp, clip, action); + } + + private static boolean isFiles(DataFlavor[] flavors) { + for (DataFlavor f : flavors) { + if (f.equals(DataFlavor.javaFileListFlavor) || f.equals(URI_LIST)) return true; + } + return false; + } + + /** A picture alone: one that comes with text is text that also offers a rendering of itself. */ + private static boolean isPicture(DataFlavor[] flavors) { + boolean image = false; + for (DataFlavor f : flavors) { + if (f.equals(DataFlavor.imageFlavor)) image = true; + else if (f.equals(DataFlavor.stringFlavor)) return false; + } + return image; + } + + @SuppressWarnings("unchecked") + private static List files(Transferable t) throws UnsupportedFlavorException, IOException { + if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { + return new ArrayList<>((List) t.getTransferData(DataFlavor.javaFileListFlavor)); + } + List files = new ArrayList<>(); + for (String line : ((String) t.getTransferData(URI_LIST)).split("\r?\n")) { + line = line.trim(); + if (line.isEmpty() || line.startsWith("#")) continue; + try { + URI uri = URI.create(line); + if (!"file".equals(uri.getScheme())) return List.of(); + files.add(new File(uri)); + } catch (IllegalArgumentException e) { + return List.of(); + } + } + return files; + } + + private static BufferedImage buffered(Image image) { + if (image instanceof BufferedImage b) return b; + BufferedImage b = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); + Graphics2D g = b.createGraphics(); + g.drawImage(image, 0, 0, null); + g.dispose(); + return b; + } + + private static DataFlavor flavor(String mime) { + try { + return new DataFlavor(mime); + } catch (ClassNotFoundException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ChatAttachmentActions.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ChatAttachmentActions.java new file mode 100644 index 0000000..d29e786 --- /dev/null +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/ChatAttachmentActions.java @@ -0,0 +1,145 @@ +package com.ts3client.ui; + +import com.ts3client.myts.ChatAttachment; +import com.ts3client.myts.ChatAttachments; +import com.ts3client.myts.MyTsException; +import com.ts3client.net.ConnectionListener.ChatScope; +import com.ts3client.net.PictureDownloads; +import com.ts3client.session.ServerSession; + +import javax.imageio.ImageIO; +import javax.swing.JFileChooser; +import javax.swing.SwingUtilities; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.List; +import java.util.function.Function; + +/** + * Shares files in one server's chats through myTeamSpeak, and shows and saves the files + * shared there. Failures land in the chat as system lines. + */ +final class ChatAttachmentActions implements ChatPanel.AttachmentHandler { + + private static final String SIGN_IN = "Sign in to myTeamSpeak to share files"; + private static final String PASTED_NAME = "image.png"; + + /** Where files were last shared from or saved to, for every server alike. */ + private static File lastDirectory; + + private final MainFrame host; + private final ServerSession session; + private final ChatPanel chat; + private final PictureDownloads pictures; + private final Function scopes; + + ChatAttachmentActions(MainFrame host, ServerSession session, ChatPanel chat, PictureDownloads pictures, + Function scopes) { + this.host = host; + this.session = session; + this.chat = chat; + this.pictures = pictures; + this.scopes = scopes; + } + + @Override + public void choose(ChatPanel.Target target, int clientId) { + if (!signedIn()) return; + JFileChooser chooser = new JFileChooser(lastDirectory); + chooser.setMultiSelectionEnabled(true); + chooser.setDialogTitle("Share files"); + if (chooser.showOpenDialog(host) != JFileChooser.APPROVE_OPTION) return; + File[] files = chooser.getSelectedFiles(); + if (files.length > 0) lastDirectory = files[0].getParentFile(); + share(target, clientId, List.of(files)); + } + + @Override + public void share(ChatPanel.Target target, int clientId, List files) { + if (!signedIn()) return; + for (File file : files) { + if (!file.isFile()) continue; + if (file.length() > ChatAttachments.MAX_UPLOAD_BYTES) { + chat.appendSystem(file.getName() + " is over " + (ChatAttachments.MAX_UPLOAD_BYTES >> 20) + " MB."); + continue; + } + try { + session.sendAttachment(scopes.apply(target), clientId, host.attachments(), + new FileInputStream(file), file.length(), file.getName()); + } catch (IOException e) { + chat.appendSystem("Could not share " + file.getName() + ": " + e.getMessage()); + } + } + } + + @Override + public void share(ChatPanel.Target target, int clientId, BufferedImage image) { + if (!signedIn()) return; + ByteArrayOutputStream png = new ByteArrayOutputStream(); + try { + ImageIO.write(image, "png", png); + } catch (IOException e) { + chat.appendSystem("Could not share the picture: " + e.getMessage()); + return; + } + session.sendAttachment(scopes.apply(target), clientId, host.attachments(), + new ByteArrayInputStream(png.toByteArray()), png.size(), PASTED_NAME); + } + + @Override + public void open(String href, boolean picture) { + ChatAttachment.Ref ref = ChatAttachment.Ref.parse(href); + if (ref == null) return; + File shown = picture ? pictures.get(href) : null; + BufferedImage image = shown == null ? null : read(shown); + if (image != null) { + new PictureViewer(host, ref.fileName(), image, () -> save(ref, shown)).setVisible(true); + } else { + save(ref, null); + } + } + + /** Asks where to save the file, then copies it there: from {@code have} when given, else fetched. */ + private void save(ChatAttachment.Ref ref, File have) { + if (have == null && !signedIn()) return; + JFileChooser chooser = new JFileChooser(lastDirectory); + chooser.setDialogTitle("Save " + ref.fileName()); + chooser.setSelectedFile(new File(lastDirectory, ref.fileName())); + if (chooser.showSaveDialog(host) != JFileChooser.APPROVE_OPTION) return; + File target = chooser.getSelectedFile(); + lastDirectory = target.getParentFile(); + ChatAttachments attachments = host.attachments(); + Thread.ofVirtual().name("chat-attachment-save").start(() -> { + try { + if (have != null) { + Files.copy(have.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING); + } else { + Files.write(target.toPath(), attachments.download(ref, ChatAttachments.MAX_UPLOAD_BYTES)); + } + } catch (IOException | MyTsException e) { + SwingUtilities.invokeLater(() -> + chat.appendSystem("Could not save " + ref.fileName() + ": " + e.getMessage())); + } + }); + } + + private boolean signedIn() { + if (host.canShareFiles()) return true; + chat.appendSystem(SIGN_IN + "."); + return false; + } + + private static BufferedImage read(File file) { + try { + return ImageIO.read(file); + } catch (IOException e) { + return null; + } + } +} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ChatLogsPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ChatLogsPanel.java index a4bd5ce..f55adc0 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ChatLogsPanel.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/ChatLogsPanel.java @@ -24,7 +24,7 @@ final class ChatLogsPanel extends FormPanel { private final JCheckBox enabled = new JCheckBox("Keep chat logs"); private final JTextField folder = new JTextField(18); private final JButton browse = new JButton("Browse…"); - private final JCheckBox pictures = new JCheckBox("Show pictures in descriptions"); + private final JCheckBox pictures = new JCheckBox("Show pictures in descriptions and chat"); ChatLogsPanel(Settings settings) { this.settings = settings; diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ChatPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ChatPanel.java index dde5d7e..5e21931 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ChatPanel.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/ChatPanel.java @@ -2,6 +2,9 @@ package com.ts3client.ui; import com.formdev.flatlaf.util.ScaledEmptyBorder; import com.formdev.flatlaf.util.UIScale; +import com.ts3client.config.Settings; +import com.ts3client.myts.ChatAttachment; +import com.ts3client.net.PictureDownloads; import com.ts3client.text.BBCode; import com.ts3client.text.ChatHtml; import com.ts3client.text.HtmlText; @@ -11,9 +14,12 @@ import com.ts3client.text.TsLink; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JLabel; import javax.swing.JPanel; +import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextField; @@ -21,6 +27,9 @@ import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.event.HyperlinkEvent; import javax.swing.text.BadLocationException; +import javax.swing.text.Element; +import javax.swing.text.StyleConstants; +import javax.swing.text.html.HTML; import javax.swing.text.html.HTMLDocument; import java.awt.BorderLayout; import java.awt.Component; @@ -30,15 +39,20 @@ import java.awt.FlowLayout; import java.awt.Insets; import java.awt.Point; import java.awt.event.ActionEvent; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; +import java.awt.image.BufferedImage; +import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.function.Supplier; /** * Chat area with one tab per conversation (server, current channel and one per @@ -66,11 +80,32 @@ public final class ChatPanel extends JPanel { void onOfflineMessagesLink(); } + /** Files shared in the chats, which the host sends, fetches and shows. */ + public interface AttachmentHandler { + /** Asks which files to share in the conversation. */ + void choose(Target target, int clientId); + + void share(Target target, int clientId, List files); + + void share(Target target, int clientId, BufferedImage image); + + /** + * A shared file was clicked. + * + * @param picture whether the picture shown for it was, rather than its name + */ + void open(String href, boolean picture); + } + private final JTabbedPane tabs = new JTabbedPane(JTabbedPane.BOTTOM); private final JTextField input = new JTextField(); /** Tab strip height, so a tab with no icon still lines up with the others. */ private static final int HEADER_HEIGHT = 20; + /** The largest a shared picture is drawn in the log. */ + private static final int PICTURE_WIDTH = 320; + private static final int PICTURE_HEIGHT = 240; + private static final int PICTURE_WIDTH_STEP = 40; private static final String NO_SERVER = "Server"; private static final String NO_CHANNEL = "Channel"; @@ -100,11 +135,25 @@ public final class ChatPanel extends JPanel { private SendHandler sendHandler; private LinkHandler linkHandler; + private AttachmentHandler attachmentHandler; private final TextZoom zoom; + private final PictureDownloads downloads; + private final DescriptionPictures pictures; + /** The server's unique identifier, which shared files are kept under; null while unknown. */ + private final Supplier room; + private final JButton attach = new JButton(Icons.of("UPLOAD")); + private boolean inputEnabled; + private boolean sharingAvailable; + private final Runnable onPicture = () -> SwingUtilities.invokeLater(() -> { + for (Tab t : allTabs()) t.picturesChanged(); + }); - public ChatPanel(TextZoom zoom) { + public ChatPanel(TextZoom zoom, Settings settings, PictureDownloads downloads, Supplier room) { super(new BorderLayout()); this.zoom = zoom; + this.downloads = downloads; + this.pictures = new DescriptionPictures(downloads, settings); + this.room = room; tabs.setFont(Theme.uiFont()); tabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); @@ -139,9 +188,19 @@ public final class ChatPanel extends JPanel { JPanel bottom = new JPanel(new BorderLayout(UIScale.scale(4), 0)); bottom.setBorder(new ScaledEmptyBorder(4, 0, 0, 0)); bottom.add(input, BorderLayout.CENTER); + bottom.add(attach, BorderLayout.EAST); add(bottom, BorderLayout.SOUTH); input.addActionListener(e -> fireSend()); + input.setTransferHandler(attachmentTransfer(input)); + attach.putClientProperty("JButton.buttonType", "toolBarButton"); + attach.setFocusable(false); + attach.addActionListener(e -> { + Tab tab = selectedTab(); + if (attachmentHandler != null && tab != null && tab.target != null) { + attachmentHandler.choose(tab.target, tab.clientId); + } + }); setInputEnabled(false); } @@ -154,6 +213,30 @@ public final class ChatPanel extends JPanel { this.linkHandler = h; } + public void setAttachmentHandler(AttachmentHandler h) { + this.attachmentHandler = h; + } + + /** Whether files can be shared at all, i.e. signed in to myTeamSpeak. */ + public void setSharingAvailable(boolean available) { + edt(() -> { + sharingAvailable = available; + updateAttach(); + }); + } + + @Override + public void addNotify() { + super.addNotify(); + downloads.addListener(onPicture); + } + + @Override + public void removeNotify() { + downloads.removeListener(onPicture); + super.removeNotify(); + } + /** Opens the find bar on the selected conversation. */ public void openFind() { edt(search::open); @@ -180,6 +263,34 @@ public final class ChatPanel extends JPanel { public void setInputEnabled(boolean enabled) { input.setEnabled(enabled); + inputEnabled = enabled; + updateAttach(); + } + + private void updateAttach() { + attach.setEnabled(inputEnabled && sharingAvailable); + attach.setToolTipText(sharingAvailable ? "Share file" : "Sign in to myTeamSpeak to share files"); + } + + /** Takes dropped and pasted files and pictures as files to share, leaving the rest to {@code c}'s own handling. */ + private AttachmentTransferHandler attachmentTransfer(JComponent c) { + return new AttachmentTransferHandler(c.getTransferHandler(), new AttachmentTransferHandler.Sink() { + @Override + public boolean files(List files) { + Tab tab = selectedTab(); + if (attachmentHandler == null || tab == null || tab.target == null) return false; + attachmentHandler.share(tab.target, tab.clientId, files); + return true; + } + + @Override + public boolean image(BufferedImage image) { + Tab tab = selectedTab(); + if (attachmentHandler == null || tab == null || tab.target == null) return false; + attachmentHandler.share(tab.target, tab.clientId, image); + return true; + } + }); } /** Opens (or focuses) the private chat with {@code clientId}. */ @@ -385,6 +496,11 @@ public final class ChatPanel extends JPanel { return all; } + private String room() { + String id = room.get(); + return id == null ? "" : id; + } + private void edt(Runnable r) { if (SwingUtilities.isEventDispatchThread()) r.run(); else SwingUtilities.invokeLater(r); @@ -409,6 +525,10 @@ public final class ChatPanel extends JPanel { private final List entries = new ArrayList<>(); /** Only messages matching this are on screen; {@code null} shows all. */ private TextQuery filter; + /** The shared pictures the entries show, and how they stood when last drawn. */ + private final List pictureUrls = new ArrayList<>(); + private String pictureState = ""; + private int renderedPictureWidth; Tab(Target target, int clientId, String title, Icon icon) { this(target, clientId, "", title, icon, null, null); @@ -436,20 +556,35 @@ public final class ChatPanel extends JPanel { log.setText("
"); log.addHyperlinkListener(e -> { if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) return; - onLink(e.getDescription()); + onLink(e.getDescription(), isPicture(e.getSourceElement())); }); + log.setTransferHandler(attachmentTransfer(log)); scroll = new JScrollPane(log); HtmlStyles.fillViewport(log); scroll.setBorder(BorderFactory.createEmptyBorder()); + scroll.getViewport().addComponentListener(new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent e) { + if (!pictureUrls.isEmpty() && pictureWidth() != renderedPictureWidth) keepingScroll(); + } + }); + } + + private static boolean isPicture(Element element) { + return element != null && element.getAttributes().getAttribute(StyleConstants.NameAttribute) == HTML.Tag.IMG; } void setClientUniqueId(String uniqueId) { if (uniqueId != null && !uniqueId.isBlank()) clientUniqueId = uniqueId; } - private void onLink(String href) { + private void onLink(String href, boolean picture) { if (href == null) return; + if (ChatAttachment.isHref(href)) { + if (attachmentHandler != null) attachmentHandler.open(href, picture); + return; + } if (TsLink.isOfflineMessages(href)) { if (linkHandler != null) linkHandler.onOfflineMessagesLink(); return; @@ -521,13 +656,16 @@ public final class ChatPanel extends JPanel { void appendMessage(int fromId, String fromUniqueId, String from, String text) { append(ChatHtml.message(fromId, - fromUniqueId == null || fromUniqueId.isBlank() ? clientUniqueId : fromUniqueId, from, text)); + fromUniqueId == null || fromUniqueId.isBlank() ? clientUniqueId : fromUniqueId, from, text, + room())); } void setHistory(List htmlEntries) { entries.clear(); + pictureUrls.clear(); if (htmlEntries != null) { - for (String entry : htmlEntries) entries.add(ChatHtml.logEntry(entry)); + String room = room(); + for (String entry : htmlEntries) add(ChatHtml.logEntry(entry, room)); } render(); } @@ -535,10 +673,49 @@ public final class ChatPanel extends JPanel { /** Replaces the whole log with fixed content; used by static-content tabs. */ void setStaticContent(String html) { entries.clear(); + pictureUrls.clear(); entries.add(html); render(); } + private void add(String entry) { + entries.add(entry); + // Static content comes with its pictures already in place. + if (noteKey == null && DescriptionPictures.hasPictures(entry)) { + pictureUrls.addAll(DescriptionPictures.urls(entry)); + } + } + + /** The entry as drawn: its shared pictures as they stand now. */ + private String drawn(String entry) { + if (noteKey != null || !DescriptionPictures.hasPictures(entry)) return entry; + return pictures.html(entry, renderedPictureWidth, UIScale.scale(PICTURE_HEIGHT)); + } + + /** + * How wide a shared picture may be: the log's width inside its margins, in steps so that + * dragging a divider does not rebuild the log on every pixel. + */ + private int pictureWidth() { + int step = UIScale.scale(PICTURE_WIDTH_STEP); + int width = scroll.getViewport().getWidth() - UIScale.scale(24); + return Math.min(UIScale.scale(PICTURE_WIDTH), Math.max(step, width / step * step)); + } + + /** A picture came or failed: redrawn if it is one of this log's. */ + void picturesChanged() { + if (!pictureUrls.isEmpty() && !pictures.state(pictureUrls).equals(pictureState)) keepingScroll(); + } + + /** Redraws the log, staying where the reader is unless that is at the end. */ + private void keepingScroll() { + JScrollBar bar = scroll.getVerticalScrollBar(); + boolean atEnd = bar.getValue() + bar.getVisibleAmount() >= bar.getMaximum() - UIScale.scale(8); + Point at = scroll.getViewport().getViewPosition(); + render(); + if (!atEnd || search.isOpen()) SwingUtilities.invokeLater(() -> scroll.getViewport().setViewPosition(at)); + } + void showMatching(TextQuery filter) { if (Objects.equals(this.filter, filter)) return; this.filter = filter; @@ -550,20 +727,29 @@ public final class ChatPanel extends JPanel { } private void render() { + // Read before drawing, so a picture coming meanwhile still counts as a change. + pictureState = pictures.state(pictureUrls); + renderedPictureWidth = pictureWidth(); StringBuilder html = new StringBuilder(); for (String entry : entries) { - if (shows(entry)) html.append(entry); + if (shows(entry)) html.append(drawn(entry)); } log.setText("
" + html + "
"); log.setCaretPosition(noteKey != null ? 0 : log.getDocument().getLength()); } void append(String entry) { - entries.add(entry); - if (shows(entry)) { + boolean stale = !pictures.state(pictureUrls).equals(pictureState); + add(entry); + if (stale) { + // A picture already shown changed and is about to be redrawn; this joins it. + render(); + } else if (shows(entry)) { + pictureState = pictures.state(pictureUrls); + if (renderedPictureWidth == 0) renderedPictureWidth = pictureWidth(); try { HTMLDocument doc = (HTMLDocument) log.getDocument(); - doc.insertBeforeEnd(doc.getElement("chatlog"), entry); + doc.insertBeforeEnd(doc.getElement("chatlog"), drawn(entry)); // Following new lines would pull the view away from the match being read. if (!search.isOpen()) log.setCaretPosition(doc.getLength()); } catch (BadLocationException | IOException ignored) { diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/DescriptionPictures.java b/ts3-client/swing/src/main/java/com/ts3client/ui/DescriptionPictures.java index d95fe44..6683c36 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/DescriptionPictures.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/DescriptionPictures.java @@ -2,8 +2,10 @@ package com.ts3client.ui; import com.formdev.flatlaf.util.UIScale; import com.ts3client.config.Settings; +import com.ts3client.myts.ChatAttachment; import com.ts3client.net.PictureDownloads; import com.ts3client.text.BBCode; +import com.ts3client.text.ChatHtml; import javax.imageio.ImageIO; import javax.imageio.ImageReader; @@ -11,7 +13,9 @@ import javax.imageio.stream.ImageInputStream; import java.awt.Dimension; import java.io.File; import java.io.IOException; +import java.util.ArrayList; import java.util.Iterator; +import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; @@ -44,6 +48,11 @@ final class DescriptionPictures { /** @param maxWidth the widest a picture may be drawn */ String html(String html, int maxWidth) { + return html(html, maxWidth, Integer.MAX_VALUE); + } + + /** @param maxHeight the tallest a picture may be drawn */ + String html(String html, int maxWidth, int maxHeight) { StringBuilder out = new StringBuilder(); Matcher m = TAG.matcher(html); String anchor = null; @@ -53,7 +62,8 @@ final class DescriptionPictures { out.append(html, last, m.start()); last = m.end(); if (m.group(1) != null) { - out.append(picture(unescape(m.group(1)), anchor, href == null ? null : unescape(href), maxWidth)); + out.append(picture(unescape(m.group(1)), anchor, href == null ? null : unescape(href), + maxWidth, maxHeight)); } else if (m.group(2) != null) { anchor = m.group(); href = m.group(2); @@ -67,7 +77,30 @@ final class DescriptionPictures { return out.append(html.substring(last)).toString(); } - private String picture(String url, String anchor, String href, int maxWidth) { + /** The pictures {@code html} shows, by address. */ + static List urls(String html) { + List urls = new ArrayList<>(); + Matcher m = TAG.matcher(html); + while (m.find()) { + if (m.group(1) != null) urls.add(unescape(m.group(1))); + } + return urls; + } + + /** + * How the pictures stand, one letter each: it changes when one of them comes or fails, + * and asks for those not on their way yet. + */ + String state(List urls) { + if (!settings.descriptionPictures) return ""; + StringBuilder state = new StringBuilder(urls.size()); + for (String url : urls) { + state.append(downloads.get(url) != null ? 'y' : downloads.failed(url) ? 'n' : '-'); + } + return state.toString(); + } + + private String picture(String url, String anchor, String href, int maxWidth, int maxHeight) { if (!settings.descriptionPictures) return link("ICONVIEWER", url, anchor, href); File file = downloads.get(url); if (file == null) { @@ -77,28 +110,37 @@ final class DescriptionPictures { if (size.width <= 0 || size.height <= 0) return link("BROKEN_IMAGE", url, anchor, href); int width = Math.min(UIScale.scale(size.width), Math.max(1, maxWidth)); int height = (int) ((long) size.height * width / size.width); + if (height > maxHeight) { + height = Math.max(1, maxHeight); + width = Math.max(1, (int) ((long) size.width * height / size.height)); + } // Swing frames a picture inside a link unless told not to. return ""; } /** * The picture's address as a link behind {@code iconKey}, shortened: Swing never breaks a - * long one, so it would widen the view past its edge. Inside another link, that link is - * closed around it and shown after it, so it is not lost with the picture that carried it. + * long one, so it would widen the view past its edge; a file shared in chat goes by its + * name. Inside another link, that link is closed around it and shown after it, so it is + * not lost with the picture that carried it. */ private static String link(String iconKey, String url, String anchor, String href) { - String own = icon(iconKey) + "" - + BBCode.escape(BBCode.shortAddress(url)) + ""; + ChatAttachment.Ref attachment = ChatAttachment.Ref.parse(url); + String label = attachment != null ? attachment.fileName() : BBCode.shortAddress(url); + String linkClass = attachment != null ? ChatHtml.ATTACHMENT_CLASS : BBCode.linkClass(url); + // A link to the picture itself already is the link this would be. + if (anchor != null && href.equals(url)) return icon(iconKey) + BBCode.escape(label); + String own = icon(iconKey) + "" + + BBCode.escape(label) + ""; if (anchor == null) return own; - String outer = href.equals(url) ? "" : " " + anchor + BBCode.escape(href) + ""; - return "" + own + outer + anchor; + return "" + own + " " + anchor + BBCode.escape(href) + "" + anchor; } private static String icon(String key) { int size = UIScale.scale(ICON); File file = IconFiles.of(key, size); if (file == null) return ""; - return " "; + return " "; } /** The picture's size in pixels, read from its header; zero when it is no picture Swing can show. */ diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/DesktopNotifier.java b/ts3-client/swing/src/main/java/com/ts3client/ui/DesktopNotifier.java index 113c53d..b7ca558 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/DesktopNotifier.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/DesktopNotifier.java @@ -6,6 +6,7 @@ import com.ts3client.notify.desktop.DesktopNotifications; import com.ts3client.notify.desktop.DesktopNotifications.Notice; import com.ts3client.notify.desktop.FreedesktopNotifications; import com.ts3client.text.BBCode; +import com.ts3client.text.ChatHtml; import com.ts3client.ui.tray.AwtTray; import javax.swing.SwingUtilities; @@ -74,7 +75,7 @@ final class DesktopNotifier { void privateMessage(ServerTab tab, int clientId, String from, String message) { if (!wanted()) return; - String text = BBCode.toPlain(message); + String text = ChatHtml.plainMessage(message); Conversation key = new Conversation(tab, clientId); worker.execute(() -> { DesktopNotifications out = backend(); diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/HtmlStyles.java b/ts3-client/swing/src/main/java/com/ts3client/ui/HtmlStyles.java index a471c94..b4cc25c 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/HtmlStyles.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/HtmlStyles.java @@ -2,6 +2,7 @@ package com.ts3client.ui; import com.formdev.flatlaf.util.UIScale; import com.ts3client.text.BBCode; +import com.ts3client.text.ChatHtml; import javax.swing.JEditorPane; import javax.swing.JViewport; @@ -106,6 +107,8 @@ final class HtmlStyles { // External links are underlined so they can't be mistaken for an identity. css.addRule("a." + BBCode.EXTERNAL_LINK_CLASS + " { color:" + hex(Theme.link()) + "; text-decoration:underline; }"); + css.addRule("a." + ChatHtml.ATTACHMENT_CLASS + + " { color:" + hex(Theme.link()) + "; text-decoration:underline; }"); kit.setStyleSheet(css); pane.setEditorKit(kit); diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java b/ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java index a8150a5..45db329 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java @@ -10,6 +10,7 @@ import com.ts3client.config.Bookmark; import com.ts3client.config.Bookmarks; import com.ts3client.config.IdentityStore; import com.ts3client.config.Settings; +import com.ts3client.myts.ChatAttachments; import com.ts3client.myts.MyTeamSpeakLogin; import com.ts3client.teamspeak.TeamSpeakImporter; import com.ts3client.contacts.ContactStore; @@ -68,6 +69,8 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { private final ContactStore contacts = ContactStore.load(); private final AudioBackend audio = new DesktopAudioBackend(); private final PictureDownloads pictures = new PictureDownloads(new File(AppDirs.profile(), "pictures"), true); + /** Files shared in chat, kept in the myTeamSpeak account's cloud storage. */ + private final ChatAttachments attachments = new ChatAttachments(myTeamSpeak); private final TextZoom chatZoom; private final TextZoom infoZoom; /** Sound pack playback, shared by every connection. */ @@ -122,6 +125,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { this.soundPlayer = audio.createSoundPlayer(settings); this.sounds.setPlayer(soundPlayer); this.notifier = new DesktopNotifier(this, settings); + pictures.addSource("tsattach:", attachments::fetchPicture); // Any of the client's windows coming to the front counts, a dialog included. KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("activeWindow", e -> { if (e.getNewValue() != null) notifier.windowActivated(); @@ -931,6 +935,12 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { hotkeys.dispose(); if (tray != null) tray.dispose(); notifier.shutdown(); + // Ends the sharing session if myTeamSpeak answers soon; it expires on its own otherwise. + try { + Thread.ofVirtual().start(attachments::close).join(2000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } } /** Leaves every server and ends the process. */ @@ -983,7 +993,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { selected == null ? null : selected.connection().getPlayback(), sounds, hotkeys, new MyTeamSpeakPanel(myTeamSpeak, new TeamSpeakImporter(identities, bookmarks, settings), - menuBar::rebuildBookmarks), + menuBar::rebuildBookmarks, this::myTeamSpeakChanged), () -> { applyOutputSettingsToAllTabs(); contactsChanged(); @@ -991,6 +1001,26 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { dlg.setVisible(true); } + /** Signed in to or out of myTeamSpeak: sharing in chat follows. */ + private void myTeamSpeakChanged() { + boolean signedIn = myTeamSpeak.isSignedIn(); + for (ServerTab tab : tabs) tab.chat().setSharingAvailable(signedIn); + if (signedIn) { + pictures.retryFailed(); + } else { + Thread.ofVirtual().name("myteamspeak-sign-out").start(attachments::close); + } + } + + ChatAttachments attachments() { + return attachments; + } + + /** Whether files can be shared in chat: that needs a myTeamSpeak account. */ + boolean canShareFiles() { + return myTeamSpeak.isSignedIn(); + } + /** Master volume, output device and receive buffer are global, so push them to every open connection. */ private void applyOutputSettingsToAllTabs() { soundPlayer.setOutputDevice(settings.outputDevice); diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/MyTeamSpeakPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/MyTeamSpeakPanel.java index c9e5c02..811ec7f 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/MyTeamSpeakPanel.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/MyTeamSpeakPanel.java @@ -45,6 +45,8 @@ final class MyTeamSpeakPanel extends JPanel { private final MyTeamSpeakLogin login; private final TeamSpeakImporter importer; private final Runnable onImported; + /** Runs when the client signs in or out, the saved sign-in being turned away included. */ + private final Runnable onSignInChanged; private final CardLayout cards = new CardLayout(); @@ -63,10 +65,12 @@ final class MyTeamSpeakPanel extends JPanel { private List accountItems = List.of(); private boolean fetched; - MyTeamSpeakPanel(MyTeamSpeakLogin login, TeamSpeakImporter importer, Runnable onImported) { + MyTeamSpeakPanel(MyTeamSpeakLogin login, TeamSpeakImporter importer, Runnable onImported, + Runnable onSignInChanged) { this.login = login; this.importer = importer; this.onImported = onImported; + this.onSignInChanged = onSignInChanged; setLayout(cards); add(buildSignedOut(), SIGNED_OUT); add(buildSignedIn(), SIGNED_IN); @@ -163,6 +167,7 @@ final class MyTeamSpeakPanel extends JPanel { status(signInStatus, " ", false); showState(); showItems(result); + onSignInChanged.run(); }); }, message -> { setSignInBusy(false); @@ -180,6 +185,7 @@ final class MyTeamSpeakPanel extends JPanel { fetched = false; email.setText(""); showState(); + onSignInChanged.run(); } private void fetch() { @@ -198,7 +204,10 @@ final class MyTeamSpeakPanel extends JPanel { status(dataStatus, message, true); // A rejected sign-in has signed out. showState(); - if (!login.isSignedIn()) status(signInStatus, message, true); + if (!login.isSignedIn()) { + status(signInStatus, message, true); + onSignInChanged.run(); + } }); } diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/PictureViewer.java b/ts3-client/swing/src/main/java/com/ts3client/ui/PictureViewer.java new file mode 100644 index 0000000..263f206 --- /dev/null +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/PictureViewer.java @@ -0,0 +1,78 @@ +package com.ts3client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.KeyStroke; +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.GraphicsConfiguration; +import java.awt.Image; +import java.awt.Rectangle; +import java.awt.Window; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.image.BufferedImage; + +/** A picture at full size, or as large as the screen allows, with a way to save it. */ +final class PictureViewer extends JDialog { + + private static final int MIN_WIDTH = 360; + private static final int MIN_HEIGHT = 240; + + PictureViewer(Window owner, String title, BufferedImage picture, Runnable onSave) { + super(owner, title, ModalityType.MODELESS); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + + JLabel view = new JLabel(new ImageIcon(fitted(picture, owner))); + view.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + dispose(); + } + }); + JScrollPane scroll = new JScrollPane(view); + scroll.setBorder(null); + + JButton save = new JButton("Save…"); + save.addActionListener(e -> onSave.run()); + JButton close = new JButton("Close"); + close.addActionListener(e -> dispose()); + JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT, UIScale.scale(4), 0)); + buttons.setBorder(new ScaledEmptyBorder(6, 6, 6, 6)); + buttons.add(save); + buttons.add(close); + + add(scroll, BorderLayout.CENTER); + add(buttons, BorderLayout.SOUTH); + getRootPane().registerKeyboardAction(e -> dispose(), KeyStroke.getKeyStroke("ESCAPE"), + JComponent.WHEN_IN_FOCUSED_WINDOW); + getRootPane().setDefaultButton(close); + pack(); + // A small picture still gets a window its title and buttons fit in. + setSize(Math.max(getWidth(), UIScale.scale(MIN_WIDTH)), Math.max(getHeight(), UIScale.scale(MIN_HEIGHT))); + setLocationRelativeTo(owner); + } + + /** The picture narrowed to most of the owner's screen; small ones are left as they are. */ + private static Image fitted(BufferedImage picture, Window owner) { + GraphicsConfiguration gc = owner != null ? owner.getGraphicsConfiguration() : null; + Rectangle screen = gc != null ? gc.getBounds() : new Rectangle(new Dimension(1280, 800)); + int maxWidth = screen.width * 85 / 100; + int maxHeight = screen.height * 75 / 100; + int width = picture.getWidth(); + int height = picture.getHeight(); + double scale = Math.min(1, Math.min(maxWidth / (double) width, maxHeight / (double) height)); + if (scale >= 1) return picture; + return picture.getScaledInstance(Math.max(1, (int) (width * scale)), Math.max(1, (int) (height * scale)), + Image.SCALE_SMOOTH); + } +} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTab.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTab.java index 48c41f2..4276ccb 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTab.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTab.java @@ -79,7 +79,7 @@ final class ServerTab { this.session = new ServerSession(settings, identities, audio, sounds, contacts, events); this.conn = session.connection(); this.groupIcons = new GroupIcons(conn.getIcons()); - this.chatPanel = new ChatPanel(host.chatZoom()); + this.chatPanel = new ChatPanel(host.chatZoom(), settings, pictures, conn::serverUniqueId); this.treeActions = new ServerTabTreeActions(host, this, conn, chatPanel, infoPanel, groupIcons); this.treePanel = new ServerTreePanel(conn.getModel(), groupIcons, contacts, settings, treeActions); treeActions.attach(treePanel); @@ -102,6 +102,8 @@ final class ServerTab { showOfflineMessages(); } }); + chatPanel.setAttachmentHandler(new ChatAttachmentActions(host, session, chatPanel, pictures, ServerTab::scope)); + chatPanel.setSharingAvailable(host.canShareFiles()); chatPanel.setInputEnabled(false); infoPanel.setDescriptionHandler(new InfoPanel.DescriptionHandler() { @@ -322,12 +324,15 @@ final class ServerTab { // ---- chat ---- private void onSendChat(ChatPanel.Target target, int clientId, String text) { - ChatScope scope = switch (target) { + session.sendChat(scope(target), clientId, text); + } + + private static ChatScope scope(ChatPanel.Target target) { + return switch (target) { case SERVER -> ChatScope.SERVER; case PRIVATE -> ChatScope.PRIVATE; default -> ChatScope.CHANNEL; }; - session.sendChat(scope, clientId, text); } /** Opens the file repository browser for a channel, as the "Browse Files" hotkey/menu action does. */