Share pictures and files in chat, the way TeamSpeak 6 does
A shared file goes to the sender's myTeamSpeak cloud storage, and an ordinary text message carries TeamSpeak 6's ts.file.myts pointer to it, so TeamSpeak 6 users see the file and we see theirs. Pictures show inline through the description picture cache, other files as a link to save; logged history shows them too. Sharing and fetching need a myTeamSpeak sign-in. Desktop: share button, drop or paste files and pictures, a picture viewer. Android: attach from the system picker, tap to view or save. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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.
|
||||
*
|
||||
* <p>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 @<myTeamSpeak ID>:<host>}
|
||||
* @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<String, Object> 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);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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<SyncItem> 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());
|
||||
|
||||
@@ -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 = "";
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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> {
|
||||
T run(MyTeamSpeak.Session session) throws IOException, MyTsException;
|
||||
}
|
||||
|
||||
private <T> T withSession(Request<T> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Runnable> listeners = new CopyOnWriteArrayList<>();
|
||||
private final Set<String> pending = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> failed = ConcurrentHashMap.newKeySet();
|
||||
private final Map<String, Source> 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<String, Source> 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);
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 <div>} 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("(<span class=\"TextMessage_Text\">)(.*?)(</span>)",
|
||||
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
|
||||
? "<a class=\"" + BBCode.IDENTITY_LINK_CLASS + "\" href=\""
|
||||
+ BBCode.escape(TsLink.clientHref(fromId, fromUniqueId == null ? "" : fromUniqueId, from))
|
||||
+ "\">" + name + "</a>"
|
||||
: 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() ? "" : "<br>" + BBCode.escape(attachment.caption());
|
||||
if (room == null || room.isBlank()) return span(ATTACHMENT_CLASS, name) + caption;
|
||||
String href = BBCode.escape(attachment.href(room));
|
||||
String open = "<a class=\"" + ATTACHMENT_CLASS + "\" href=\"" + href + "\">";
|
||||
if (attachment.isImage() && attachment.fileSize() <= ChatAttachments.MAX_PREVIEW_BYTES) {
|
||||
return "<br>" + open + "<img src=\"" + href + "\"></a>" + caption;
|
||||
}
|
||||
String size = attachment.fileSize() >= 0 ? " " + span(MUTED_CLASS, "(" + size(attachment.fileSize()) + ")") : "";
|
||||
return open + name + "</a>" + 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)<img\\b[^>]*>", "")
|
||||
.replaceFirst("(?i)^\\s*<p\\b", "<div")
|
||||
.replaceFirst("(?i)</p>\\s*$", "</div>");
|
||||
normalized = withAttachment(normalized, room);
|
||||
return normalized.startsWith("<div") ? normalized : div(normalized);
|
||||
}
|
||||
|
||||
/** The log entry with the message text that points to a shared file replaced by the file. */
|
||||
private static String withAttachment(String html, String room) {
|
||||
Matcher m = LOG_TEXT.matcher(html);
|
||||
if (!m.find()) return html;
|
||||
ChatAttachment attachment = ChatAttachment.parse(HtmlText.plain(m.group(2)));
|
||||
if (attachment == null) return html;
|
||||
return html.substring(0, m.start(2)) + attachment(attachment, room) + html.substring(m.end(2));
|
||||
}
|
||||
|
||||
/** A file size as people read it. */
|
||||
static String size(long bytes) {
|
||||
if (bytes < 1024) return bytes + " B";
|
||||
if (bytes < 1024 * 1024) return String.format(Locale.ROOT, "%.0f KB", bytes / 1024.0);
|
||||
return String.format(Locale.ROOT, "%.1f MB", bytes / (1024.0 * 1024));
|
||||
}
|
||||
|
||||
private static String stamp() {
|
||||
return "[" + TIME.format(LocalTime.now()) + "] ";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
package com.ts3client.text;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Just enough JSON for the small objects other clients put into chat messages: values
|
||||
* come back as {@link String}, {@link Double}, {@link Boolean}, {@code null},
|
||||
* {@link List} and {@link Map}.
|
||||
*/
|
||||
public final class Json {
|
||||
|
||||
private final String src;
|
||||
private int pos;
|
||||
|
||||
private Json(String src) {
|
||||
this.src = src;
|
||||
}
|
||||
|
||||
/** @return the object {@code text} holds, or {@code null} when it is not a JSON object */
|
||||
public static Map<String, Object> parseObject(String text) {
|
||||
if (text == null) return null;
|
||||
try {
|
||||
Json json = new Json(text);
|
||||
json.skipSpace();
|
||||
if (json.peek() != '{') return null;
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> object = (Map<String, Object>) 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<String, Object> object() {
|
||||
Map<String, Object> 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<Object> array() {
|
||||
List<Object> 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++;
|
||||
}
|
||||
}
|
||||
@@ -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(" "));
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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"));
|
||||
}
|
||||
}
|
||||
@@ -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("<img src=\"" + PICTURE.href(ROOM) + "\">"), 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</a>"), html);
|
||||
assertTrue(html.contains("(3.0 MB)"), html);
|
||||
}
|
||||
|
||||
@Test
|
||||
void namesTheFileWhereItCannotBeFetched() {
|
||||
String html = ChatHtml.message(5, "uid", "alice", PICTURE.toMessage());
|
||||
assertFalse(html.contains("<img"), html);
|
||||
assertTrue(html.contains("cat.png"), html);
|
||||
}
|
||||
|
||||
@Test
|
||||
void showsTheFileInLogHistory(@TempDir Path temp) throws Exception {
|
||||
ChatLogStore logs = new ChatLogStore(temp, ROOM);
|
||||
logs.appendMessage(ChatLogScope.CHANNEL, false, 5, "uid", "alice", PICTURE.toMessage());
|
||||
List<String> history = logs.channelHtmlHistory();
|
||||
String html = ChatHtml.logEntry(history.get(history.size() - 1), ROOM);
|
||||
assertTrue(html.contains("<img src=\"" + PICTURE.href(ROOM) + "\">"), html);
|
||||
assertFalse(html.contains("msg_type"), html);
|
||||
}
|
||||
|
||||
@Test
|
||||
void previewsAFileByItsName() {
|
||||
assertEquals("cat.png", ChatHtml.plainMessage(PICTURE.toMessage()));
|
||||
assertEquals("hi", ChatHtml.plainMessage("[b]hi[/b]"));
|
||||
}
|
||||
}
|
||||
@@ -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<File> 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<File> 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<File> files(Transferable t) throws UnsupportedFlavorException, IOException {
|
||||
if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
|
||||
return new ArrayList<>((List<File>) t.getTransferData(DataFlavor.javaFileListFlavor));
|
||||
}
|
||||
List<File> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<ChatPanel.Target, ChatScope> scopes;
|
||||
|
||||
ChatAttachmentActions(MainFrame host, ServerSession session, ChatPanel chat, PictureDownloads pictures,
|
||||
Function<ChatPanel.Target, ChatScope> 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<File> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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<File> 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<String> 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<String> 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<File> 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<String> 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<String> 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("<html><body><div id=\"chatlog\"></div></body></html>");
|
||||
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<String> 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><body><div id=\"chatlog\">" + html + "</div></body></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) {
|
||||
|
||||
@@ -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<String> urls(String html) {
|
||||
List<String> 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<String> 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 "<img src='" + file.toURI() + "' width='" + width + "' height='" + height + "' border='0'>";
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) + "<a class=\"" + BBCode.linkClass(url) + "\" href=\"" + BBCode.escape(url) + "\">"
|
||||
+ BBCode.escape(BBCode.shortAddress(url)) + "</a>";
|
||||
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) + "<a class=\"" + linkClass + "\" href=\"" + BBCode.escape(url) + "\">"
|
||||
+ BBCode.escape(label) + "</a>";
|
||||
if (anchor == null) return own;
|
||||
String outer = href.equals(url) ? "" : " " + anchor + BBCode.escape(href) + "</a>";
|
||||
return "</a>" + own + outer + anchor;
|
||||
return "</a>" + own + " " + anchor + BBCode.escape(href) + "</a>" + anchor;
|
||||
}
|
||||
|
||||
private static String icon(String key) {
|
||||
int size = UIScale.scale(ICON);
|
||||
File file = IconFiles.of(key, size);
|
||||
if (file == null) return "";
|
||||
return "<img src='" + file.toURI() + "' width='" + size + "' height='" + size + "'> ";
|
||||
return "<img src='" + file.toURI() + "' width='" + size + "' height='" + size + "' border='0'> ";
|
||||
}
|
||||
|
||||
/** The picture's size in pixels, read from its header; zero when it is no picture Swing can show. */
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<SyncItem> 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();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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. */
|
||||
|
||||
Reference in New Issue
Block a user