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++;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user